将类成员向量的内容复制到另一个向量中,然后将其交换回
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
对象。
关于"如何深度克隆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....
相关文章:
- C++:如何读取分离变量,然后读取向量
- 如何正确地推回然后遍历堆中对象的向量?
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- C++:将向量传递给函数,然后在main中调用函数.错过了什么
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 如何在每次循环迭代期间生成向量,存储数据,然后删除该向量?
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- 我可以在中断中写入向量,然后以安全的方式仅在主线程内读取吗?
- 制作一个对的向量,对其进行排序,然后从中提取向量
- 根据标准对结构向量进行排序,然后显示结果
- C - 将文本文件读为一串单词,然后将字符串分为向量
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 我有不同的类,我想用这些类中的对象制作一个向量,然后按值对其进行排序
- remove_if然后擦除对向量有效吗
- 如何在C++中创建一个网格,这将允许我将每个索引设置为一个向量,以便以后操作该向量,然后绘制它
- 如何使用选择语句检索 sqlite 并分配给向量然后分配给字符串