聊聊C++标准库中优先队列priority_queue的源码

本文详细介绍了C++标准库中的优先队列priority_queue,包括其内部实现、构造方式及成员函数。揭示了优先队列如何利用堆数据结构进行高效操作,以及如何自定义优先级比较。

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

C++标准库提供了优先队列priority_queue,顾名思义,就是可以按照优先级出队的队列,而且时间复杂度为 O ( l o g n ) O(logn) O(logn),算法中有很多优化项就是用优先队列来优化的。

C++11的标准库是怎么构造出优先队列的呢?优先队列是用堆来构造的。所以,优先队列其实并不能叫队列,它的完整定义应该是这样的:优先队列是用堆来构造,包装成队列的适配器

其实想一想,堆确实适合构造优先队列,优先队列每次需要弹出优先级最大的元素,而堆的堆顶恰巧就是优先级最大的元素,关于C++11中的堆,可以参考聊聊C++11标准库中堆(heap)算法的源码

那就一起来看看MinGW中C++11的标准库stl_queue.h中的priority_queue的源码。

先来看看标准库对优先队列的介绍:

/**
   *  @brief  A standard container automatically sorting its contents.
   *
   *  @ingroup sequences
   *
   *  @tparam _Tp  Type of element.
   *  @tparam _Sequence  Type of underlying sequence, defaults to vector<_Tp>.
   *  @tparam _Compare  Comparison function object type, defaults to 
   *                    less<_Sequence::value_type>.
   *
   *  This is not a true container, but an @e adaptor.  It holds
   *  another container, and provides a wrapper interface to that
   *  container.  The wrapper is what enforces priority-based sorting 
   *  and %queue behavior.  Very few of the standard container/sequence
   *  interface requirements are met (e.g., iterators).
   *
   *  The second template parameter defines the type of the underlying
   *  sequence/container.  It defaults to std::vector, but it can be
   *  any type that supports @c front(), @c push_back, @c pop_back,
   *  and random-access iterators, such as std::deque or an
   *  appropriate user-defined type.
   *
   *  The third template parameter supplies the means of making
   *  priority comparisons.  It defaults to @c less<value_type> but
   *  can be anything defining a strict weak ordering.
   *
   *  Members not found in @a normal containers are @c container_type,
   *  which is a typedef for the second Sequence parameter, and @c
   *  push, @c pop, and @c top, which are standard %queue operations.
   *
   *  @note No equality/comparison operators are provided for
   *  %priority_queue.
   *
   *  @note Sorting of the elements takes place as they are added to,
   *  and removed from, the %priority_queue using the
   *  %priority_queue's member functions.  If you access the elements
   *  by other means, and change their data such that the sorting
   *  order would be different, the %priority_queue will not re-sort
   *  the elements for you.  (How could it know to do so?)
  */

这里面大致说了优先队列支持哪些成员函数,用了哪个数据结构来存储元素,排序规则等等。

template <typename _Tp, typename _Sequence = vector<_Tp>,
          typename _Compare = less<typename _Sequence::value_type>>
class priority_queue
{
public:
    typedef typename _Sequence::value_type value_type;
    typedef typename _Sequence::reference reference;
    typedef typename _Sequence::const_reference const_reference;
    typedef typename _Sequence::size_type size_type;
    typedef _Sequence container_type;

protected:
    //  See queue::c for notes on these names.
    _Sequence c;
    _Compare comp;
}

模板参数中,_Sequence默认是vector<_Tp>,也就是说priority_queue默认以vector作为容器,但是支持任意有push_backpop_backfront成员函数,并且提供随机迭代器的容器;

然后就是容器必须的五个类型重定义;

成员函数只有序列c和比较函数comp

从类的模板参数可以看出来,如果想要自定义优先级,那么就必须把第二个模板参数显示地写出来,即std::priority_queue<int, std::vector<int>, std::greater<int>>

public:
    explicit priority_queue(const _Compare &__x,
                            const _Sequence &__s)
        : c(__s), comp(__x)
    {
        std::make_heap(c.begin(), c.end(), comp);
    }

    explicit priority_queue(const _Compare &__x = _Compare(),
                            _Sequence &&__s = _Sequence())
        : c(std::move(__s)), comp(__x)
    {
        std::make_heap(c.begin(), c.end(), comp);
    }

    template <typename _InputIterator>
    priority_queue(_InputIterator __first, _InputIterator __last,
                   const _Compare &__x,
                   const _Sequence &__s)
        : c(__s), comp(__x)
    {
        c.insert(c.end(), __first, __last);
        std::make_heap(c.begin(), c.end(), comp);
    }

    template <typename _InputIterator>
    priority_queue(_InputIterator __first, _InputIterator __last,
                   const _Compare &__x = _Compare(),
                   _Sequence &&__s = _Sequence())
        : c(std::move(__s)), comp(__x)
    {
        c.insert(c.end(), __first, __last);
        std::make_heap(c.begin(), c.end(), comp);
    }

可以看到,priority_queue的构造函数就是在造一个堆。

    bool empty() const
    {
        return c.empty();
    }

    size_type size() const
    {
        return c.size();
    }

    const_reference top() const
    {
        return c.front();
    }

    void push(const value_type &__x)
    {
        c.push_back(__x);
        std::push_heap(c.begin(), c.end(), comp);
    }

    void push(value_type &&__x)
    {
        c.push_back(std::move(__x));
        std::push_heap(c.begin(), c.end(), comp);
    }

    template <typename... _Args>
    void emplace(_Args &&... __args)
    {
        c.emplace_back(std::forward<_Args>(__args)...);
        std::push_heap(c.begin(), c.end(), comp);
    }

    void pop()
    {
        std::pop_heap(c.begin(), c.end(), comp);
        c.pop_back();
    }
    void swap(priority_queue &__pq) noexcept(noexcept(swap(c, __pq.c)) && noexcept(swap(comp, __pq.comp)))
    {
        using std::swap;
        swap(c, __pq.c);
        swap(comp, __pq.comp);
    }

