调用自身 N 次的 C++ 递归函数?

标签 c++ function boost recursion

假设我有一个函数:

int recursive(int NbProducts, int NbPlates, int NbPositions)
{ //the following is a recursive function that will call itself 3 times
 //code to be repeated goes here
 recursive(int NbProducts, int NbPlates, int NbPositions);
}

我想不通的是如何让函数知道它在哪个递归数上,以及如何停止它。任何有效和聪明的方法来做到这一点?如果有帮助,我正在使用 boost 算法。

最佳答案

给它传一个参数,在函数执行前进行检查,如果迭代结束,返回结果,否则继续

int recursive(int NbProducts, int NbPlates, int NbPositions,int repeat)
{ 
 repeat --;
   if(repeat==0)
 return result;
   else
 recursive(NbProducts, NbPlates, NbPositions, repeat);
}

如果你想让它重复3次,你只需要说

recursive(NbProducts, NbPlates, NbPositions, 3);

关于调用自身 N 次的 C++ 递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26630716/

相关文章:

c++ - RGB 的奇怪输出

C++:在模板化类型中存在命名成员时在模板化类中提供类函数?

c++ - 访问 boost::geometry 多边形中的点数据时出错

c - 在 C 中的循环内声明一个函数

javascript - this 关键字不适用于箭头函数

c++ - boost::optional 会触发 shared_ptr 的引用计数吗?

具有删除旧样本能力的 C++ 累加器库

C++ 返回在函数范围内声明的引用

c++ - 链接到 VS2012 中的 Boost Regex 库

python - 将每行的第一个单词分配给字典中的关键字