c++ - 将对象添加到向量,然后从迭代器更新它
问题描述
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向量仍然是空的,这是为什么呢?
解决方案
这条线
activeNodeList.push_back(root);
将复制 root
到activeNodeList
. 所有进一步的操作activeNodeList
都会影响这个副本,而不是root
它本身。
你可以这样做:
activeNodeList.push_back(TreeNode{});
TreeNode& root = activeNodeList.back();
现在root
将是对新添加元素的引用。但要小心:如果activeNodeList
重新分配,这个引用将成为一个悬空的。
推荐阅读
- python - 抓取网站(marketchameleon)返回加密数据
- docker - 在运行时连接 Dockerfile 中的变量
- swift - 如何在 GUI 中使用 Swift 的 BlueSocket 库?
- highcharts - Highcharts - 如何使用滚动条隐藏 xAxis 上的最后一个类别刻度标签
- javascript - 更改路径“d”属性以弯曲线
- scala - 比较 2 个键值对之间的值时,Spark Scala 匹配错误
- if-statement - Why doesn't my if-then statement in Scratch ever trigger?
- javascript - 某些数据未保存在 firebase 数据库中
- scala - Akka 测试 - 等待actor初始化
- c# - LINQ - 将带有子列表的对象列表展平为一个列表