在递归函数中打印一次变量,该变量会随着每次递归而不断变化

Print a variable Once in a Recursive Function, which keeps changing with each Recursion

本文关键字:变量 递归 变化 打印 递归函数 一次      更新时间:2023-10-16

我在 c++ 中有一个void函数。它是递归的。在每次递归期间,我都会传递一个在函数中更新的向量。我只想在矢量完全退出函数时打印它。但是如果我只是在函数结束时打印向量,那么每次它退出递归时都会打印它。是否有任何条件可以应用,以便我可以确保打印只发生一次(在第一个函数调用结束时)?

我真的不想将函数返回类型从'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 mainFunction(vector<...> &v) {
    prepareVector(v);
    printVector(v);
}
void prepareVector(vector<...> &v) {
    //your recursive code here
}

第二个选项是添加一些参数来确定这是否是第一次调用:

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;
}

我假设满足以下条件:当且仅当condition为真时,您正在进行递归调用。

但是这个函数可以换成loop

while(condition) {
    #some code to update path and minPath
}