在递归函数中打印一次变量,每次递归都会不断变化 我在C++中有一个空白>代码>函数。它是递归的。在每次递归过程中,我传递一个在函数中更新的向量。我只想在向量完全脱离函数时打印它。但是,如果我只是在函数的末尾打印向量,那么每次它退出递归时都会打印出来。我是否可以应用任何条件以确保打印只发生一次(在第一次函数调用结束时)

在递归函数中打印一次变量,每次递归都会不断变化 我在C++中有一个空白>代码>函数。它是递归的。在每次递归过程中,我传递一个在函数中更新的向量。我只想在向量完全脱离函数时打印它。但是,如果我只是在函数的末尾打印向量,那么每次它退出递归时都会打印出来。我是否可以应用任何条件以确保打印只发生一次(在第一次函数调用结束时),c++,recursion,C++,Recursion,我真的不想将函数返回类型从“void”更改为任何内容。是有办法还是不可能 编辑: 代码如下所示 void myClass::shortestPath(string* ar, int dim[2], vector<vector < int > > & path, vector<int > & minPath) { if (condition) { #some code to update path and minPath

我真的不想将函数返回类型从“
void
”更改为任何内容。是有办法还是不可能

编辑: 代码如下所示

void myClass::shortestPath(string* ar, int dim[2], vector<vector < int > > & path, vector<int > & minPath) {
    if (condition) {
        #some code to update path and minPath
        shortestPath(ar,dim,path, minPath);
    }
    #I cannot print minPath here because it will print each time it returns
    return;

}
void myClass::最短路径(string*ar,int dim[2],vector>&path,vector&minPath){
如果(条件){
#更新path和minPath的一些代码
最短路径(ar、dim、path、minPath);
}
#我不能在这里打印minPath,因为它每次返回时都会打印
返回;
}

最简单的方法是创建第二个函数:

void mainFunction(vector<...> &v) {
    prepareVector(v);
    printVector(v);
}

void prepareVector(vector<...> &v) {
    //your recursive code here
}

在第二个选项中,当您递归调用第二个参数为false的函数时,变量
first
是否会设置为“false”?(因为函数接收的第二个参数是变量
first
)@DarshilChauhan是的,这就是问题所在:递归调用没有打印。我在第一次调用中问,
first
是真的。然后,当递归调用函数时,
first
设置为false。在所有的递归过程中都是这样。它再也不会变成现实。当函数退出所有递归(返回到第一个调用)并到达用于打印的
if
语句时,
first
将为false,对吗?否,它将为
true
。没有对变量
first
的引用,每个递归调用都有它自己的副本。因此,使用更改的值进行调用不会更改当前调用的值。
void recursiveFunction(vector<...> &v, bool first=true) {
    ...
    recursiveFunction(v, false);
    ...
    if(first) {
        printVector(v);
    }
}
void myClass::shortestPath(string* ar, int dim[2], vector<vector < int > > & path, vector<int > & minPath) {
    if (condition) {
        #some code to update path and minPath
        shortestPath(ar,dim,path, minPath);
        return;
    }
    // now you can print it here we terminate calls before this line
    // if condition is true
    return;
}
while(condition) {
    #some code to update path and minPath
}