variable nested for loops

前端 未结 6 1658
南旧
南旧 2020-12-01 20:15

I\'m trying to figure out how I can use recursion to do n-level nested for loops. For example, if n=3, there would be 3 \'levels\'

for(z=0;z<6;z++){
   fo         


        
6条回答
  •  庸人自扰
    2020-12-01 20:35

    You could write it like this, but... I wouldn't. It's confusing code and doesn't give you any benefits. If you want it because your true use case has a high number of nested loops, consider just not doing that, instead; it's a serious design smell.

    void nested_loop(const int levels, const int comparator, const int level = 0, const int accumulator = 0)
    {
       if (level < levels) {
          for (int i = 0; i < 6; i++) {
             nested_loop(levels, comparator, level + 1, accumulator + i);
          }
       }
       else {
          if (accumulator == comparator) {   // your if (z+y+x==f)
             //do something
          }
       }
    }
    
    int main() {
       const int levels = 3;
       const int f = 42;
    
       nested_loop(levels, f);
    }
    

    Live demo.

提交回复
热议问题