C++ STL之priority_queue的使用及模拟实现


1. 介绍

英文解释:

在这里插入图片描述

也就是说:

  1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。

  2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。

  3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。

  4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
    empty():检测容器是否为空
    size():返回容器中有效元素个数
    front():返回容器中第一个元素的引用
    push_back():在容器尾部插入元素
    pop_back():删除容器尾部元素

  5. 标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。

  6. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作。

作图理解:
在这里插入图片描述
关于其底层数据结构可以参照树、二叉树(C语言版)中==二叉树的顺序结构实现==部分的内容,这里重点讲解priority_queue的使用和其在库中的模拟实现。

2. priority_queue的使用

template <class T, class Container = vector<T>, class Compare = less<typename Container::value_type>> class priority_queue;

priority_queue是容器适配器。使用时需实例化其模板参数。

有三个模板参数:

  1. T:表示存储在优先级队列中的元素的类型。
  2. Container:表示用于存储元素的底层容器类型。默认情况下,它使用 vector<T>,但你可以根据需要指定其他容器类型。
  3. Compare:表示用于比较元素优先级的函数对象类型(传参可以用类重载operator()形成的仿函数)。默认情况下,它使用 less<typename Container::value_type>,这将使用元素类型的 < 运算符来进行比较。你也可以提供自定义的比较函数对象。即默认为==大堆==。

用法样例:

class mycomparison
{
    bool reverse;
public:
    mycomparison(const bool& revparam = false)
    {
        reverse = revparam;
    }
    bool operator() (const int& lhs, const int& rhs) const
    {
        if (reverse) return (lhs > rhs);
        else return (lhs < rhs);
    }
};

int main()
{
    int myints[] = { 10,60,50,20 };

    std::priority_queue<int> first;
    std::priority_queue<int> second(myints, myints + 4);
    std::priority_queue<int, std::vector<int>, std::greater<int> >
        third(myints, myints + 4);
    // using mycomparison:
    typedef std::priority_queue<int, std::vector<int>, mycomparison> mypq_type;

    mypq_type fourth;                       // less-than comparison
    mypq_type fifth(mycomparison(true));   // greater-than comparison

    return 0;
}

说明:

  • first 变量是空的 priority_queue 对象,使用默认的 less 比较,是大堆。
  • second 变量包含了四个整数,这四个整数由 myints 定义。默认使用 less 比较,所以为大堆,此时堆顶为60。
  • third 变量包含四个整数,只不过使用了 greater 比较,变成了小堆,此时堆顶为10。
  • fourth 变量是空的 priority_queue 对象,使用自定义的比较方式 mycomparision,此时同样为大堆。
  • fifth 变量是空的 priority_queue 对象,使用自定义的比较方式 mycomparision,同时传参 true 构造改变了operator()的返回值,此时为小堆。

注:这里由于 mycomparison 重载了operator(),所以可以作为仿函数充当形参。具体调用 mycomparison 时的操作,请看模拟实现部分。

接口成员函数

函数名称代码功能说明
emptybool empty() const;返回 priority_queue 是否为空。
sizesize_type size() const;返回 priority_queue 中元素个数。
topconst_reference top() const;返回堆顶元素的引用。
pushvoid push (const value_type& val);
void push (value_type&& val);
向 priority_queue 插入一个新元素 val。
popvoid pop();删除堆顶元素。
swapvoid swap (priority_queue& x) noexcept;用于和另一个容器适配器 x 交换内容。

priority_queue的遍历

#include <iostream>
#include <queue>

int main()
{
    int myints[] = { 10,60,50,20,30,100,200 };
    std::priority_queue<int> myPriorityQueue(myints, myints + sizeof(myints) / sizeof(int));

    // 使用迭代器遍历优先级队列
    std::priority_queue<int> tempQueue = myPriorityQueue; // 创建临时队列用于遍历
    while (!tempQueue.empty())
    {
        std::cout << tempQueue.top() << " ";
        tempQueue.pop();
    }

    return 0;
}

