列举了四种用法,分别是默认降序、内置的greater升序、重载<运算符、仿函数。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
#include <algorithm>
using namespace std;
using LL = long long;
const int inf = 0x3f3f3f3f;
struct node
{
node(int i) { v = i; }
int v;
bool operator < (const node & n) const { return v < n.v; } // 实际上是给定优先级,这里意味着降序,跟sort是相反的
};
struct cmp
{
bool operator()(const node & a, const node & b) const { return a.v > b.v; } // 这是升序,小顶堆
};
int main()
{
srand((unsigned int) time(0));
priority_queue<int> pq; // 默认是大顶堆,降序
//priority_queue<int, vector<int>, greater<int> > pq; // 小顶堆,第三个参数是仿函数
// 自定义类型有两种方法
//priority_queue<node> pq; // 重载小于号
//priority_queue<node, vector<node>, cmp> pq; // 仿函数
// 随机插入10个
for (int i = 0; i < 10; i++)
{
pq.push(rand() % 100);
}
// 打印
while (!pq.empty())
{
cout << pq.top() << endl;//前两种
//cout << pq.top().v << endl;//后两种
pq.pop();
}
return 0;
}