优先队列的两种自定义排序方式

首先简单的优先队列的定义方法有三种

1.默认从大到小排序

priority_queue<int>q;

2.等价于上面(从大到小排序)

priority_queue<int,vector<int>,less<int> >q;//注意这里最后的两个>要分开

3.定义从小到大排序的优先队列

priority_queue<int,vector<int>,greater<int> >q;

定义包含结构体的多级优先队列

1.定义在结构体内的友元函数方法

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long int LL;
const int MAXN(1e5);
struct node {
    int x,y;
    friend bool operator <(node p,node q) {
        return p.x>q.x; // >号代表从小到大排序 (按照x排序)
    }
}nod;
priority_queue<node>q;
int main() {
    q.push(node{2,3});
    q.push(node{1,5});
    q.push(node{5,4});
    while(!q.empty()) {
        cout<<q.top().x<<" "<<q.top().y<<endl;
        q.pop();
    }
}

 

 

2.定义在结构体外,自定义排序函数

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long int LL;
const int MAXN(1e5);
struct node {
    int x,y;
}nod;
struct cmp {
    bool operator() (const node &p,const node &q) {
        return p.x>q.x;// >号代表从小到大排序
    }
};
priority_queue<node,vector<node>,cmp>q;
int main() {
    q.push(node{2,3});
    q.push(node{1,5});
    q.push(node{5,4});
    while(!q.empty()) {
        cout<<q.top().x<<" "<<q.top().y<<endl;
        q.pop();
    }
}

注意的地方

优先队列和普通队列有两点不同:

第一是获得队首元素的写法是q.top(),普通队列是q.front()

第二是写代码的过程中踩过的坑:

在上述自定义结构体排序中,如果是普通队列套结构体,可以利用以下写法对结构体内的队首元素进行修改

q.front().x=v;

但是在优先队列里不能这样进行修改。

(虽然是个小问题,但是在有的代码中,优先队列不能这样直接修改元素会增加代码的编写难度,个人认为)

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值