【C++STL】pirority_queue(优先队列)

简介

头文件:#include

定义:priority_queue
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆(即算子为less,小的往前排,大的往后排,出队时序列尾的元素出队)。同时默认使用vector来存储

//升序队列
priority_queue ,greater > q;
//降序队列
priority_queue ,less >q;

自定义算子

自定义算子有两种方法:

  1. 重写仿射函数,类似于sort那样。
  2. 重载运算符。
#include 
#include 
using namespace std;

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大顶堆
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b) 
    {
        return a.x < b.x; //大顶堆
    }
};

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

    priority_queue, tmp2> f;
    f.push(c);
    f.push(b);
    f.push(a);
    while (!f.empty()) 
    {
        cout << f.top().x << '\n';
        f.pop();
    }
}

参考:https://blog.csdn.net/weixin_36888577/article/details/79937886

 

你可能感兴趣的:(C++算法小模板,队列,stl,stack,docker,numpy)