STL之优先级队列priority_queue
摘要:
priority_queue,自适应容器(即容器适配器):不能由list来组建;
最大值优先级队列(最大值始终在对首,push进去时候)
最小值优先级队列;
优先级队列适配器 STL priority_queue
priority_queue<int, deque<int> > pg;
priority_queue<int, vector<int> > pg;
STL中实现的方法:
pg.empty();
pg.size();
pg.top(); //查看队首的元素
pg.pop(); //从队首删除元素;
pg.push(item); //从队尾加入元素
1 #include <iostream> 2 #include <queue> 3 4 using namespace std; 5 int main() 6 { 7 //最大值有限队列, 会进行自动排序 8 priority_queue<int, vector<int> > pg; 9 priority_queue<int, deque<int> > pg2; 10 //priority_queue<int> pg3; 11 12 pg.push(10); 13 pg.push(5); 14 pg.push(-1); 15 pg.push(20); 16 17 std::cout <<"priority_queue first item: " << pg.top() << std::endl; 18 while(!pg.empty()){ 19 std::cout<<"priority_queue del item: " << pg.top() << std::endl; 20 pg.pop(); 21 } 22 //最小值有限队列,从小到大排序 23 priority_queue<int, deque<int>, greater<int> > pg3; 24 pg3.push(10); 25 pg3.push(5); 26 pg3.push(-1); 27 pg3.push(20); 28 std::cout <<"priority_queue first item: " << pg3.top() << std::endl; 29 while(!pg3.empty()){ 30 std::cout<<"priority_queue del item: " << pg3.top() << std::endl; 31 pg3.pop(); 32 } 33 34 return 0; 35 }