问题描述
我想编写一个函数来执行以下操作,给函数int K
和int nest_level
两个参数,生成所有可能的点,这些点是由于创建nest_level
嵌套循环而产生的,每个循环的范围从-K
K
.例如,如果k = 5
和nest_level = 3
,该函数将打印以下内容产生的数字序列:
I would like to write a function to do the following, given two arguments to the function int K
and int nest_level
generate all possible points that result from creating nest_level
nested loops where each loop ranges from -K
to K
. For example if k = 5
and nest_level = 3
the function prints the sequences of numbers that result from the following:
for(int i = -k; i <= k; ++i)
for(int j = -k; j <= k; ++j)
for(int m = -k; m <= k; ++m)
print(i, j, k)
这适用于任何K
和nest_level
从我的研究中,我理解这应该是一个递归解决方案,但是我很难专门在C ++中实现它.
From my research, I understand this should be a recursive solution but i'm having difficulty implementing it specifically in C++.
推荐答案
使用std::vector
.通过引用.在i从-k到k的循环中:
Use a std::vector
. Pass it by reference. In a loop of i from -k to k:
-
将
i
推入其中.
如果向量的长度等于嵌套级别,请打印.
If length of vector equals nest level, print.
否则,递归,通过引用传递向量.
Otherwise, recurse, passing in the vector by reference.
现在,从向量的末端弹出最后一个元素,然后继续循环.
Now, pop the last element off the end of the vector, and continue the loop.
这篇关于生成N个嵌套的for循环的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!