将对象添加到向量,然后从迭代器更新它

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 vector 仍然是空的,这是为什么?

这一行

activeNodeList.push_back(root);

复制rootactiveNodeListactiveNodeList 的所有进一步操作将影响此副本,而不是 root 本身。

你可以这样做:

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

现在 root 将成为对新添加元素的 引用。但要小心:如果 activeNodeList 重新分配,此引用将成为悬空引用。