c++的priority_queue和sort重载函数
时间: 2025-03-26 18:15:14 浏览: 31
### C++ 中 `priority_queue` 和自定义比较器
在 C++ 的标准模板库(STL)中,`std::priority_queue` 是一种容器适配器,默认情况下它是一个最大堆。为了改变其行为并实现最小堆或其他排序逻辑,可以提供一个自定义的比较函数。
#### 自定义优先级队列
当创建 `std::priority_queue` 时,可以通过传递第三个参数来指定不同的比较方式:
```cpp
#include <queue>
#include <functional>
struct Compare {
bool operator()(const int& lhs, const int& rhs) const {
return lhs > rhs;
}
};
std::priority_queue<int, std::vector<int>, Compare> minHeap;
// 或者使用 lambda 表达式作为比较器
auto cmp = [](int a, int b){return a > b;};
std::priority_queue<int, std::vector<int>, decltype(cmp)> customPQ(cmp);
```
上述代码展示了如何通过结构体或 Lambda 函数来自定义比较操作[^1]。
#### 排序算法中的重载函数
对于内置类型的数组或向量可以直接调用 `std::sort()` 进行升序排列;如果想要降序或者其他特定顺序,则需传入额外的谓词表达式给该函数:
```cpp
#include<algorithm>
#include<vector>
bool compare(int a, int b){
return a>b; // 实现降序排序
}
std::vector<int> vec={7,2,5,3};
std::sort(vec.begin(),vec.end(),compare);
// 使用lambda简化写法
std::sort(vec.begin(), vec.end(), [](int a,int b)->bool{return a<b;} );
```
此部分说明了如何利用外部布尔返回值型的二元运算符来进行定制化排序[^4]。
阅读全文
相关推荐



















