C++中priority_queue默认为最大堆,top()返回最大元素;要实现最小堆需指定std::greater比较器;仅支持堆顶访问和增删,不支持遍历与修改。

在C++中,priority_queue 是标准模板库(STL)提供的**最大堆**实现,默认按元素值从大到小自动排序。它底层基于堆(通常是二叉堆),支持在 O(log n) 时间内插入和弹出最值元素。
默认情况下,priority_queue 是一个**最大堆**,顶部(top())返回最大元素:
std::priority_queue<int> pq;</int>
pq.push(3); pq.push(1); pq.push(4);
pq.top() → 返回 4(不删除)pq.pop(); → 移除 4,之后 top() 变为 3
pq.empty(),获取大小:pq.size()
要让 priority_queue 表现为**最小堆**(顶部是最小元素),需显式指定比较器:
std::greater<int></int>:std::priority_queue<int std::vector>, std::greater<int>> min_pq;</int></int>
std::priority_queue<int std::vector>, std::less<int>></int></int> 是默认最大堆;std::greater 翻转逻辑,使小的元素“优先”上浮auto cmp = [](const Node& a, const Node& b) { return a.cost > b.cost; };,然后声明为 priority_queue<node vector>, decltype(cmp)> pq(cmp);</node>
priority_queue 不提供遍历、查找或随机访问接口,仅支持堆顶操作和增删:
立即学习“C++免费学习笔记(深入)”;
begin()/end(),不能用范围 for 遍历内部元素std::vector,也可换为 std::deque(需显式指定,但极少必要)priority_queue<int> pq(v.begin(), v.end());</int>
优先队列天然适合需要动态维护“当前最优选择”的问题:
基本上就这些。用对比较器,理解它是只读顶+单向弹出的结构,就不容易踩坑。
以上就是C++如何使用优先队列(priority_queue)?(堆数据结构)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号