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

Copy contents of a class member vector into another vector and then swapping them back

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

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 个对象。

关于问题"How to deep clone a vector of pointers"

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

#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....