通过结构调用递归函数

Calling recursive function by struct

本文关键字:递归函数 调用 结构      更新时间:2023-10-16

首先看看我的结构

 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"
        */
    }
}

显然取决于你那里的代码,只是想提醒你这种可能性。