priority_queue用法简记

堆是一种很常用的数据结构,自己手打堆当然可以,但是为了不必要的出错,一般可以选择c++ STL中的优先队列priority_queue。

首先是库的调用。

#include<queue>
using namespace std;

然后就是优先队列的声明。

priority_queue<int> q; //默认q是大根堆

如果要使用小根堆,可以这样写。

priority_queue<int,vector<int>,greater<> > q;
//那个vector<int>代表存放数据的容器,greater<>代表元素比较方式
//注意最后要写成> >,尽量避免被认为是>>运算符

当然如果数据类型是自定义结构体的话,还可以通过重载运算符的方式。

struct s {
    int w;
    bool operator < (const s& rhs) const { //都是重载<运算符
        return w>rhs.w;
    }
};

猜你喜欢

转载自www.cnblogs.com/Mr94Kevin/p/9575181.html