priority_queue 结构体类型

记录一下,以后不能忘了!!

如果priority_queue插入结构体类型的变量,需要重载<运算符

有两种重载<运算符方式:
1.在结构体内部写重载

举例:

#include<cstdio>
#include<queue>
using namespace std;
struct Node{
    int a, b;
    bool operator <(const Node &x)const
    {
        return a < x.a;
    }
}node[100];


int main()
{
    priority_queue<Node> que;
    int N;
    scanf("%d",&N); 
    for(int i=0; i<N; i++)
    {
        scanf("%d%d",&node[i].a, &node[i].b);
        que.push(node[i]);
    }
    printf("\n");
    while(!que.empty())
    {
        Node u = que.top(); que.pop();
        printf("%d %d\n",u.a, u.b);
    }
    return 0;
}

2.在结构体外部写重载
举例:

#include<cstdio>
#include<queue>
using namespace std;
struct Node{
    int a, b;
}node[100];

bool operator <(const Node &x, const Node &y)
{
    return x.a < y.a;
}
int main()
{
    priority_queue<Node> que;
    int N;
    scanf("%d",&N); 
    for(int i=0; i<N; i++)
    {
        scanf("%d%d",&node[i].a, &node[i].b);
        que.push(node[i]);
    }
    printf("\n");
    while(!que.empty())
    {
        Node u = que.top(); que.pop();
        printf("%d %d\n",u.a, u.b);
    }
    return 0;
}

这样优先队列的优先级就重写好了。重载根据自己要求写就行。


运行图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值