头文件
#include < queue >
定义
priority_queue<int> name1;//默认最大值堆
priority_queue<int, vector<int>, greater<int>> name2;//最小值堆
priority_queue<int, vector<int>, less<int>> name3;//最大值堆
如果遇到结构体堆里面的内容是结构体
struct Goods {
int weight;
int value;
float val_wei;
};
priority_queue<Goods, vector<Goods>, less<Goods>> tmp;
会出现下面的报错
运算符不兼容。查看less的模板为:
根据模板仿写一个运算结构体:
struct cmp {
bool operator ()(Goods a, Goods b) { //通过传入不同类型来定义不同类型优先级
return a.val_wei < b.val_wei; //最大值优先
}
};
定义总结
priority_queue<int> name1;//默认最大值堆
priority_queue<int, vector<int>, greater<int>> name2;//最小值堆
priority_queue<int, vector<int>, less<int>> name3;//最大值堆
struct cmp {//结构体的比较结构体
bool operator ()(Goods a, Goods b) { //通过传入不同类型来定义不同类型优先级
return a.val_wei < b.val_wei; //最大值优先
}
};
priority_queue<Goods, vector<Goods>, cmp> name4;//结构体形式
常用操作
push()
用法 tmp.push(要加入的元素)
向堆中加入元素
pop()
tmp.pop()
把队首(堆顶)元素出队。无返回值
top()
tmp.top()
返回队首的元素
empty()
tmp.empty()
返回优先队列十分为空,空返回true,非空返回false
size()
tmp.size()
返回优先队列的元素数