优先队列
调用priority_queue<int> pq; 默认为最大堆
1 #include <cstdio> 2 #include <iostream> 3 #include <queue> 4 using namespace std; 5 int main() 6 { 7 priority_queue<int> pq; 8 pq.push(3); 9 pq.push(5); 10 pq.push(1); 11 while(!pq.empty()){ 12 //获取并删除最大值 13 cout<<pq.top()<<endl; 14 pq.pop(); 15 } 16 //5 3 1 17 return 0; 18 }
调用下面的可以指定最大堆或者最小堆
priority_queue<int,vector<int>,less<int> > p;
priority_queue<int,vector<int>,greater<int> > q;
1 #include <cstdio> 2 #include <iostream> 3 #include <queue> 4 using namespace std; 5 int main() 6 { 7 priority_queue<int,vector<int>,less<int> > p; 8 priority_queue<int,vector<int>,greater<int> > q; 9 p.push(3); 10 p.push(5); 11 p.push(1); 12 q.push(3); 13 q.push(5); 14 q.push(1); 15 while(!p.empty()){ 16 //获取并删除最大值 17 cout<<p.top()<<" ";//5 3 1 18 p.pop(); 19 } 20 cout<<endl; 21 while(!q.empty()){ 22 //获取并删除最小值 23 cout<<q.top()<<" ";//1 3 5 24 q.pop(); 25 } 26 return 0; 27 }