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

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

本文关键字:向量 然后 交换 另一个 复制 成员      更新时间:2023-10-16

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

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

关于"如何深度克隆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....
相关文章: