通过结构调用递归函数
Calling recursive function by struct
首先看看我的结构
typedef struct {
int treeDepth;
unsigned __int8 dmv[19];
unsigned __int8 dv[19];
unsigned __int8 ih;
bool flagLeft = true ;
bool flagRight = true;
}problem_t;
我有一个适用于这个结构的函数,
void PMSprune(problem_t &problem)
{
/*
--blocks of code!
--modify properties of "problem"
*/
PMSprune(problem);// I want to call it with problem.treeDepth++, but I
//don't want my original struct to be modified
}
但是这个函数是递归的,我想用正在修改的结构的一个属性来调用这个函数,有人知道我该怎么做吗?
更新:我的项目是实时的,时间对我来说真的很重要,这个函数在一个循环中被调用了大约一百万次。
拆分函数:
void PMSpruneRec(problem_t &problem, int treeDepth)
{
/*
--blocks of code!
--modify properties of "problem"
*/
PMSpruneRec(problem, treeDepth + 1);
}
void PMSprune(problem_t &problem)
{
PMSpruneRec(problem, problem.treeDepth);
}
当然,您仍然需要一些终止条件。
只需在更改之前复制它:
void PMSprune(problem_t &problem)
{
/*
--blocks of code!
*/
problem_t new_problem = problem
/*
--modify properties of "new_problem"
*/
PMSprune(new_problem);
}
如果某个设计的treeDepth
应该是problem_t
成员,您可以在每次递归调用后简单地重置其值:
void PMSprune(problem_t &problem)
{
/*
--blocks of code!
--modify properties of "problem"
*/
++problem.treeDepth;
PMSprune(problem);// I want to call it with problem.treeDepth++, but I
//don't want my original struct to be modified
--problem.treeDepth;
}
否则塞巴斯蒂安的方法更好。它更加清晰和结构化。
你有没有考虑过把它变成一个循环?它甚至可以在性能方面有所帮助,因为它是紧密循环中的嵌套调用。
void PMSprune(problem_t &problem)
{
for(int treeDepth = problem.treeDepth; someStoppingCondition; ++treeDepth)
{
/*
--blocks of code!
--modify properties of "problem"
*/
}
}
显然取决于你那里的代码,只是想提醒你这种可能性。
相关文章:
- 如何在Elixir中调用递归函数并行
- 即使没有调用这个递归函数,它是如何工作的?
- 如何在递归函数调用中返回当前函数值
- 递归函数调用在后台工作
- 递归列表:调用析构函数的所有内容
- 如何在递归函数中调用引用数组?
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 我应该如何递归地调用带有模板的函数
- 在堆栈已满之前,在C/C 中以最大递归函数调用并给出分段故障
- 如何在不使用静态变量的情况下从递归函数中只调用另一个函数一次
- 递归函数是否可以在不将常量作为参数发送的情况下了解首次调用它的函数中的常量
- 可以valgrind报告丢失块的内存地址(用于调试递归函数调用)
- 如何使用"wrapper function"调用没有参数的递归函数 n 次?
- 当我在递归函数中调用 return 时,我的程序意外完成
- C++递归函数,调用当前深度
- 如何跟踪递归函数的调用堆栈使用情况
- 在循环中调用递归函数
- C++在递归函数中平衡了树/调用顺序
- 为什么递归函数打印正确的值,而调用后的cout语句却没有打印正确的值?
- Eclipse抱怨递归函数调用