c++ 优先级队列(priority_queue)
从网上搜优先级队列用法,都是有些乱七八糟的,有几种用法都没说,直接贴代码。实在郁闷,于是自己在此归纳归纳。
废话不多说,直入主题。
优先级队列的核心是比较函数的实现。
比较函数有两种实现方法:
1、在结构体或类外面定义一个比较结构体。 //假如有个Point结构体。则new对象的时候:priority_queue<Point,vector<Point>,cmp> pg;其中cmp是自定义比较函数
2、在结构体或类中自己重载<操作符。 //假如有个Point结构体。这种方式定义优先级队列: priority_queue<Point> pg;
第1种方法实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <iostream> #include <queue> #include <algorithm> #include <vector> using namespace std; class Point { public : int x,y; }; struct cmp { bool operator()(Point a,Point b) { return a.x>b.x; //返回 !cmp } }; priority_queue<Point,vector<Point>,cmp> pq; Point p; int main() { int n; while (cin>>n) { while (!pq.empty()) pq.pop(); while (n--) { cin>>p.x>>p.y; pq.push(p); } while (!pq.empty()) { cout<<pq.top().x<< "-" <<pq.top().y<< " " ; pq.pop(); } } return 0; } |
第2种方法实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #include <iostream> #include <queue> #include <algorithm> #include <functional> #include <vector> using namespace std; class Point { public : friend bool operator <(Point a,Point b); int x,y; }; //友元函数在外面实现 也可在类里面实现 bool operator <(Point a,Point b) //优先级队列要求必须要实现<的重载,否则编译错误 而int型有默认的<函数。 { return a.x>b.x; //返回比较结果的相反值,这种情况是从小到大排序 } /** 友元函数在类里面实现如下 class Point { public: friend bool operator <(Point a,Point b) { return a.x>b.x; } int x,y; }; **/ priority_queue<Point> pq; Point p; int main() { int n; while (cin>>n) { while (!pq.empty()) pq.pop(); while (n--) { cin>>p.x>>p.y; pq.push(p); } while (!pq.empty()) { cout<<pq.top().x<< "-" <<pq.top().y<< " " ; pq.pop(); } } return 0; } |
人生如修仙,岂是一日间。何时登临顶,上善若水前。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)