运行结果:

在这里插入图片描述

说明:

首先将其内容复制到一个临时队列 tempQueue 中,使用 top 函数访问临时队列的顶部元素,将其输出,然后使用 pop 函数将其从队列中移除。重复这个过程,直到临时队列为空。

3. priority_queue的模拟实现

#pragma once
#include<vector>

using namespace std;

namespace my_priority_queue
{
    // 大堆
    template<class T>
    struct less
    {
        bool operator()(const T& left, const T& right)
        {
            return left < right;
        }
    };
	
    // 小堆
    template<class T>
    struct greater
    {
        bool operator()(const T& left, const T& right)
        {
            return left > right;
        }
    };

    template <class T, class Container = vector<T>, class Compare = less<T>>
    class priority_queue
    {
    public:
        priority_queue()
        {}

        template <class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
            :c(first, last)
        {
            for (int i = (c.size() - 1 - 1) / 2; i >= 0; i--)
            {
                adjudge_down(i);
            }
        }

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

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

        const T& top() const
        {
            return c[0];
        }

        void push(const T& x)
        {
            c.push_back(x);
            adjudge_up(c.size() - 1);
        }

        void pop()
        {
            swap(c[0], c[c.size() - 1]);
            c.pop_back();
            adjudge_down(0);
        }

    private:
        void adjudge_up(size_t child)
        {
            if (child == 0)
                return;
            size_t parent = (child - 1) / 2;
            while (child > 0)
            {
                if (comp(c[parent], c[child]))
                {
                    swap(c[parent], c[child]);
                    child = parent;
                    parent = (child - 1) / 2;
                }
                else
                {
                    break;
                }
            }
        }

        void adjudge_down(size_t parent)
        {
            size_t child = parent * 2 + 1;
            while (child < c.size())
            {
                if (child + 1 < c.size() && comp(c[child], c[child + 1]))
                {
                    ++child;
                }

                if (comp(c[parent], c[child]))
                {
                    swap(c[parent], c[child]);
                    parent = child;
                    child = parent * 2 + 1;
                }
                else
                {
                    break;
                }
            }
        }

        Container c;
        Compare comp;
    };
};
  • 18
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++ STL中的priority_queue是一个优先队列,它是一个使用实现的容器。它可以按照一定的优先级顺序存储元素,并且每次访问队首元素都是访问优先级最高的元素。 在使用priority_queue时,可以通过定义不同的比较函数来指定元素的优先级顺序。默认情况下,对于基本类型,默认是大顶,降序队列。也可以通过指定参数来实现小顶,升序队列。例如: priority_queue<int, vector<int>, greater<int>> q; //小顶,升序队列 priority_queue<int, vector<int>, less<int>> q; //大顶,降序队列 在对priority_queue进行操作时,可以使用push()函数向队列中插入元素,使用top()函数获取队首元素,使用pop()函数删除队首元素。 在自定义类型的优先队列中,可以重载运算符>或<来定义优先级。例如,可以重载operator>来定义小顶,即优先级较小的元素排在前面。示例代码如下: struct Node{ int x, y; Node(int a=0, int b=0): x(a), y(b) {} }; bool operator> (Node a, Node b){ if(a.x == b.x) return a.y > b.y; return a.x > b.x; } priority_queue<Node, vector<Node>, greater<Node>> q; q.push(Node(rand(), rand())); while(!q.empty()){ cout<<q.top().x<<' '<<q.top().y<<endl; q.pop(); } 总结来说,C++ STL中的priority_queue是一个使用实现的优先队列,可以按照指定的优先级顺序存储元素。可以通过定义不同的比较函数或重载运算符来指定优先级规则。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【总结】C++ 基础数据结构 —— STL之优先队列(priority_queue) 用法详解](https://blog.csdn.net/weixin_44668898/article/details/102132580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自信不孤单

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值