c++优先队列自定义排序

2018/01/26 C 共 520 字,约 2 分钟

引入头文件queue

定义排序规则:

1.在优先队列中存储常用类型时,利用自定义结构体cmp来实现自定义的<比较。

    struct cmp{
        bool operator()(int &x,int &y){
            return test[x]>test[y];
        }
    };
    priority_queue<int,vector<int>,cmp> que1;

2.在优先队列中存储自定义数据类型时,只需要在自定义类型中重载<比较。

别忘记加两个const,否则无法类型转换

    struct node{
        int x, y;
        bool operator<(const node &nod)const{
            return x>nod.x;//x越小,优先级越高
        }
    };
    priority_queue<node>que3;
  1. 对于常用数据类型,使用functional头文件

大顶堆

priority_queue<int, vector<int>, less<int>> pq;

小顶堆

priority_queue<int, vector<int>, greater<int>> pq;

Search

    Table of Contents