|
本帖最后由 2191265529 于 2019-9-27 10:13 编辑
MaxHeap.h文件如下:- #pragma once
- #ifndef _MAX_HEAP_
- #define _MAX_HEAP_
- template <class T>
- class MaxHeap
- {
- public:
- MaxHeap(int mx = 10);
- ~MaxHeap();
- bool isEmpty();
- void Push(T e);
- T& Top();
- private:
- T* maxHeap;
- int maxSize;
- int currentSize;
- void trickleUp(int index);
- void trickleDown(int index);
- };
- template <class T>
- MaxHeap<T>::MaxHeap(int mx)
- {
- maxSize = mx;
- maxHeap = new T(mx);
- }
- template <class T>
- bool MaxHeap<T>::isEmpty()
- {
- return currentSize == 0;
- }
- template <class T>
- MaxHeap<T>::~MaxHeap()
- {
- delete[] maxHeap;
- }
- template <class T>
- void MaxHeap<T>::Push(T e)
- {
- if (currentSize == maxSize) throw "MaxHeap is full";
- maxHeap[currentSize] = e;
- trickleUp(currentSize++);
- }
- template <class T>
- void MaxHeap<T>::trickleUp(int index)
- {
- T bottom = maxHeap[index];
- while (index > 0 && maxHeap[index - 1 >> 1] < maxHeap[index])
- {
- maxHeap[index] = maxHeap[index - 1 >> 1];
- index = index - 1 >> 1;
- }
- maxHeap[index] = bottom;
- }
- template <class T>
- T& MaxHeap<T>::Top()
- {
- if (currentSize <= 1) throw "maxheap is empty!";
- return maxHeap[0];
- }
- #endif
复制代码
main.cpp文件如下:
- #include <iostream>
- #include "MaxHeap.h"
- using namespace std;
- int main()
- {
- MaxHeap<int> h;
- h.Push(20);
- h.Push(10);
- h.Push(30);
- cout << h.Top() << endl;
- system("pause");
- return 0;
- }
复制代码
程序这里cout << h.Top() << endl; 会蹦溃什么情况,Top()函数的定义返回值不是引用的话也会崩溃,按理说,return会产生一个副本啊?
|
上一篇: Qt不能再当前代码也表示字符问题下一篇: SOCKET TCP服务器,客户端一断开cpu占用就飙升
|