【C++】优先队列priority_queue(转载)
https://blog.csdn.net/weixin_36888577/article/details/79937886
1 基本用法:
//升序队列 priority_queue <int,vector<int>,greater<int> > q; //降序队列 priority_queue <int,vector<int>,less<int> >q; //greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
2 自定义比较方式
static bool cmp(pair<int, int>& m, pair<int, int>& n) { return m.second > n.second; } priority_queue<pair<int, int>, vector<pair<int, int>>,decltype(&cmp)> q(cmp);
题目 https://leetcode-cn.com/problems/top-k-frequent-elements/submissions/
decltype关键字 https://www.cnblogs.com/ghbjimmy/p/10636030.html
3 自定义类型
#include <iostream> #include <queue> using namespace std; //方法1 struct tmp1 //运算符重载< { int x; tmp1(int a) {x = a;} bool operator<(const tmp1& a) const { return x < a.x; //大顶堆 } }; //方法2 struct tmp2 //重写仿函数 { bool operator() (tmp1 a, tmp1 b) { return a.x < b.x; //大顶堆 } }; int main() { tmp1 a(1); tmp1 b(2); tmp1 c(3); priority_queue<tmp1> d; d.push(b); d.push(c); d.push(a); while (!d.empty()) { cout << d.top().x << '\n'; d.pop(); } cout << endl; priority_queue<tmp1, vector<tmp1>, tmp2> f; f.push(c); f.push(b); f.push(a); while (!f.empty()) { cout << f.top().x << '\n'; f.pop(); } }