首页 > 解决方案 > 将对象添加到向量,然后从迭代器更新它

问题描述

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

我有这个简单的节点类。我将节点添加到向量中,然后像这样遍历该向量:

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

标签: c++vectoriteratorvariable-assignment

解决方案


这条线

activeNodeList.push_back(root);

复制 rootactiveNodeList. 所有进一步的操作activeNodeList都会影响这个副本,而不是root它本身。

你可以这样做:

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

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


推荐阅读