簡體   English   中英

修改矢量的元素

[英]Modify in place the elements of a vector

以下內容無法按需工作(打印2),因為我猜想,即使向量是通過引用傳遞的,節點也是按值傳遞的。 我該如何解決?

#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); ,調整向量的大小,使先前保留的引用無效,因為它將現有成員復制到新分配的存儲塊中。 在您的情況下, *this createChildren內部的*this是這樣的引用(對asdf [0])。 更改其中的值已不再是定義的行為,因為已經執行了此對象的析構函數(嘗試定義~Node()並查看何時調用它)。

該解決方案與Adrian Regan所說的有關。

如果在“ createChildren()”方法中將另一個元素推到節點向量上,則向量很可能需要調整自身大小。 這樣做時,它將所有現有元素復制到新分配的存儲中。

因此,這是第一次發生,它將節點0的初始值復制為值0。

編譯器將生成一個默認的復制構造函數,該構造函數執行按位復制。 但是,僅實現復制構造函數將無濟於事,因為您總是會丟失節點0的更新值。

H。

如果要將Node類放入向量(或與此相關的任何其他容器)中,則需要確保其具有復制構造函數和and operator =實現,否則應將指向Node的指針放入向量中

class Node {
   ...
   public:
      Node(const Node& rhs) { ... }

      Node& operator=(const Node& rhs) {
           if(this == &rhs)
              return *this;
           value = rhs.value;
           // ... other members copied ...
           return *this;
      }

      Node& operator=(Node& rhs) { ... non const version ... }
 };

除此之外,您的createChildren()方法應在循環后將值設置為5。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM