以下内容没有按预期工作(打印 2),因为我猜,节点是按值传递的,即使 vector 是按引用传递的。我该如何解决?
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
class Node{
public:
int value;
Node(int);
void createChildren(vector<Node> &);
};
//! constructor of a single node
Node::Node(int value)
{
this->value = value;
}
void Node::createChildren(vector<Node> &nodes)
{
for (int i = 0; i < 5; i++) {
Node n(0);
nodes.push_back(n);
if (i == 0) {
value = nodes.size();
}
}
}
int main(void) {
Node a(0);
vector<Node> asdf;
asdf.push_back(a);
asdf[0].createChildren(asdf);
cout << asdf[0].value << endl;
return 0;
}
最佳答案
当您执行 nodes.push_back(n);
行时, vector 会调整大小,在将现有成员复制到新分配的内存块时使先前持有的引用无效。在你的例子中, *this
里面的 createChildren
就是这样一个引用(对 asdf[0])。更改其中的值不再是定义的行为,因为该对象的析构函数已被执行(尝试定义 ~Node()
并查看何时调用它)
关于c++ - 就地修改 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3083932/