优先队列C++实现

 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     }

测试结果:

转载于:https://www.cnblogs.com/pczhou/p/4648146.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值