-1

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

Aeisys
  • 367
  • 1
  • 3
  • 13

1 Answers1

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.

striving_coder
  • 798
  • 1
  • 5
  • 7
  • 1
    Have to be a little careful of this approach if HeapItem is a polymorphic type otherwise you could slice the items. The classic solution is to have a virtual clone method on HeapItem. If HeapItem is not polymorphic there is little reason not to store it in the vector by value. – Chris Drew Nov 22 '14 at 03:42
  • So you mean instead of `data[i] = new HeapItem(*h.data[i]);` it would be something like `data[i] = h.data[i]->clone();` where `clone()` returns pointer to the `HeapItem`'s subclass? – striving_coder Nov 22 '14 at 03:50
  • Yes, see [here](http://books.google.co.uk/books?id=mmjVIC6WolgC&lpg=PP1&dq=coding%20standards%20c%2B%2B%20clone&pg=PT336#v=onepage&q&f=false), for example. – Chris Drew Nov 22 '14 at 03:54
  • That page is closed for viewing :( But thanks anyway for the tip, Chris - and +1! :) – striving_coder Nov 22 '14 at 03:56