简体   繁体   English

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

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

So I am facing a weird issue. 所以我面临一个奇怪的问题。 I have a tree of A's & am trying to find the min of a specific field within all of the A's. 我有一棵A的树,并且正在尝试查找所有A内特定字段的最小值。 I do not have a vector of ptrs of ALL the nodes within the manager class. 我没有manager类中所有节点的ptrs向量。 I merely have the root nodes stores there. 我只在其中存储根节点。 Each node will however have a vector of ptrs of all it's children though. 但是,每个节点都将具有其所有子节点的ptrs向量。

Now if I call into this using the following: 现在,如果我使用以下命令对此进行调用:

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);
}

This calls into the following: 这需要以下内容:

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));
}

I seem to always get a true on the "is null?" 我似乎总是对“是否为空?”为真。 comparison. 比较。

If I modify as follows, it seems to work fine: 如果我进行如下修改,它似乎可以正常工作:

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

And call into the following function: 并调用以下函数:

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));
}

Since you are passing the value of pointer minVal , which was initally zero, it will always return true because original value of minVal will not be modified. 由于您要传递的指针minVal的值最初为零,因此它将始终返回true,因为不会修改minVal的原始值。 if you want to modify the value, use reference to a pointer like: 如果要修改值,请使用对指针的引用,例如:

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

or a pointer to a pointer as you have used in second example. 或在第二个示例中使用的指向指针的指针。

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

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