一、优先队列基础用法(必掌握)
1. 头文件与初始化
cpp
#include <iostream>
#include <queue> // 核心头文件
using namespace std;
// 1. 默认大顶堆(存储int,底层vector)
priority_queue<int> pq1;
// 2. 小顶堆(指定greater<int>)
priority_queue<int, vector<int>, greater<int>> pq2;
// 3. 用容器初始化
vector<int> vec = {3,1,4};
priority_queue<int> pq3(vec.begin(), vec.end()); // 大顶堆,top=4
priority_queue<int, vector<int>, greater<int>> pq4(vec.begin(), vec.end()); // 小顶堆,top=1
2、priority_queue 的模板定义(核心框架)
(1)先明确 priority_queue 的模板定义
cpp
template <class T, class Container = vector<T>, class Compare = less<T>>
class priority_queue;
(2)逐个解析参数
第一个参数、优先队列存储的元素类型
第二个参数、底层存储的容器类型
第三个参数、优先级的比较规则
3. 核心操作(高频接口)
|-----------|--------------|---------|
| push(val) | 插入元素,自动调整堆 | O(logn) |
| pop() | 删除队首元素,自动调整堆 | O(logn) |
| top() | 访问队首元素(仅读) | O(1) |
| empty() | 判断是否为空 | O(1) |
| size() | 获取元素个数 | O(1) |
基础示例(大顶堆):
cpp
priority_queue<int> pq;
pq.push(3); pq.push(1); pq.push(4);
cout << pq.top() << endl; // 4(最大值)
pq.pop(); // 删除4
cout << pq.top() << endl; // 3(新的最大值)
// 遍历(仅能通过pop逐个访问,会清空队列)
while (!pq.empty()) {
cout << pq.top() << " "; // 3 1
pq.pop();
}
基础示例(小顶堆):
cpp
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(3); pq.push(1); pq.push(4);
cout << pq.top() << endl; // 1(最小值)
pq.pop();
cout << pq.top() << endl; // 3(新的最小值)
二、自定义优先级(高频进阶用法)
默认优先级仅支持基础类型,存储结构体 /pair 时需手动定义规则,这是刷题的核心考点:
场景 1:存储 pair 类型(默认规则)
cpp
priority_queue<pair<int, int>> pq;
pq.push({2, 3}); pq.push({1, 5}); pq.push({2, 2});
// 输出顺序:(2,3) → (2,2) → (1,5)
while (!pq.empty()) {
cout << "(" << pq.top().first << "," << pq.top().second << ") ";
pq.pop();
}
场景 2:存储结构体(自定义优先级)
方式 1:结构体重载 < 运算符(推荐
cpp
struct Node {
int val;
int id;
// 重载 <:val 大的优先(大顶堆)
bool operator<(const Node& other) const {
// 注意:优先队列比较是「反向」的------a < b 表示 b 优先级更高
return this->val < other.val;
// 若要小顶堆(val 小的优先):return this->val > other.val;
}
};
priority_queue<Node> pq;
pq.push({3,1}); pq.push({1,2}); pq.push({5,3});
// 输出:(5,3) → (3,1) → (1,2)
方式 2:自定义比较器(灵活调整)
cpp
struct Node { int val; int id; };
// 自定义比较器:val 小的优先(小顶堆)
struct CompareNode {
bool operator()(const Node& a, const Node& b) {
return a.val > b.val; // > 表示小顶堆,< 表示大顶堆
}
};
priority_queue<Node, vector<Node>, CompareNode> pq;
pq.push({3,1}); pq.push({1,2}); pq.push({5,3});
// 输出:(1,2) → (3,1) → (5,3)