Creating N nested for-loops

2019-01-18 12:29发布

Is there a way to create for-loops of a form

for(int i = 0; i < 9; ++i) {
    for(int j = 0; j < 9; ++i) {
    //...
        for(int k = 0; k < 9; ++k) { //N-th loop

without knowing N at the compile time. Ideally I'm trying to figure out a way to loop through separate elements of a vector of digits to create each possible number if a certain amount of digits is replaced with different digits.

7条回答
forever°为你锁心
2楼-- · 2019-01-18 13:26

You can use recursive call as:

void runNextNestedFor(std::vector<int> counters, int index)
{
     for(counters[index] = 0; counters[index] < 9; ++counters[index]) {
       // DO
       if(index!=N)
          runNextNestedFor(counters, index+1);
     }
}

Call it first time as:

std::vectors<int> counters(N);
runNextNestedFor(counters, 0);
查看更多
登录 后发表回答