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; }
默认状态:

#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; }
优先输出小数据:
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; }
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; }
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 还在手写JSON调教大模型?.NET 9有新玩法
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· Coze Studio:字节跳动 Coze 的开源版本来了!第一时间深度解析
· 一款超级经典复古的 Windows 9x 主题风格 Avalonia UI 控件库,满满的回忆杀!
· 我给 AI 接上了一个 C# 运行器,结果它学会了自己上网、调试代码
· 源码浅析:SpringBoot main方法结束为什么程序不停止
· Qwen Code与Claude Coder Router体验