gpt4 book ai didi

c++ - 在递归函数中打印一个变量 Once,它随着每次递归而不断变化

转载 作者:行者123 更新时间:2023-11-30 03:57:05 25 4
gpt4 key购买 nike

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

我真的不想将函数返回类型从“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
}

关于c++ - 在递归函数中打印一个变量 Once,它随着每次递归而不断变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28150966/

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