priority_queue的用法

priority_queue本质是一个堆,默认为按照元素值的大小从大到小排序

1.简单的使用方法

复制代码
//二叉树  默认为小根堆
#include<iostream>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int>  pq;
    pq.push(1);
    cout<<pq.size()<<endl;
    while(pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
    cout<<endl;
} 
View Code
复制代码

默认状态:

复制代码
#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int> p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}
View Code
复制代码

优先输出小数据:

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

复制代码
#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int, vector<int>, greater<int> >p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}
View Code
复制代码

2.重载  “<”  定义优先级

复制代码
#include<iostream>
#include<queue>
#include<cstdlib>
using namespace std;
struct Node{
    int x,y;
    Node(int a=0, int b=0):
        x(a), y(b) {}
};
 
struct cmp{
    bool operator()(Node a, Node b){
        if(a.x == b.x)    return a.y>b.y;
        return a.x>b.x;
    }
};
 
int main(){
    priority_queue<Node, vector<Node>, cmp>p;
    
    for(int i=0; i<10; ++i)
        p.push(Node(rand(), rand()));
        
    while(!p.empty()){
        cout<<p.top().x<<' '<<p.top().y<<endl;
        p.pop();
    }//while
    //getchar();
    return 0;
}
View Code
复制代码

 

posted @   Hello_World2020  阅读(110)  评论(0编辑  收藏  举报
编辑推荐:
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
阅读排行:
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 想让你多爱自己一些的开源计时器
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
点击右上角即可分享
微信分享提示