priority_queue以struct为存贮的使用方式
时间: 2024-01-15 18:18:31 浏览: 34
priority_queue以struct为存储的使用方式如下所示:
```cpp
#include <iostream>
#include <queue>
using namespace std;
struct Student {
string name;
int score;
};
struct Compare {
bool operator()(const Student& s1, const Student& s2) {
return s1.score < s2.score; // 按照分数从小到大排序
}
};
int main() {
priority_queue<Student, vector<Student>, Compare> pq;
Student s1 = {"Alice", 85};
Student s2 = {"Bob", 92};
Student s3 = {"Charlie", 78};
pq.push(s1);
pq.push(s2);
pq.push(s3);
while (!pq.empty()) {
Student top = pq.top();
pq.pop();
cout << "Name: " << top.name << ", Score: " << top.score << endl;
}
return 0;
}
```
在上述代码中,我们定义了一个`Student`结构体,包含学生的姓名和分数。然后,我们定义了一个`Compare`结构体,重载了`()`运算符,用于比较两个学生的分数大小。接下来,在主函数中,我们创建了一个`priority_queue`,指定存储的元素类型为`Student`,底层容器为`vector`,比较函数为`Compare`。然后,我们创建了三个学生对象,并将它们依次插入到优先级队列中。最后,我们通过循环取出队列中的元素,并输出学生的姓名和分数。