簡體   English   中英

將 object 添加到向量,然后從迭代器更新它

[英]Adding object to vector and then updating it from an iterator

class TreeNode {
public:
    Box box;
    vector<int> points;
    vector<TreeNode> children;
};

我有這個簡單的節點 class。 我將節點添加到向量中,然后像這樣遍歷該向量:

TreeNode root;
vector<TreeNode> activeNodeList;
activeNodeList.push_back(root);

vector<TreeNode>::iterator b = activeNodeList.begin();

while (b != activeNodeList.end()) {
    vector<TreeNode> tempNodeList;
    // tempNodeList is populated with multiple TreeNode's
    (*b.base()).children = tempNodeList;
}

在調試器中,存儲在activeNodeList中的節點的children被設置為tempNodeList,但是root的children向量仍然是空的,這是為什么呢?

這條線

activeNodeList.push_back(root);

root復制activeNodeList 所有對activeNodeList的進一步操作都會影響這個副本,而不是root本身。

你可以這樣做:

activeNodeList.push_back(TreeNode{});
TreeNode& root = activeNodeList.back();

現在root將是對新添加元素的引用 但要小心:如果activeNodeList重新分配,這個引用將變成一個懸空的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM