我今天早些时候遇到了这个问题,我想我可能会分享我最终想出的解决方案。我不确定这里关于回复旧帖子的政策是什么。我只是在今天早上遇到这个问题的事实,这种事情对我很有用。
为了提高效率,我避免了递归。此外,它不使用任何特定的 c++ 东西——它也可以在 C 上正常工作。
我们正在尝试创建 N 个嵌套的“for”循环。
而不是使用
for(int i = 0; i<max; i++)
for (int j = 0; j<max; j++)
...
我将 i, j, ... 替换为一个数组:i[0], i[1], ..., i[n-1]。
这是我的解决方案:
const int n = /*Insert N here: how many loops do you need?*/;
int i[n+1]; // if "n" is not known before hand, then this array will need to be created dynamically.
//Note: there is an extra element at the end of the array, in order to keep track of whether to exit the array.
for (int a=0; a<n+1; a++) {
i[a]=0;
}
int MAX = 79; //That's just an example, if all of the loops are identical: e.g. "for(int i=0; i<79; i++)". If the value of MAX changes for each loop, then make MAX an array instead: (new) int MAX [n]; MAX[0]=10; MAX[1]=20;...;MAX[n-1]=whatever.
int p = 0; //Used to increment all of the indicies correctly, at the end of each loop.
while (i[n]==0) {//Remember, you're only using indicies i[0], ..., i[n-1]. The (n+1)th index, i[n], is just to check whether to the nested loop stuff has finished.
//DO STUFF HERE. Pretend you're inside your nested for loops. The more usual i,j,k,... have been replaced here with i[0], i[1], ..., i[n-1].
//Now, after you've done your stuff, we need to increment all of the indicies correctly.
i[0]++;
// p = 0;//Commented out, because it's replaced by a more efficient alternative below.
while(i[p]==MAX) {//(or "MAX[p]" if each "for" loop is different. Note that from an English point of view, this is more like "if(i[p]==MAX". (Initially i[0]) If this is true, then i[p] is reset to 0, and i[p+1] is incremented.
i[p]=0;
i[++p]++; //increase p by 1, and increase the next (p+1)th index
if(i[p]!=MAX)
p=0;//Alternatively, "p=0" can be inserted above (currently commented-out). This one's more efficient though, since it only resets p when it actually needs to be reset!
}
}
就这些了。希望 cmets 清楚地表明它的目的是什么。我认为它应该非常有效 - 几乎与真正的嵌套 for 循环一样多。大部分开销在一开始都是一次性的,所以这应该比使用递归函数等更有效(如果我在这一点上错了,请纠正我)。
希望有一天它对某人有用。
和平与爱。