gpt4 book ai didi

c++ - 你能在 C++ 中动态创建 for 循环吗?

转载 作者:行者123 更新时间:2023-11-27 23:47:46 26 4
gpt4 key购买 nike

我的问题在代码中有注释,有什么办法可以实现我想要的吗?

#include <iostream>

int main()
{
std::cin >> n_loops; //I want to specify the number of nested loops and create new variables dynamically:
// variables names: x1, x2, x3, ... x(n_loops)
// if n_loops is 3, for example, I want this code to be executed.
for (int x1 = 0; x1 < 10; x1++)
for (int x2 = 0; x2 < 10; x2++)
for (int x3 = 0; x3 < 10; x3++)
{
std::cout << x1 << ", " << x2 << ", " << x3 << std::endl;
}
std::cin.get();
}

最佳答案

不是直接的,但是你可以像这样实现“里程表式”的行为:

#include <iostream>
#include <vector>

static bool AdvanceOdometer(std::vector<int> & counters, int idxToIncrement, int counter_max)
{
if (++counters[idxToIncrement] == counter_max)
{
if (idxToIncrement == 0) return false; // signal that we've reached the end of all loops

counters[idxToIncrement] = 0;
return AdvanceOdometer(counters, idxToIncrement-1, counter_max);
}
return true;
}

int main()
{
int n_loops;
std::cin >> n_loops;

std::vector<int> counters;
for (size_t i=0; i<n_loops; i++) counters.push_back(0);

const int counter_max = 10; // each "digit" in the odometer should roll-over to zero when it reaches this value
while(true)
{
std::cout << "count: ";
for (size_t i=0; i<n_loops; i++) std::cout << counters[i] << " ";
std::cout << std::endl;

if (AdvanceOdometer(counters, counters.size()-1, counter_max) == false) break;
}
return 0;
}

同样的概念纯粹迭代地表达(一些读者可能会觉得这样更清楚,并且它避免了递归调用可能的边际效率低下)可以像这样:

#include <iostream>
#include <string> // std::stoi
#include <vector> // std::vector
using namespace std;

auto advance( vector<int> & digits, int const radix )
-> bool // true => advanced without wrapping back to all zeroes.
{
for( int& d : digits )
{
++d;
if( d < radix ) { return true; }
d = 0;
}
return false;
}

auto main( int n_args, char** args )
-> int
{
int const n_loops = stoi( args[1] );
std::vector<int> digits( n_loops );

const int radix = 10;

do
{
for( int i = digits.size() - 1; i >= 0; --i )
{
cout << digits[i] << " ";
}
cout << std::endl;
} while( advance( digits, radix ) );
}

关于c++ - 你能在 C++ 中动态创建 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com