priority_queue创建堆
- 默认情况下,
priority_queue
使用最大堆,也就是说,优先级最高的元素会最先出队。 - 如果你想使用最小堆,可以传入一个自定义的比较函数。
最大堆创建
#include <iostream>
#include <queue>
#include <vector>
int main() {
std::priority_queue<int> pq;
// 向队列中添加元素
pq.push(10);
pq.push(5);
pq.push(15);
// 输出并移除优先队列中的元素
while (!pq.empty()) {
std::cout << pq.top() << " "; // 打印队列顶部的元素(最大值)
pq.pop(); // 移除队列顶部的元素
}
// 输出:15 10 5
return 0;
}
最小堆创建
#include <iostream>
#include <queue>
#include <vector>
#include <functional> // 引入 std::greater
int main() {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
pq.push(10);
pq.push(5);
pq.push(15);
while (!pq.empty()) {
std::cout << pq.top() << " "; // 打印队列顶部的元素(最小值)
pq.pop(); // 移除队列顶部的元素
}
// 输出:5 10 15
return 0;
}