gpt4 book ai didi

c - 其间有代码的 for 循环的可变数量

转载 作者:行者123 更新时间:2023-11-30 18:50:35 25 4
gpt4 key购买 nike

所以我遇到的问题是我想通过以下方式实现 N 个 for 循环(其中 N 是一个变量):

for i0=0:MAX
cOR[0] = initial + move[i0];
for i1=0:MAX
cOR[1] = cOR[0] + move[i1];
....
some other stuff inside the final loop

(cOR是长度等于for循环数的 vector )

因此,我发现这个解决方案在您只有嵌套循环( https://stackoverflow.com/a/20577981/3932908 )时有效,但一直在努力针对我的特定情况(需要在 for 循环之间添加代码)修改它。是否有一种简单的方法来实现这一点,或者是否需要不同的方法?

最佳答案

一般方法是

  1. 编写一个递归函数。
  2. 如果由于某种原因递归不适合您的代码(例如,递归深度很长,或者需要暂停执行的能力),则可以通过对堆栈进行显式建模,将递归版本转换为迭代版本。

做 1 很容易:

void f(int depth, int initial, int *cOR)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
return;
}

for(int i = 0; i < MAX; ++i)
{
cOR[depth] = initial + move[i];
f(depth+1, cOR[depth]);
}
}

并这样调用它:

f(0, initial, cOR);

现在我们进入第 2 步,即转换为非递归版本。我们需要的额外状态是之前存储在堆栈上的内容:i 变量的值。那么我们开始吧:

int i[max_depth];
int depth = 0;

for(;;)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...

do {
if(--depth < 0)
return;
} while(++i[depth] >= MAX);
}
else
i[depth] = 0;

cOR[depth] = (depth > 0 ? cOR[depth-1] : initial) + move[i[depth]];
++depth;
}

如果您无法先验估计 max_depth,那么您可以切换到根据需要增长的动态分配数组。

关于c - 其间有代码的 for 循环的可变数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39750058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com