所以我有两个类格式如下:
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
个对象。
答案 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....