关于priority_queue的随笔

简介

A standard container automatically sorting its contents.

模板参数:
_Tp – Type of element.
_Sequence – Type of underlying sequence, defaults to vector<_Tp>.
_Compare – Comparison function object type, defaults to less<_Sequence::value_type>. This is not a true container, but an 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 front(), push_back, 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 less<value_type> but can be anything defining a strict weak ordering. Members not found in normal containers are container_type, which is a typedef for the second Sequence parameter, and * push, pop, and top, which are standard %queue operations.

仅有的几个成员函数

一段使用的示例代码

#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

struct Idea
{
    int id;      // Idea序号
    int pm;      // PM序号
    int useTime; //花费时间

    Idea(int id, int pm, int useTime) : id(id), pm(pm), useTime(useTime) {}

    friend ostream &operator<<(ostream &os, const Idea &idea)
    {
        os << idea.id << endl;
        return os;
    }
};
struct cmp
{
    // PM序号小在前面,序号相同时间少的在前面(堆排序)
    bool operator()(const Idea &a, const Idea &b)
    {
        if (a.pm != b.pm)
            return a.pm > b.pm;
        else
            return a.useTime > b.useTime;
    }
};

int main()
{
    priority_queue<Idea, vector<Idea>, cmp> priDeque;

    priDeque.emplace(Idea(1, 1, 5));
    priDeque.emplace(Idea(2, 1, 1));
    priDeque.emplace(Idea(3, 0, 1));
    priDeque.emplace(Idea(4, 0, 2));
    priDeque.emplace(Idea(5, 2, 3));
    while (!priDeque.empty())
    {
        Idea tmp = priDeque.top();
        priDeque.pop();
        std::cout << tmp;
    }
    std::cout << "************************************" << std::endl;
    priority_queue<int> numbers;
    numbers.emplace(5);
    numbers.emplace(78);
    numbers.emplace(12);
    numbers.emplace(56);
    numbers.emplace(4);
    numbers.emplace(45);
    while (!numbers.empty())
    {
        int tmp = numbers.top();
        numbers.pop();
        std::cout << tmp << " \t";
    }
    std::cout << std::endl;

    return 0;
}

上述代码运行结果:

priority_queue不是容器,它是容器适配器,按照优先级自动对内部元素排序,默认的比较仿函数是less<value_type>,但是这样的结果是元素从大到小排序(TOP K问题使用它直接解决了)。它支持自定义比较函数。

posted @ 2022-08-03 21:33  时间的风景  阅读(26)  评论(0编辑  收藏  举报