c++ - 变量嵌套 for 循环

标签 c++ for-loop nested

我试图弄清楚如何使用递归来执行 n 级嵌套 for 循环。
例如,如果 n=3,则将有 3 个“级别”

         if (z+y+x==f){
            //do something


我似乎无法弄清楚如何将 if 循环放在最后一个 for 循环中,以及如何从 if 语句访问先前 for 循环的变量。我知道变量嵌套循环的问题已经被问过很多次了,我已经浏览了所有这些问题。但似乎没有人帮助我。

有人可以提出一种使用递归来实现这一目标的简单方法,请记住我仍然是 C++ 的初学者,为我指明正确的方向吗?


Write a program to input the number of dice m. The program will output the total number of possible cases, the number of possible cases for each possible n and the n with the highest probability. Note: only one input m is read in. n is computed by the program

Example if user enters m=2 then program should output

The total number of possible cases is 36.
The possibilities are
2 1
3 2
4 3
12 1



为了效率,我避免了递归。此外,它不使用任何特定的 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++) {

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.
  // 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]++; //increase p by 1, and increase the next (p+1)th index
      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!

那里,仅此而已。希望评论能说明它的意图。我认为它应该非常有效 - 几乎和真正的嵌套 for 循环一样有效。大部分开销一开始都是一次性的,所以这应该比使用递归函数等更有效(如果我在这一点上错了,请纠正我)。



关于c++ - 变量嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9555864/


javascript - 如何减少执行JavaScript代码的时间

javascript - 在Javascript中遍历表格单元格ID

python - 将带有 parent 的对象的字典转换为带有 child 的嵌套字典

ruby-on-rails - 嵌套 form_for 单一资源

c++ - 如何在 C++ 中处理 -nan 输出

java - 初始化语句

c++ - 对RTTI raw_name()的好奇心


c++ - C++ 是否提供线程安全的引用计数器?

c++ - libtorch中的np.delete等效于什么?