priority_queue是STL中基于堆实现的容器适配器,默认为大顶堆,可通过greater或自定义比较器实现小顶堆或结构体排序,常用于Dijkstra、任务调度等场景。

在C++中,priority_queue 是 STL 中的一个容器适配器,用于实现一个自动排序的队列,默认情况下它是一个大顶堆(最大值优先)。也就是说每次取出的元素都是当前队列中最大的。
基本用法和头文件
使用 priority_queue 需要包含头文件:
#include定义方式如下:
std::priority_queue常用操作示例
下面是一个基础使用例子:
立即学习“C++免费学习笔记(深入)”;
#include iostream>#include
using namespace std;
int main() {
priority_queue
pq.push(10);
pq.push(30);
pq.push(20);
cout
pq.pop();
cout
return 0;
}
小顶堆(最小堆)怎么实现?
默认是大顶堆,如果需要小顶堆,可以使用 greater 比较器:
#include#include
#include
std::priority_queue
min_pq.push(10);
min_pq.push(30);
min_pq.push(20);
cout
注意:第二个参数是底层容器(通常是 vector),第三个是比较函数对象。
自定义结构体的优先队列
比如我们有一个学生结构体,想按成绩从高到低排序:
struct Student {string name;
int score;
Student(string n, int s) : name(n), score(s) {}
};
// 自定义比较函数
struct Compare {
bool operator()(const Student& a, const Student& b) {
return a.score }
};
std::priority_queue
stu_pq.push(Student("Alice", 85));
stu_pq.push(Student("Bob", 90));
stu_pq.push(Student("Charlie", 78));
cout
常见成员函数
- push(x):插入元素 x
- pop():移除堆顶元素
- top():获取堆顶元素(只读)
- empty():判断是否为空
- size():返回元素个数
基本上就这些。priority_queue 在 Dijkstra 算法、合并 K 个有序链表、任务调度等场景中非常实用。不复杂但容易忽略细节,比如小顶堆的模板写法。








