std::priority_queue默认为最大堆,最小堆需指定std::greater<int>为第三个模板参数;自定义类型须重载operator<或提供比较仿函数;pop后不可直接调用top,须先判空。

怎么定义最大堆和最小堆
默认的 std::priority_queue 是最大堆,即顶部元素是最大值。想用最小堆,不能直接改比较逻辑,得换模板参数——关键是第三个模板参数要传入 std::greater<int></int>(或其他对应类型的 std::greater)。
常见错误是只改了比较函数但忘了包含头文件或写错类型:
- 漏掉
#include <functional>,std::greater会编译失败 - 写成
std::greater<>(无模板参数)在旧标准下不兼容,建议显式写std::greater<int></int> - 自定义类型没提供
operator<或没传自定义比较器,会导致编译报错“no match for ‘operator<’”
#include <queue> #include <functional> std::priority_queue<int> max_heap; // 默认最大堆 std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap; // 最小堆
为什么不能用 less<int> 显式写最大堆
可以写,但没必要——std::less<int></int> 就是默认第三个参数,等价于不写。真正要注意的是:它的作用是“决定谁该排在堆顶”,而 std::less<T>(a, b) 返回 true 表示 a 应该排在 b 前面,这和堆的“大根/小根”逻辑是反直觉的。
简单记法:比较器返回 true 的方向,就是“优先级更高”的方向;堆顶永远是“优先级最高”的那个元素。
立即学习“C++免费学习笔记(深入)”;
-
std::less<int>(a, b)为 true ⇒ a < b ⇒ b 更大 ⇒ b 优先级更高 ⇒ 最大堆 -
std::greater<int>(a, b)为 true ⇒ a > b ⇒ a 更大 ⇒ a 优先级更高 ⇒ 最小堆?不对!等等——其实这里容易绕晕,直接按效果记更稳:用greater就是最小堆,别纠结内部调用顺序
自定义结构体怎么进 priority\_queue
两种方式:重载 operator<,或传 lambda / 函数对象(C++20 起支持 lambda 作为模板参数,但多数项目仍用仿函数或普通函数)。
推荐用仿函数(struct + operator()),清晰且兼容性好:
struct Task {
int id;
int priority;
};
struct CompareTask {
bool operator()(const Task& a, const Task& b) {
return a.priority > b.priority; // 小 priority 先出队 → 最小堆语义
}
};
std::priority_queue<Task, std::vector<Task>, CompareTask> task_queue;
- 注意:返回
a.priority > b.priority才能得到“优先级数字越小越先处理”的效果(即最小堆) - 如果用
operator<,需定义为bool operator<(const Task& b) const { return priority > b.priority; },否则默认按<解释会变成最大堆 - lambda 不能直接做模板参数(除非 C++20 并配合
decltype),不建议初学强行用
常见误用:pop 后访问 top 导致未定义行为
这是运行时最隐蔽的坑:pop() 不返回值,只删顶;删完立刻调 top() 是未定义行为(空堆访问)。调试时可能偶然不崩,上线后随机 crash。
- 正确做法:先
!q.empty()判断,再top(),再pop() - 想“取并删”,必须两步,没有原子操作
- 某些算法题里反复写
if (!q.empty()) { auto x = q.top(); q.pop(); ... }是标准套路,别省
另外,priority_queue 不支持遍历、查找、中间修改——它不是容器,是适配器。需要这些功能?换 std::set 或手写堆。









