c++优先队列第三个参数
时间: 2024-03-03 22:44:59 浏览: 15
C++的优先队列(priority_queue)是一种特殊的队列,它可以根据元素的优先级自动排序。在C++中,优先队列的第三个参数是一个比较函数,用于指定元素的优先级比较方式。
下面是一个示例,演示了如何使用C++优先队列的第三个参数来自定义元素的优先级比较方式:
```cpp
#include <iostream>
#include <queue>
using namespace std;
// 自定义结构体,表示一个学生
struct Student {
string name;
int score;
};
// 自定义比较函数,按照学生的分数从高到低排序
struct CompareStudent {
bool operator()(const Student& s1, const Student& s2) {
return s1.score < s2.score;
}
};
int main() {
// 创建一个优先队列,元素类型为Student,使用CompareStudent作为比较函数
priority_queue<Student, vector<Student>, CompareStudent> pq;
// 添加一些学生到优先队列中
pq.push({"Alice", 90});
pq.push({"Bob", 80});
pq.push({"Charlie", 95});
// 输出优先队列中的元素
while (!pq.empty()) {
cout << pq.top().name << " " << pq.top().score << endl;
pq.pop();
}
return 0;
}
```
运行上述代码,输出结果为:
```
Charlie 95
Alice 90
Bob 80
```
在上述示例中,我们定义了一个自定义结构体`Student`,包含学生的姓名和分数。然后,我们定义了一个自定义比较函数`CompareStudent`,按照学生的分数从高到低排序。最后,我们创建了一个优先队列`pq`,元素类型为`Student`,并使用`CompareStudent`作为比较函数。通过`pq.push()`方法将学生添加到优先队列中,然后通过`pq.top()`方法获取队列中的最高优先级元素,并通过`pq.pop()`方法将该元素从队列中移除。