priority_queue(结构体排序)

本文介绍了一个使用 C++ 实现的优先队列应用案例,通过自定义结构体和重载比较运算符实现对节点按特定条件进行排序的功能。文章通过一个具体的例子展示了如何在程序中使用优先队列,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
using namespace std;
struct node
{
 int id;
 int lv;
 friend bool operator < (const node x,const node y)///友源函数,重载函数
    {                 ///先根据等级排列,如果等级相同,则根据id排列
        if(x.lv==y.lv)
        {
            return x.id>y.id;///id大的排前面,因为pop是从后面开始的,top()也是从队列尾部输出的
        }
        return x.lv<y.lv;///lv大的排后面
    }
}tmp;
int main()
{
 int n;
 while(scanf("%d",&n)!=EOF)
 {
  tmp.id=0;///将id装入tmp中,方便,排列
  priority_queue<node> q[4];///输出时候用q[i].top()
  while(n--)                ///queue才是q[i].front()
  {
   string m;
   int i=0,a,b;
   cin>>m;
   if(m=="IN")
   {
    tmp.id++;
    cin>>a>>b;
    tmp.lv=b;
    q[a].push(tmp);///队列a(1~3)排列
   }
   else
   {
       cin>>a;
       if(!q[a].empty())///如果为非空就输出
        {
            cout<<q[a].top().id<<endl;
            q[a].pop();///输出完了就删除
        }else{
            puts("EMPTY");
     }
   }
  }
 }
 return 0;
}

priority_queue一般需要用到 friend bool operator来结构体内排序

priority_queue用.top()来输出


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值