繁体   English   中英

在C ++中遍历树期间更改指针

[英]Pointer changing during iterating through tree in C++

所以我面临一个奇怪的问题。 我有一棵A的树,并且正在尝试查找所有A内特定字段的最小值。 我没有manager类中所有节点的ptrs向量。 我只在其中存储根节点。 但是,每个节点都将具有其所有子节点的ptrs向量。

现在,如果我使用以下命令对此进行调用:

std::vector<A*> treeRoots; //only keeps the roots of each tree
A* minVal = nullptr;
time_t minTime = std::numeric_limits<time_t>::max();

for(auto root : treeRoots){
    root->findMin(minVal, &minTime);
}

这需要以下内容:

void A::findMin(A* minA, time_t* pMinVal){
  //find the smallest amongst the children
  for(auto child : children_){ //children_ is an std::vector<A*>
    child->findMin(minFactor, pMinVal);
  }

  time_t currentNodeData = getValue(); //the value we are comparing
  if(currentNodeData < *pMinVal){
    minA = this;
    *pMinVal  = currentNodeData;
  }
  log()->info("is null? %d",(minA == nullptr));
}

我似乎总是对“是否为空?”为真。 比较。

如果我进行如下修改,它似乎可以正常工作:

for(auto root : treeRoots){
    root->findMin(&minVal, &minTime);
}

并调用以下函数:

void A::findMin(A** minA, time_t* pMinVal){
  //find the smallest amongst the children
  for(auto child : children_){ //children_ is an std::vector<A*> within each node
    child->findMin(minFactor, pMinVal);
  }

  time_t currentNodeData = getValue(); //the value we are comparing
  if(currentNodeData < *pMinVal){
    *minA = this;
    *pMinVal  = currentNodeData;
  }
  log()->info("is null? %d",(*minA == nullptr));
}

由于您要传递的指针minVal的值最初为零,因此它将始终返回true,因为不会修改minVal的原始值。 如果要修改值,请使用对指针的引用,例如:

root->findMin(minval,&time);
then
void findMin(A* &minA,time_t *pminVal)
{
 .....
}

或在第二个示例中使用的指向指针的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM