巧用优先队列:重载运算符在STL优先队列中的应用
前言
写优先队列优化dijkstra的时候,需要放进优先队列的常常有数值和编号两类,以下介绍让编号捆绑数值放入优先队列的几种方法。
由于过程比较简单,记住代码即可,下面不再讲解,只附上代码,请读者自行理解。
1.pair<>
#include<queue>
priotity_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;//最小值优先
priotity_queue<pair<int,int>,vector<pair<int,int> >,less<pair<int,int> > > q;//最大值优先
priority_queue<pair<int,int> > q;//什么都不加默认最大值优先;
q.push(make_pair(w,v));// pair默认按前者大小排序,故权值之类要放到前边;
w=q.top().first;
v=q.top().second;
2.结构体+比较函数
#include<queue>
struct ne{
int w;
int v;
};
struct cmp{
bool operator()(int &a,int &b){
return a>b; //最小值优先
}
};
struct cmp{
bool operator()(int &a,int &b){
return a<b; //最大值优先
}
};
priority_queue<ne,vector<ne>,cmp> q;
3.结构体+重载运算符
#include<queue>
struct ne{
int w;
int v;
bool operator < (const ne &a) const{
return w<a.w;//最大值优先
}
};
struct ne{
int w;
int v;
bool operator < (const ne &a) const{
return w>a.w;//最小值优先
}
};
priority_queue<int> q;
附:结构体内初始化及赋值
struct ne{
int x;
int y;
ne(){
x=0;
y=0;
}
ne(int a,int b){
x=a;y=b;
}
};
//具体应用
queue<ne> q; //栈,队列等的压入;
q.push(ne(x,y));
ne now; //结构体数据类型的赋值;
now=ne(x,y);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义