c++优先队列排序键值对
时间: 2024-01-12 15:21:34 浏览: 39
在C++中,可以使用优先队列(priority_queue)来对键值对进行排序。下面是一个示例代码:
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
struct Node {
int key;
int value;
};
struct Compare {
bool operator()(const Node& n1, const Node& n2) {
return n1.key > n2.key; // 按照键值升序排序
}
};
int main() {
std::map<int, int> mp = {{1, 10}, {3, 30}, {2, 20}};
std::priority_queue<Node, std::vector<Node>, Compare> pq;
for (auto e : mp) {
pq.push({e.first, e.second});
}
while (!pq.empty()) {
Node node = pq.top();
pq.pop();
std::cout << "Key: " << node.key << ", Value: " << node.value << std::endl;
}
return 0;
}
```
这段代码首先定义了一个结构体Node,用来表示键值对。然后定义了一个比较器Compare,用来指定优先队列的排序方式。在主函数中,创建了一个map对象mp,并将其中的键值对依次放入优先队列pq中。最后,通过循环从优先队列中取出元素并打印出来,即可按照键值升序排序输出。