优先队列中使用自定义排序

原文:https://blog.csdn.net/Akatsuki__Itachi/article/details/84142336

简单优先队列的定义方法

//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();
    }
}
  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;
}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();
    }
}
  1. 优先队列中使用 pair , 自定义排序(新增)
    参考
typedef pair<int,int> pii;
struct cmp
{
    bool operator() (const pii p1,const pii p2)
    {
        return p1.first > p2.first;         // first 小的先弹出
    }
};
 
priority_queue<pii,vector<pii>,cmp> Q;

注意的地方

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

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

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

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

q.front().x=v;

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

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值