在递归函数中打印一个变量 Once,它随着每次递归而不断变化
Print a variable Once in a Recursive Function, which keeps changing with each Recursion
我在 C++ 中有一个 void
函数。它是递归的。在每次递归期间,我传递一个在函数中更新的向量。我只想在向量完全脱离函数时才打印向量。但是如果我只是在函数末尾打印向量,那么每次它退出递归时都会打印它。有没有我可以应用的条件,以确保打印只发生一次(在第一次函数调用结束时)?
我真的不想将函数 return 类型从“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++ 中有一个 void
函数。它是递归的。在每次递归期间,我传递一个在函数中更新的向量。我只想在向量完全脱离函数时才打印向量。但是如果我只是在函数末尾打印向量,那么每次它退出递归时都会打印它。有没有我可以应用的条件,以确保打印只发生一次(在第一次函数调用结束时)?
我真的不想将函数 return 类型从“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
}