[英]Print a variable Once in a Recursive Function, which keeps changing with each Recursion
I have a void
function in c++. 我在C ++中有一个void
函数。 It is recursive. 它是递归的。 During each recursion I pass on a vector that gets updated in the function. 在每次递归过程中,我都会传递一个向量,该向量将在函数中进行更新。 I want to print the vector only when it gets out of the function completely. 我只想在向量完全脱离功能时才打印向量。 But If I simply print the vector at the end of function, then it will be printed each time it gets out of recursion. 但是,如果我只是在函数末尾打印矢量,那么每次退出递归时都会打印它。 Is there any condition I can apply so that I can make sure printing happens only once (At the end of the first function call)? 是否可以应用任何条件,以确保仅打印一次(在第一个函数调用的末尾)?
I really don't want to change the function return type from ' void
' to anything. 我真的不想将函数的返回类型从' void
'更改为任何东西。 Is there a way or is it impossible? 有办法还是不可能?
EDIT: Code looks something like below 编辑:代码如下所示
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;
}
The easies way would be creating second function: 简单的方法是创建第二个功能:
void mainFunction(vector<...> &v) {
prepareVector(v);
printVector(v);
}
void prepareVector(vector<...> &v) {
//your recursive code here
}
Second option is adding some parameter for determining if this is first call or not: 第二种选择是添加一些参数来确定这是否是第一次调用:
void recursiveFunction(vector<...> &v, bool first=true) {
...
recursiveFunction(v, false);
...
if(first) {
printVector(v);
}
}
In your code, if you just want to print it once, at the end, you can change your code to: 在代码中,如果只想打印一次,那么最后可以将代码更改为:
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;
}
I'm assuming, that following condition is satisfied: You are making recursive call if and only if condition
is true. 我假设满足以下条件:当且仅当condition
为true时,您才进行递归调用。
But this function could me replaced with loop
: 但是我可以用loop
代替这个功能:
while(condition) {
#some code to update path and minPath
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.