[英]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.