priority_queue理解与使用

描述

在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素在顶部。优先队列具有最高级先出 (first in, largest out)的行为特征。

优先队列有三个参数,其声明形式为:

priority_queue< type, container, function >

这三个参数,后面两个可以省略,第一个不可以。
其中:

  • type:数据类型;
  • container:实现优先队列的底层容器;
  • function:元素之间的比较方式;

对于container,要求必须是数组形式实现的容器,例如vector、deque,而不能使list。

成员函数

假设type类型为int,则:

  • bool empty() const
    返回值为true,说明队列为空;
  • int size() const
    返回优先队列中元素的数量;
  • void pop()
    删除队列顶部的元素,也即根节点
  • int top()
    返回队列中的顶部元素,但不删除该元素;
  • void push(int arg)
    将元素arg插入到队列之中;

使用示例

#include <iostream>
#include <queue>
using namespace std;

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const //假想成a为后来者
    {
        return x < a.x; //大顶堆  满足条件直接放在后面,不满足条件就换位置
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b) //假想成b为后来者
    {
        return a.x < b.x; //大顶堆
	//return a.x > b.x; //小顶堆  满足条件直接放在后面,不满足条件就换位置
    }
};

int main()
{
    tmp1 a(1);
    tmp1 b(2);
    tmp1 c(3);
    priority_queue<tmp1> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while (!d.empty())
    {
        cout << d.top().x << '\n';
        d.pop();
    }
    cout << endl;

    priority_queue<tmp1, vector<tmp1>, tmp2> f;
    f.push(b);
    f.push(c);
    f.push(a);
    while (!f.empty())
    {
        cout << f.top().x << '\n';
        f.pop();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值