繁体   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