这些都是priority_queue的成员函数,其中emplaceswap是C++11新增的成员函数,emplace默认调用std::vector::emplace_back来构造元素;

出队就std::pop_heap; std::vector::pop_back;,入队就std::vector::push_back; std::push_heap;

template <typename _Tp, typename _Sequence, typename _Compare>
inline void swap(priority_queue<_Tp, _Sequence, _Compare> &__x,
                 priority_queue<_Tp, _Sequence, _Compare> &__y) noexcept(noexcept(__x.swap(__y)))
{
    __x.swap(__y);
}

template <typename _Tp, typename _Sequence, typename _Compare, typename _Alloc>
struct uses_allocator<priority_queue<_Tp, _Sequence, _Compare>, _Alloc>
    : public uses_allocator<_Sequence, _Alloc>::type
{
};

这两个是C++11为priority_queue做的两个特化。

<think>好的,用户想了解C++优先队列priority_queue的用法,包括使用方法、示例、语法和解释。我需要根据提供的引用资料来整理回答。 首先,要确定priority_queue的基本用法。根据引用[1],priority_queueC++中需要包含头文件,但引用[4]提到头文件是<queue>,而引用[5]的例子也使用了#include <queue>,所以应该纠正引用[4]中的头文件错误。基本语法是priority_queue<类型, 容器, 比较函数>,默认使用vector作为容器,比较函数默认是less,形成大顶堆。 接下来,自定义比较函数部分。引用[1]和[2]提到可以使用仿函数或decltype来指定比较函数。例如,仿函数需要重载operator(),并且注意比较的逻辑,比如引用[2]中的例子用*a > *b实现小顶堆。同时,引用[3]展示了使用less和greater来创建大顶堆和小顶堆的不同方法。 然后,示例部分。引用[5]提供了基本的示例代码,使用默认的priority_queue,输出是按大顶堆排列。需要补充小顶堆的示例,以及使用自定义比较函数的例子,比如结构体或指针的比较。 需要注意语法中的细节,比如模板参数的位置,使用decltype时需要配合构造函数传递比较函数对象,如引用[1]中的例子。此外,在C++17之后可能可以省略模板参数,但为了兼容性最好明确指定。 用户可能的问题包括如何调整堆的类型、自定义数据结构的比较方法,以及为什么使用仿函数。需要确保回答覆盖这些点,并引用正确的资料。例如,引用[3]解释了大顶堆和小顶堆的不同声明方式,引用[2]展示了指针类型的比较方法。 最后,生成相关问题,可能涉及性能、应用场景或与其他容器的比较。需要确保问题与主题相关,并基于引用内容,比如比较函数的实现方式或优先队列时间复杂度。 总结回答结构:基本用法、自定义比较函数的三种方法、示例代码、注意事项,然后相关问题。确保每个部分都有对应的引用支持,并正确标注引用标识。</think>### C++priority_queue的用法详解 #### 1. 基本语法与默认行为 优先队列`priority_queue`是C++标准库提供的**堆数据结构**实现,包含在头文件`<queue>`中[^4][^5]。其默认行为为**大顶堆**(降序排列),声明语法为: ```cpp priority_queue<T, Container, Compare> pq; ``` - `T`:元素类型(如`int`、`string`) - `Container`:底层容器(默认`vector<T>`) - `Compare`:比较函数(默认`less<T>`,即大顶堆) 例如,创建整数大顶堆: ```cpp priority_queue<int> pq; // 等价于 priority_queue<int, vector<int>, less<int>> ``` #### 2. 自定义比较函数方法 ##### (1) 使用内置函数对象 通过`greater<T>`创建**小顶堆**(升序排列): ```cpp priority_queue<int, vector<int>, greater<int>> min_heap; // 小顶堆[^3] ``` ##### (2) 自定义仿函数(推荐) 定义含`operator()`的类,例如处理指针类型: ```cpp class Compare { public: bool operator()(int* a, int* b) { return *a > *b; // 小顶堆比较规则[^2] } }; priority_queue<int*, vector<int*>, Compare> ptr_heap; ``` ##### (3) 使用decltype与lambda表达式(C++11+) 适用于需要动态比较逻辑的场景: ```cpp auto cmp = [](int a, int b) { return a > b; }; priority_queue<int, vector<int>, decltype(cmp)> custom_heap(cmp); // 需传递lambda对象[^1] ``` #### 3. 完整示例代码 ##### 示例1:默认大顶堆 ```cpp #include <iostream> #include <queue> using namespace std; int main() { int arr[] = {3, 1, 4, 1, 5}; priority_queue<int> pq; for (int x : arr) pq.push(x); while (!pq.empty()) { cout << pq.top() << " "; // 输出:5 4 3 1 1 pq.pop(); } return 0; } ``` ##### 示例2:结构体排序 ```cpp struct Node { int value; Node(int v) : value(v) {} }; struct NodeCompare { bool operator()(const Node& a, const Node& b) { return a.value < b.value; // 按value降序排列 } }; priority_queue<Node, vector<Node>, NodeCompare> node_heap; ``` #### 4. 关键注意事项 1. **时间复杂度**:插入(`push`)和删除堆顶(`pop`)操作均为$O(\log n)$,访问堆顶(`top`)为$O(1)$[^3] 2. **元素类型要求**:比较函数需满足**严格弱序**关系 3. **容器选择**:底层容器必须支持随机访问迭代器(如`vector`或`deque`)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值