在递归函数中打印一次变量,该变量会随着每次递归而不断变化
Print a variable Once in a Recursive Function, which keeps changing with each Recursion
我在 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
}
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用递归时获取变量的奇怪值
- 使用静态变量的递归调用的不同输出
- 如果我们通过引用传递变量,则递归中使用的堆栈空间量是否为零?
- 可以清除递归函数中的变量吗?
- 使用变量模板的递归计算 - gcc 与 clang
- 在递归函数C++中声明变量
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 没有参数的递归,也没有静态或全局变量
- 共享指针中的递归,而变量在类中定义
- 在 c++ 中使用递归时不使用变量反转字符串
- C 递归变量lambda
- C++:递归(变量失去值)
- 我对变量在递归函数中如何工作的理解是否正确?
- 为什么我必须专门化递归模板变量
- 无全局变量或功能参数的递归调用
- 递归返回语句无法正确返回变量
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- 如何求解递归变量
- 带有boost变量递归包装器的字符串解析器