对于 vector 中的某些对象(元素)aArray
,我想创建一个最小排序堆。
我想修改
aArray
其他函数中的成员并调用Heap
成员函数来更新最小堆。这意味着我应该将一个常量向量传递给Heap
结构,但是我遇到了很多麻烦,因为它被错误淹没了。将常量对象传递给Heap
构造函数的正确方法是什么?另外,当我调用函数时
popHeap
,我只想删除指向堆中根的指针,但它aArray
也会删除向量中的对象。我怎样才能解决这个问题?#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. }