问题
I have a class called Heap that is a Vector of pointers to HeapItem objects
vector<HeapItem*> myHeap;
I want to create a deep copy of Heap so that I can delete all the items in the copy without affecting the original Heap.
EX:
OriginalHeap = new Heap();
OriginalHeap.Insert(HeapItem1);
OriginalHeap.Insert(HeapItem2);
OriginalHeap.Insert(HeapItem3);
CopyHeap = OriginalHeap;
CopyHeap.deleteMin();
print(OriginalHeap);
print(CopyHeap);
Output:
OriginalHeap = HeapItem1,HeapItem2,HeapItem3
CopyHeap = HeapItem2, HeapItem3
回答1:
Since you introduce the notion of Heap class which is a wrapper for vector<HeapItem*>
you can define copy constructor for this class that takes care of desired deep copying:
class Heap{
vector<HeapItem*> data;
public:
... // various constructors if needed
Heap(const Heap& h) {
data = new vector<HeapItem*>(h.size());
for (int i=0; i<h.size(); i++)
data[i] = new HeapItem(*h.data[i]); // if HeapItem supports copy construction
}
... // various member functions if needed
}
One possible modification as was pointed out by Chris is to use HeapItem
's clone()
method if former is a polymorphic class - see comments to this answer.
In addition, you might define copy assignment (if you want to be able to assigned one existing Heap
to another one) and you sure want to define destructor to make sure memory is properly released when the Heap
object's life is over.
You can also define Heap
as a template class so that you'd be able to parameterize it with the type of HeapItem
.
来源:https://stackoverflow.com/questions/27073528/c-deep-copy-vector-pointer-object