priority_queue 小值优先方法

版权声明:转载请注明出处 https://blog.csdn.net/TY_GYY/article/details/82531942

priority_queue默认为大顶堆,即堆顶元素为堆中最大元素。如果我们想要用小顶堆有两种方法

1. 对于非结构体的数据类型方法(int double 等等)

需要增加使用两个参数:

priority_queue<int, vector<int>, greater<int> > q;  // 小顶堆
priority_queue<int, vector<int>, less<int> > q;     // 大顶堆
//注意 > >必须分开 否则编译器会误认

2.  一般的方法

struct cmp{
    bool operator ()(const int a, const int b)const{//a 的优先级比b小时 return true
    return a>b;
    }
};
priority_queue <int,vector<int>,cmp >pq;

3.可以在结构体内进行重定义 <运算符

struct Temp{//小的优先
    int k;
    bool operator <(const Temp a)const{//a 的优先级比b小时 return true
    return k>a.k;
    }
};

猜你喜欢

转载自blog.csdn.net/TY_GYY/article/details/82531942