c plus plus 14怎样设置priority_queue队列的Compare函数
时间: 2023-11-04 18:04:43 浏览: 35
C++14 中的 priority_queue 类默认使用 std::less 作为 Compare 函数,即将元素按升序排列。如果你想要自定义 Compare 函数,可以通过以下两种方式来实现:
1. 重载运算符 "<"
你可以在你的元素类中重载小于运算符 "<",并将该元素类作为 priority_queue 的模板参数。例如,如果你想要按降序排列 int 型元素,可以这样写:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct cmp {
bool operator() (const int& a, const int& b) {
return a > b;
}
};
int main() {
priority_queue<int, vector<int>, cmp> pq;
pq.push(3);
pq.push(1);
pq.push(4);
pq.push(1);
pq.push(5);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
输出结果为:5 4 3 1 1
2. 自定义 Compare 函数
你可以自定义一个 Compare 函数,并将其作为 priority_queue 的第三个模板参数传入。例如,如果你想要按降序排列 int 型元素,可以这样写:
```c++
#include <iostream>
#include <queue>
using namespace std;
bool cmp(const int& a, const int& b) {
return a > b;
}
int main() {
priority_queue<int, vector<int>, decltype(cmp)*> pq(cmp);
pq.push(3);
pq.push(1);
pq.push(4);
pq.push(1);
pq.push(5);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
输出结果为:5 4 3 1 1
注意,第二种方式要使用 decltype 来获取 Compare 函数的类型,并将其指针作为第三个模板参数传入 priority_queue。