我在一个递归函数中有一个for循环。我的代码中的索引i在for循环每次完成时都会更改,但是在递归开始时它会重置。有没有可能通过另一个变量或类似的东西保存该值?我需要一个变量来保持第一个递归步骤的'i‘值(或者更确切地说,是我在任何递归开始之前拥有的'i’值)。我的实际代码看起来相当复杂,所以我只是粘贴了一个示例代码来解释我的问题。
我尝试过使用其他变量,也包括全局变量。不幸的是,每当递归发生时,它们也会发生变化,因为我需要以某种方式将'i‘值保存到它们中。
int array[2][10];
void function(){
int x = 1;
for (int i = 0; i < 10; i++){
//Something happens here... (The base cases are in here)
for (int j = 0; j < 10; j++){
//Something happens here...(More base cases are in here)
array[0][x] += i; //When function() starts, i is 0. I need it to
//remain 0, while it
//runs through all the recursion steps (limited
//by a recursion counter).
//After the recursion returns to the first level,
//the for loop will continue.
//'i' will be 1 and then I need this value to
//stay the same throughout all the
//recursion steps once again. How do I do that?
//Recursion
function();
}
}
}我希望'i‘保持不变,但是每次递归重新启动for循环时,它都会被重置。
发布于 2019-01-17 03:37:35
听起来您可能想要将i循环移出function,然后将其传递进来。
例如,如果你有这样的东西:
void someOtherFunction()
{
function();
}
void function(){
int x = 1;
for (int i = 0; i < 10; i++){
//Something happens here...
for (int j = 0; j < 10; j++){
//Something happens here...
array[0][x] += i;
//Recursion
function();
}
}
}您可以将其更改为:
void someOtherFunction()
{
for (int i=0; i<10; ++i)
function(i);
}
void function(int i){
int x = 1;
//Something happens here...
for (int j = 0; j < 10; j++){
//Something happens here...
array[0][x] += i;
//Recursion
function(i);
}
}在这种情况下,i可能有一个更好、更具描述性的名称。
https://stackoverflow.com/questions/54223966
复制相似问题