优先队列及其优先级设置

优先队列也是用 #include<queue> 这个头文件,且不必引入vector的头文件

基础类型优先级设置

默认定义: 
priority_queue<int> 大顶堆

手工设置:

  • priority_queue<int, vector<int>, less<int>> 大顶堆:表示其他都比堆顶小
  • priority_queue<int, vector<int>, greater<int>> 小顶堆:表示其他都比堆顶大

后面补充的两个参数:内部用容器+规则。

既然默认是大顶堆,所以手动设置时只用管小顶堆即可,greater!.

#include <cstdio>
// #include <vector>
#include <queue>

using namespace std;

int main()
{
    priority_queue<int, vector<int> ,greater<int> >  q;
    q.push(3);
    q.push(2);
    q.push(1);

    printf("%d\n", q.top());
    return 0;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

结构体设置优先级:

只可在结构体内部重载小于号。

两种重置用法:

  • 运算符重载 + 友元
struct fruit
{
    string name;
    double price;
    friend bool operator< (fruit f1, fruit f2)
    {
        return f1.price < f2.price; // 相当于less,这是大顶堆,反之则是小顶堆
    }
} f1, f2, f3; //定义三个结构体变量

这样直接可以:
`priority_queue<fruit > q;`
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 比较运算符外置
struct fruit
{
    string name;
    double price;
} f1, f2, f3; //定义三个结构体变量

struct cmp
{
    bool operator () (fruit f1, fruit f2) // 重载括号
    {
        return f1.price < f2.price; // 等同于less
    }
};
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

调用语法是:priority_queue<fruit,vector<fruit> , cmp > q; //这个和基本类型的用法就相似了,只不过是用cmp代替了less或者greater

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值