将类成员向量的内容复制到另一个向量中,然后将它们交换回来

时间:2015-02-06 02:14:41

标签: c++ class vector member

所以我有两个类格式如下:

class HashMinHeap {
private:
    vector<int> MiniHeap;
public:
  ...
];

class HashTable {
private:
    vector<HashMinHeap*> table;

public:
...
};

我想创建第二个向量vector <HashMinHeap*> table2,将table的内容复制到table2,然后我将对table执行一些操作最终会删除table的内容,因此要保留其内容,我希望将table2的原始内容交回table。任何人都知道如何进行复制和交换? 谢谢! 当我进行复制和交换时,注意 table中包含HashMinHeap个对象。

1 个答案:

答案 0 :(得分:0)

关于问题&#34;如何深度克隆vector of pointers&#34;

使用复制构造函数,如下所示。

#include <iostream>
#include <vector>

using namespace std;


class HashMinHeap {
public:
    string s;
    vector<int> MiniHeap;

    HashMinHeap() { }

    HashMinHeap(const HashMinHeap& other ) : MiniHeap(other.MiniHeap), s(other.s) { }
};

class HashTable {
public:
    vector<HashMinHeap*> table;

    HashTable() { }

    HashTable(const HashTable& other ) {
        for(auto& item : other.table) {
            table.push_back(new HashMinHeap(*item));
        }
    }
};

int main(int argc, const char * argv[]) {
    HashTable table;
    table.table.push_back(new HashMinHeap);
    table.table.push_back(new HashMinHeap);
    table.table[0]->s = "Hello world....";
    table.table[1]->s = "Hello universe....";

    HashTable tableCopy = table;
    tableCopy.table[0]->s = "Changed....";

    cout << "original1 " << table.table[0]->s << endl;
    cout << "original2 " << table.table[1]->s << endl;
    cout << "copy " << tableCopy.table[0]->s << endl;
    cout << "copy2 " << tableCopy.table[1]->s << endl;
    return 0;
}

结果

original1 Hello world....
original2 Hello universe....
copy Changed....
copy2 Hello universe....