priority_queue里面自定义类型的使用。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 struct tree{ 5 int num; 6 string s; 7 tree(int x,string zfc) 8 { 9 num=x; 10 s=zfc; 11 } 12 friend bool operator>(const tree &a,const tree &b) 13 { 14 return a.num>b.num; 15 } 16 /* 显然用不用友元来重载是不一样滴*/ 17 /*bool operator<(const tree &a)const 18 { 19 return a.num>num; 20 }*/ 21 bool operator==(const tree &a)const 22 { 23 return a.num>num; 24 } 25 }; 26 /* 两个重载的<,随便一个都可以,显然里面和外面重载参数个数是不同滴*/ 27 bool operator<(tree a,tree b) 28 { 29 return a.s<b.s; 30 } 31 int main() 32 { 33 priority_queue<tree> q; 34 /* 因为要用到优先队列,所以必须重载<*/ 35 tree t(5,"hh"); 36 q.push(t); 37 tree r(4,"xx"); 38 q.push(r); 39 while(!q.empty()) 40 { 41 cout<<q.top().num<<" "<<q.top().s<<endl; 42 q.pop(); 43 } 44 if(r==t) 45 cout<<"hh"; 46 else 47 cout<<"xx"; 48 }
这是优先队列里面装一个普通的自定义类型。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 typedef struct tree* T; 5 struct tree{ 6 int num; 7 string s; 8 T next; 9 tree(){ 10 } 11 tree(int x,string zfc) 12 { 13 num=x; 14 s=zfc; 15 } 16 friend bool operator<(const tree a,const tree b) 17 { 18 return b.num>a.num; 19 } 20 }; 21 struct cmp{ 22 bool operator()(T a,T b) 23 { 24 return a->num>b->num; 25 } 26 }; /* 使用结构体重载排序函数,priority_queue中就必须写好3个参数*/ 27 int main() 28 { 29 // priority_queue<T,vector<T>,cmp> q; 30 priority_queue<T> q;/* 不知道为啥,这里创造优先队列,没有重载排序函数,它也没有报错了*/ 31 T t=new tree();/* 指针类型必须分配空间*/ 32 t->num=5; 33 t->s="hhh"; 34 q.push(t); 35 T r=new tree(); 36 r->num=4; 37 r->s="xxx"; 38 q.push(r); 39 T h=new tree(3,"nn"); 40 q.push(h); 41 while(!q.empty()) 42 { 43 cout<<q.top()->num<<" "<<q.top()->s<<endl; 44 q.pop(); 45 } 46 }
要是用3个参数的priority_queue,就要用结构体重载排序函数了。然后再使用过程中,遇到了一些问题,也不知道为什么。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单