c++ priority_queue 优先队列

C++ 标准模板库中的 priority_queue 是一种特殊的容器,它总是保证顶部元素具有最高优先级。默认情况下,它使用大顶堆策略,即 top 元素是最值。可以通过自定义比较函数实现小顶堆。priority_queue 的成员函数包括 top、empty、size、push 和 pop,分别用于访问顶部元素、检查是否为空、获取元素数量、插入和移除元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

priority_queue
Syntax:

In their implementation in the C++ Standard Template Library, priority queues take three template parameters:1
2 template < class T, class Container = vector,
class Compare = less > class priority_queue;

Where the template parameters have the following meanings:
T: Type of the elements.
Container: Type of the underlying container object used to store and access the elements.
Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and a and b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less, which returns the same as applying the less-than operator .
The priority_queue object uses this expression when an element is inserted or removed from it (using push or pop, respectively) to grant that the element popped is always the greater in the priority queue.

T
容器所包含的元素的类型。
在类模板内部,使用其别名为 value_type 的成员类型。
Container
底层的用于存储元素的容器的类型。必须是用数组实现的容器,比如 vector, deque 但不能用 list.
Compare
一个二元谓词,以两个元素为参数返回一个 bool 值。
可以是函数指针(Function pointer)类型或函数对象(Function object)类型。STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。
如果要用到小顶堆,则一般要把模板的三个参数都带进去。
STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆

priority_queue<intvector<int>, greater< int> > qi2;

自定义优先级 compare
首先看一下less模板类:

template <class T> struct less {  
  bool operator() (const T& x, const T& y) const {return x<y;}  
  typedef T first_argument_type;  
  typedef T second_argument_type;  
  typedef bool result_type;  
};  

在一个struct里面实现了()操作符,我们可以类比这个方式实现自己的比较函数。

小顶堆的比较函数如下:

struct bigger{
        bool operator()(pair<int,int> &a,pair<int,int>&b)
        {
            return a.first > b.first;
        }
    };

大顶堆的比较函数如下:

struct smaller{
        bool operator()(class &a,class &b)
        {
            return a.first < b.first;
        }
    };

priority_queue成员函数
top 访问顶部元素
empty 判断是否为空
size 返回有效元素个数
push 在容器顶部插入元素
pop 移除容器顶部的元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值