c++ - 就地修改 vector 的元素

标签 c++ vector pass-by-reference

以下内容没有按预期工作(打印 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/

相关文章:

c++ - 模板按值传递或 const 引用或...?

python - 使用 lambdify 将涉及向量转置的表达式转换为数值函数

c - 通过引用调用的行为

c++ - 对短字符串编码的有理数执行算术运算时 float 的简单替代方法

c++ - 二叉树和特殊节点打印

Java arrayList 与 Vector 不兼容

c++ - 在操作后使用 vector 的原始值

php - 在 PHP 中测试可选参数

c++ - C++/ObjC 中的链接器问题

c++ - VC++ 中的动态数组大小和动态数组分配器