std::priority_queue是C++中基于堆的容器适配器,默认为最大堆,可通过greater或自定义比较实现最小堆;支持push、top、pop等操作,适用于优先级调度场景。

在C++中,std::priority_queue 是一个基于堆实现的容器适配器,用于自动维护元素的优先级顺序。默认情况下,它是一个最大堆,即顶部元素是队列中最大的。
包含头文件 #include <queue> 即可使用 priority_queue。
常见定义方式:
std::priority_queue<int> pq;:默认最大堆,顶部为最大值。std::priority_queue<int, std::vector<int>, std::greater<int>> pq;:最小堆,顶部为最小值。常用操作:
立即学习“C++免费学习笔记(深入)”;
当处理自定义类型(如结构体)或需要特殊排序规则时,需提供比较函数对象。
有三种方式实现自定义比较:
1. 函数对象(仿函数)
struct Person {
int age;
std::string name;
};
struct CompareAge {
bool operator()(const Person& a, const Person& b) {
return a.age < b.age; // 最大堆:按年龄从大到小
}
};
std::priority_queue<Person, std::vector<Person>, CompareAge> pq;
Lambda 不能直接作为模板参数传入 priority_queue,但可以封装在类中或使用别名技巧。更实用的是用函数对象或结构体重载。
3. 重载结构体内的 operator<
struct Person {
int age;
std::string name;
bool operator<(const Person& other) const {
return age < other.age; // 默认使用 <,构建最大堆
}
};
std::priority_queue<Person> pq;
注意:priority_queue 使用 less<T> 时是最大堆,使用 greater<T> 是最小堆。逻辑是:比较函数返回 true 时,第一个参数优先级更低。
一些实际开发中的建议:
std::greater 构建最小堆。a.age > b.age(最小堆逻辑)。示例:最小堆版本的 Person 队列
struct CompareYounger {
bool operator()(const Person& a, const Person& b) {
return a.age > b.age; // 年龄小的优先级高
}
};
std::priority_queue<Person, std::vector<Person>, CompareYounger> pq;
pq.push({30, "Alice"});
pq.push({20, "Bob"});
// top() 是 Bob(20岁)
基本上就这些。掌握默认行为、自定义比较方式和堆序逻辑,就能灵活使用 priority_queue 解决各类优先级调度问题。
以上就是c++++中std::priority_queue的用法和自定义比较函数 _c++ priority_queue使用技巧的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号