优先队列使用按从大到小排序
时间: 2023-07-28 08:40:45 浏览: 60
在默认情况下,C++ STL 中的 `priority_queue` 是按照从大到小的顺序排序的,也就是最大堆。如果需要按照从小到大的顺序排序,可以通过以下两种方法实现:
1. 重载运算符
可以通过重载运算符 `<`,使得 `priority_queue` 按照从小到大的顺序排序。例如,以下代码演示了如何使用一个结构体来实现从大到小的排序:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct cmp {
bool operator() (const int& a, const int& b) const {
return a > b;
}
};
int main() {
priority_queue<int, vector<int>, cmp> pq;
pq.push(10);
pq.push(30);
pq.push(20);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
输出结果为:
```
10 20 30
```
在这个例子中,我们使用一个结构体 `cmp` 重载了小于号运算符 `<`,使得元素按照从小到大的顺序排序。
2. 使用 greater
可以使用 STL 中的 `greater` 函数对象来实现从小到大的排序。例如,以下代码演示了如何使用 `greater` 函数对象来排序:
```c++
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(10);
pq.push(30);
pq.push(20);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
输出结果为:
```
10 20 30
```
在这个例子中,我们使用了 STL 中提供的 `greater` 函数对象,它会将元素按照从小到大的顺序排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)