我正在尝试为最小堆编写 C++ 代码。我想创建一个指针向量并确保它们被正确删除。
我能够创建一个指针向量,但是我从默认构造函数中得到一个无效的转换错误。为什么会这样?
此外,我正在尝试编写用户定义的析构函数以确保我没有任何内存问题。但是,我无法弄清楚为什么我会收到指针未分配的错误。
#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*>()) {} //WHY AM I GETTING AN ERROR FOR THE DEFAULT CONSTRUCTOR AND NOT THE CONSTRUCTOR BELOW?
//ERROR: invalid conversion from ‘std::vector<A*, std::allocator<A*> >*’ to ‘long unsigned int’
//ERROR: initializing argument 1 of ‘std::vector<_Tp, _Alloc>::vector(size_t, const _Tp&, const _Alloc&) [with _Tp = A*, _Alloc = std::allocator<A*>]’
Heap(std::vector<A*> p) : ptr(p) { //Works fine.
makeHeap();
}
~Heap(){ //I DON'T UNDERSTAND WHY I AM GETTING A MEMORY ERROR HERE
std::vector<A*>::iterator it;
for(it=ptr.begin(); it<ptr.end(); ++it)
{
delete *it;
*it=NULL;
}
}//ERROR: malloc pointer being freed was not allocated
void makeHeap()
{ //some code }
std::vector<A*> ptr;
std::vector<int> heapLoc;
};
int main()
{
A a0(2,5), a1(4,2);
std::vector<A*> aArray;
aArray.push_back(&a0);
aArray.push_back(&a1);
Heap h(aArray);
return 0;
}