c++11 stl priority_queue自定义比较函数

2,239 阅读1分钟

概念

priority_queue<class Type,class Container,class Compare>

优先级队列,堆。

常用操作

push() //增加元素
pop()  //删除堆顶元素
top()  //返回堆顶元素值

自定义比较函数

#include<bits/stdc++.h>

using namespace std;

// 自定义比较函数,需重载 () 运算符
struct cmp {
    bool operator() (pair<int, int> &a, pair<int, int> &b) {
        return a.first > b.first;   // 小根堆
    }
};

// 自定义数据结构,需重载 < 运算符
struct Info
{
    int h_;
    Info(int h) : h_(h) {}

    bool operator<(const Info& t) const // 不加const会报错!
    {
        return h_ > t.h_; // 小根堆
    }
};

int main() {
    // 默认大根堆, 第三个参数 less<int> 可以不加
    priority_queue<int, vector<int>, less<int>> q1;
    // 小根堆
    priority_queue<int, vector<int>, greater<int>> q2;
    // 自定义比较函数
    priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q3;
    // 自定义数据类型
    priority_queue<Info, vector<Info>> q4;
}