For certain objects (elements) in the vector aArray, I want to create a mininum sorted heap.
-
I want to modify the members of
aArrayin other functions and callHeapmember functions to update the min heap. This means that I should pass in a constant vector to theHeapstructure, but I am having a lot of trouble with this am being swamped with errors. What is the proper way to pass constant objects toHeapconstructor? -
Also, when I call the function
popHeap, I want to delete only the pointer to the root in the heap, but it deletes the object in vectoraArrayalso. How can I fix this?#include <vector> #include <iostream> struct A { A(int av, int bv):a(av),b(bv){} int a, b; }; struct Heap { Heap() : ptr(new std::vector<A>()) {} Heap(std::vector<A> *p) : ptr(p) {} void makeHeap() { // some code here } void popHeap() { ptr->erase(ptr.begin()+heapLoc[0]); //DELETES aArray member! I only want to delete the pointer, not the object. //some code here } std::vector<A> *ptr; std::vector<int> heapLoc; }; int main() { A a0(2,5), a1(4,2), a2(8,4), a3(0,3); std::vector<A> aArray; aArray.push_back(a0); aArray.push_back(a1); aArray.push_back(a2); aArray.push_back(a3); for(int i=0; i<aArray.size(); ++i) { std::cout << "aArray[i].a = " << aArray[i].a << " " << "aArray[i].b = " << aArray[i].b << "\n"; } //All 4 objects outputted Heap h(&aArray); h.makeHeap(); h.popHeap(); for(int i=0; i<aArray.size(); ++i) { std::cout << "aArray[i].a = " << aArray[i].a << " " << "aArray[i].b = " << aArray[i].b << "\n"; } //Only 3 objects outputted. One gets deletated. }
Copy the entire passed vector in the constructor (don’t just have a pointer to it). Allowing anything to modify the internal structure of something that needs to have a specific structure (as in sorted elements) to work is a bad idea. You can do this simply as follows:
You will need to either have a copy constructor or override the
=operator for A for the above to work, but doing both doesn’t hurt. As in:Adding both pieces of code will copy all the elements in the vector in the heap’s constructor. Pointers won’t work for this since are always be shallow-copied, unless you explicitly deep-copy them, which is a bit more effort.
An alternative to this is always starting with an empty heap and having an
addmethod (still not using pointers).If you don’t want to copy elements, you can use the
constkeyword. As in useconst Aeverywhere in your code where you usedA.Note 1 – I’d suggest getting rid of the makeHeap method and just doing that work in the constructor.
Note 2 – I used
classabove, and notstruct. Don’t usestructin C++, useclassinstead.structis more C.