答案:可通过vector配合堆操作函数模拟优先队列。①用push_back插入元素后调用push_heap维持堆序;②弹出时先pop_heap将首元素移至末尾再pop_back;③自定义比较器可实现最小堆;④可封装类实现类似priority_queue接口;⑤该方式比标准容器更灵活,适用于需访问内部元素的场景。

在C++中,优先队列(priority queue)可以通过标准库中的 std::priority_queue 直接使用。但如果你想手动模拟一个优先队列的行为,可以借助 std::vector 或 std::deque 配合 堆操作函数 std::make_heap、std::push_heap、std::pop_heap 来实现。这种方式能更灵活地控制底层逻辑,比如访问内部元素或修改优先级。
你可以用 vector 存储元素,并通过堆操作保持堆结构:
示例代码:
#include <vector> #include <algorithm> #include <iostream> std::vector<int> heap; // 插入元素 heap.push_back(10); std::push_heap(heap.begin(), heap.end()); // 维护最大堆 heap.push_back(5); std::push_heap(heap.begin(), heap.end()); // 弹出最大元素 std::pop_heap(heap.begin(), heap.end()); // 把最大元素移到末尾 std::cout << heap.back() << "\n"; // 输出它 heap.pop_back(); // 真正删除
默认是最大堆,若要模拟最小堆,传入 std::greater:
立即学习“C++免费学习笔记(深入)”;
#include <functional> std::vector<int> min_heap; // 所有操作加上比较器 std::push_heap(min_heap.begin(), min_heap.end(), std::greater<int>()); std::pop_heap(min_heap.begin(), min_heap.end(), std::greater<int>());
可以封装成类似 std::priority_queue 的接口:
template<typename T = int, typename Compare = std::less<T>>
class MyPriorityQueue {
std::vector<T> data;
public:
void push(const T& val) {
data.push_back(val);
std::push_heap(data.begin(), data.end(), Compare{});
}
void pop() {
std::pop_heap(data.begin(), data.end(), Compare{});
data.pop_back();
}
const T& top() const { return data.front(); }
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};
使用方式和 std::priority_queue 基本一致:
MyPriorityQueue<int, std::greater<int>> pq;
pq.push(3); pq.push(1); pq.push(4);
while (!pq.empty()) {
std::cout << pq.top() << " "; // 输出: 1 3 4
pq.pop();
}
基本上就这些。手动模拟有助于理解堆的工作机制,也适用于需要干预队列内部状态的场景。标准 priority_queue 更简洁,而 vector + 堆操作更灵活。根据需求选择即可。
以上就是c++++中如何模拟优先队列_c++优先队列模拟方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号