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

dri*_*pie 0 c++ recursion boost function

假设我有一个功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚的是如何让函数知道它所在的递归数,以及如何停止它。任何有效和聪明的方法来做到这一点?如果它有帮助,我正在使用 boost 算法。

Uni*_*ash 5

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

int recursive(int NbProducts, int NbPlates, int NbPositions,int repeat)
{ 
 repeat --;
   if(repeat==0)
 return result;
   else
 recursive(NbProducts, NbPlates, NbPositions, repeat);
}
Run Code Online (Sandbox Code Playgroud)

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

recursive(NbProducts, NbPlates, NbPositions, 3);
Run Code Online (Sandbox Code Playgroud)