您的位置:首页 > 编程语言 > C语言/C++

最大堆的C++实现,及过程中遇到的一个小问题

2014-05-07 19:44 225 查看
template<class T>
class MaxHeap{
public:
MaxHeap(int MaxHeapSize = 10);
~MaxHeap(){ delete[] heap; }
int Size()const{ return CurrentSize; }
T Max()const;
MaxHeap<T>& Insert(const T& x);
MaxHeap<T>& DeleteMax(T& x);
void Initialize(T a[], int size, int ArraySize);
int GetCurrentSize()const;
private:
int CurrentSize, MaxSize;
T *heap;
};

template<class T>
MaxHeap<T>::MaxHeap(int MaxHeapSize){
MaxSize = MaxHeapSize;
heap = new T[MaxSize + 1];
CurrentSize = 0;
}

template<class T>
T MaxHeap<T>::Max()const{
if (CurrentSize)
return heap[1];
else
throw OutOfBounds();
}

template<class T>
MaxHeap<T>& MaxHeap<T>::Insert(const T& x){
if (CurrentSize == MaxSize)
throw OutOfBounds();

int i = ++CurrentSize;
while (i != 1 && x > heap[i / 2]){
heap[i] = heap[i / 2];
i /= 2;
}
heap[i] = x;
return *this;
}

template<class T>
MaxHeap<T>& MaxHeap<T>::DeleteMax(T& x){
if (CurrentSize == 0)
throw OutOfBounds();
x = heap[1];
T y = heap[CurrentSize--];
int i = 1, ci = 2;
while (ci <= CurrentSize){
if (ci < CurrentSize&&heap[ci] < heap[ci + 1])
ci++;
if (y >= heap[ci])
break;
heap[i] = heap[ci];
i = ci;
ci *= 2;
}
heap[i] = y;
return *this;
}

template<class T>
void MaxHeap<T>::Initialize(T a[], int size, int ArraySize){
delete[] heap;
CurrentSize = size;
MaxSize = ArraySize;
heap = new T[MaxSize + 1];
for (int i = 0; i <= size; i++){
heap[i] = a[i];
}
for (int i = CurrentSize / 2; i >= 1; i--){
T y = heap[i];
int c = 2 * i;
while (c <= CurrentSize){
if (c < CurrentSize&&heap[c] < heap[c + 1])
c++;
if (y >= heap[c])
break;

heap[c / 2] = heap[c];
c *= 2;
}
heap[c / 2] = y;
}
}

template<class T>
int MaxHeap<T>::GetCurrentSize()const{
return CurrentSize;
}


以上代码在VS2013中可以通过编译,实现最大堆的初始化,插入和删除操作。


但是第一遍写的时候照着书上写最大堆的初始化时出现了一个错误,先看一下代码。

template<class T>
void MaxHeap<T>::Initialize(T a[], int size, int ArraySize){
delete[] heap;
heap=a;
        CurrentSize = size;
MaxSize = ArraySize;
for (int i = CurrentSize / 2; i >= 1; i--){
T y = heap[i];
int c = 2 * i;
while (c <= CurrentSize){
if (c < CurrentSize&&heap[c] < heap[c + 1])
c++;
if (y >= heap[c])
break;

heap[c / 2] = heap[c];
c *= 2;
}
heap[c / 2] = y;
}
}
然后新建一个最大堆并调用初始化方法,出错! Debug发现初始化结束后数据组织上没有任何问题,百思不得其解。

然后百度了一下错误信息,才发现问题所在。

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

原来我用heap直接指向了a,在main方法结束之后,编译器先是释放了数组a所占的内存,然后调用MaxHeap的析构方法时再次尝试释放a时出错了。

至此问题得以解决。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