优先队列之自定义比较函数

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <string>

using namespace std;

struct cmp{
    /*在左边(也就是队尾),优先级越低
     * 默认使用less,小数在左边优先级越低
     * 可选greater,大数在左边优先级越低
     *
     * */
    bool operator ()(int a,int b){
        return a<b;//小的放左边,即less
    }
};

struct cmp2{
    bool operator ()(int a,int b){
        return a>b;//大的放左边,即greater
    }
};

int main(){
    priority_queue<int,vector<int>,cmp> pq;
    pq.push(4);
    pq.push(8);
    pq.push(1);
    pq.push(5);

    while(!pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
}

cmp返回8541,cmp2返回1458

posted @ 2019-02-27 22:33  开局一把刀  阅读(9)  评论(0)    收藏  举报