首页 > 后端开发 > C++ > 正文

c++怎么使用std::priority_queue_c++ std::priority_queue使用方法

下次还敢
发布: 2025-09-28 17:24:01
原创
332人浏览过
std::priority_queue是C++中用于实现最大堆或最小堆的容器适配器,默认为大根堆,通过指定std::greater可创建小根堆,支持自定义比较规则,常用于求前K大/小元素、任务调度等场景。

c++怎么使用std::priority_queue_c++ std::priority_queue使用方法

在C++中,std::priority_queue 是一个容器适配器,用于实现最大堆(默认)或最小堆。它位于 <queue> 头文件中,提供快速访问最大(或最小)元素的功能,常用于贪心算法、Dijkstra最短路径、合并K个有序链表等场景。

包含头文件

使用前需要引入头文件:

#include <queue>

基本定义与默认用法(最大堆)

默认情况下,std::priority_queue 是一个大根堆,顶部元素是最大的。

std::priority_queue<int> pq;

常用操作:

立即学习C++免费学习笔记(深入)”;

  • pq.push(x):插入元素 x
  • pq.top():获取堆顶元素(最大值)
  • pq.pop():移除堆顶元素
  • pq.empty():判断是否为空
  • pq.size():返回元素个数

示例代码:

#include <iostream>
#include <queue>
int main() {
   std::priority_queue<int> pq;
   pq.push(10);
   pq.push(30);
   pq.push(20);

   while (!pq.empty()) {
     std::cout << pq.top() << " ";
     pq.pop();
   }
   // 输出:30 20 10
   return 0;
}

创建最小堆(小根堆)

要使用最小堆,需指定第三个模板参数为 std::greater<T>,并带上两个额外的容器参数。

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店
std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq;

说明:

  • 第一个参数:元素类型
  • 第二个参数:底层容器,默认是 std::vector<int>
  • 第三参数:比较函数对象,std::greater<int> 表示小顶堆

示例:

std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq;
min_pq.push(10);
min_pq.push(30);
min_pq.push(20);
while (!min_pq.empty()) {
   std::cout << min_pq.top() << " ";
   min_pq.pop();
}
// 输出:10 20 30

自定义比较函数(结构体或类)

如果存储的是结构体或需要特殊排序规则,可以自定义比较方式。

例如,按学生的分数升序排列

struct Student {
   int score;
   std::string name;
};

// 自定义比较结构体
struct Compare {
   bool operator()(const Student& a, const Student& b) {
     return a.score > b.score; // 小顶堆:score 小的优先级高
   }
};

std::priority_queue<Student, std::vector<Student>, Compare> pq_student;

这样就实现了以 score 为键的小根堆。

常见用途建议

  • 求前K大/小元素时,配合堆大小控制非常高效
  • 处理带优先级的任务调度
  • 配合算法如 Huffman 编码、Prim 最小生成树等
  • 注意:不支持遍历,也不能直接删除非堆顶元素

基本上就这些。掌握构造方式和比较器设置,就能灵活使用 std::priority_queue 了。

以上就是c++++怎么使用std::priority_queue_c++ std::priority_queue使用方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号