[C++]priority_queue

原文地址:https://blog.csdn.net/xiaoquantouer/article/details/52015928

 

1、头文件

#include<queue>

 

2、定义

[cpp] view plain copy

  1. priority_queue<int> p;  

 

 

3、优先输出大数据

 

 

priority_queue<Type, Container, Functional>

Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。

如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。

 

例如:

[cpp] view plain copy

  1. #include<iostream>  
  2. #include<queue>  
  3. using namespace std;  
  4.   
  5. int main(){  
  6.     priority_queue<int> p;  
  7.     p.push(1);  
  8.     p.push(2);  
  9.     p.push(8);  
  10.     p.push(5);  
  11.     p.push(43);  
  12.     for(int i=0;i<5;i++){  
  13.         cout<<p.top()<<endl;  
  14.         p.pop();  
  15.     }  
  16.     return 0;  
  17. }  

 

 

输出:

 

 

 

 

 

4、优先输出小数据

方法一:

[cpp] view plain copy

  1. priority_queue<int, vector<int>, greater<int> > p;  

 

 

例如:

 

 

[cpp] view plain copy

  1. #include<iostream>  
  2. #include<queue>  
  3. using namespace std;  
  4.   
  5. int main(){  
  6.     priority_queue<int, vector<int>, greater<int> >p;  
  7.     p.push(1);  
  8.     p.push(2);  
  9.     p.push(8);  
  10.     p.push(5);  
  11.     p.push(43);  
  12.     for(int i=0;i<5;i++){  
  13.         cout<<p.top()<<endl;  
  14.         p.pop();  
  15.     }  
  16.     return 0;  
  17. }  

 

 

输出:

 

 

 

 

方法二:自定义优先级,重载默认的 < 符号

 

例子:

[cpp] view plain copy

  1. #include<iostream>  
  2. #include<queue>  
  3. #include<cstdlib>  
  4. using namespace std;  
  5. struct Node{  
  6.     int x,y;  
  7.     Node(int a=0, int b=0):  
  8.         x(a), y(b) {}  
  9. };  
  10.   
  11. struct cmp{  
  12.     bool operator()(Node a, Node b){  
  13.         if(a.x == b.x)  return a.y>b.y;  
  14.         return a.x>b.x;  
  15.     }  
  16. };  
  17.   
  18. int main(){  
  19.     priority_queue<Node, vector<Node>, cmp>p;  
  20.       
  21.     for(int i=0; i<10; ++i)  
  22.         p.push(Node(rand(), rand()));  
  23.           
  24.     while(!p.empty()){  
  25.         cout<<p.top().x<<' '<<p.top().y<<endl;  
  26.         p.pop();  
  27.     }//while  
  28.     //getchar();  
  29.     return 0;  
  30. }  

 

 

输出:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值