【问题标题】:Adding object to vector and then updating it from an iterator将对象添加到向量,然后从迭代器更新它
【发布时间】:2019-11-21 05:13:55
【问题描述】:
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++ vector iterator variable-assignment


    【解决方案1】:

    这一行

    activeNodeList.push_back(root);
    

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

    你可以这样做:

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

    现在root 将成为新添加元素的引用。但请注意:如果activeNodeList 重新分配,此引用将成为悬空引用。

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多