1 #include <vector> 2 using std::vector; 3 4 template<typename T> 5 class PriorityQueue 6 { 7 public: 8 PriorityQueue(int size = 101):bHeap(size),currentSize(0) {} 9 const T& top() const 10 { return bHeap[1]; } 11 void pop() 12 { 13 T tmp = bHeap[currentSize--]; 14 int hole = 1, child; 15 16 //percolate down 17 for(; hole*2<=currentSize; hole = child) 18 { 19 child = hole*2; 20 if(child!=currentSize&&bHeap[child+1]<bHeap[child]) 21 ++child; 22 if(bHeap[child]<tmp) 23 bHeap[hole] = bHeap[child]; 24 else 25 break; 26 } 27 bHeap[hole] = tmp; 28 } 29 void push(const T &x) 30 { 31 if(currentSize==bHeap.size()-1) 32 bHeap.resize(bHeap.size()*2); 33 34 int hole = ++currentSize; 35 36 //percolate up 37 for(; hole>1&&bHeap[hole/2]>x; hole /= 2) 38 bHeap[hole] = bHeap[hole/2]; 39 40 bHeap[hole] = x; 41 } 42 bool empty() const 43 { return currentSize==0; } 44 void clear() 45 { 46 bHeap.clear(); 47 currentSize = 0; 48 } 49 50 private: 51 vector<T> bHeap; 52 int currentSize; 53 };
测试代码:
1 PriorityQueue<int> q; 2 3 for(int i=0; i<10; ++i) 4 { 5 int tmp; 6 cout<<"please input: "; 7 cin>>tmp; 8 q.push(tmp); 9 } 10 11 cout<<"按序输出:"<<endl; 12 while(!q.empty()) 13 { 14 cout<<q.top()<<endl; 15 q.pop(); 16 }
测试结果: