c++怎么使用优先队列priority_queue_c++ 最大堆最小堆定义与应用【技巧】

std::priority_queue默认为最大堆,最小堆需指定std::greater为第三个模板参数;自定义类型须重载operator

怎么定义最大堆和最小堆

默认的 std::priority_queue 是最大堆,即顶部元素是最大值。想用最小堆,不能直接改比较逻辑,得换模板参数——关键是第三个模板参数要传入 std::greater(或其他对应类型的 std::greater)。

常见错误是只改了比较函数但忘了包含头文件或写错类型:

  • 漏掉 #include std::greater 会编译失败
  • 写成 std::greater(无模板参数)在旧标准下不兼容,建议显式写 std::greater
  • 自定义类型没提供 operator 或没传自定义比较器,会导致编译报错“no match for ‘operator
#include 
#include 

std::priority_queue max_heap;                    // 默认最大堆
std::priority_queue, std::greater> min_heap;  // 最小堆

为什么不能用 less 显式写最大堆

可以写,但没必要——std::less 就是默认第三个参数,等价于不写。真正要注意的是:它的作用是“决定谁该排在堆顶”,而 std::less(a, b) 返回 true 表示 a 应该排在 b 前面,这和堆的“大根/小根”逻辑是反直觉的。

简单记法:比较器返回 true 的方向,就是“优先级更高”的方向;堆顶永远是“优先级最高”的那个元素

  • std::less(a, b) 为 true ⇒ a
  • std::greater(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, CompareTask> task_queue;
  • 注意:返回 a.priority > b.priority 才能得到“优先级数字越小越先处理”的效果(即最小堆)
  • 如果用 operator,需定义为 bool operator 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 或手写堆。