Creating N nested for-loops

后端 未结 7 1987
终归单人心
终归单人心 2020-12-03 11:16

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; +         


        
7条回答
  •  庸人自扰
    2020-12-03 11:43

    You can use recursive call as:

    void runNextNestedFor(std::vector 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 counters(N);
    runNextNestedFor(counters, 0);
    

提交回复
热议问题