C++中堆是基于完全二叉树的结构,用于实现优先队列。1. STL的priority_queue默认为最大堆,提供push、top、pop等操作;2. 手动实现需掌握shiftUp和shiftDown以维护堆序性;3. 堆适用于优先队列、Top K问题、堆排序和Dijkstra算法;4. 注意priority_queue不支持遍历,手动实现时防止数组越界,自定义类型需重载比较规则。

在C++中,堆(Heap)是一种基于完全二叉树的数据结构,常用于实现优先队列。堆分为最大堆(大根堆)和最小堆(小根堆),其中最大堆的父节点值不小于子节点,最小堆则相反。C++标准库提供了 priority_queue 来方便使用堆,但理解手动实现堆有助于掌握其底层原理。
C++ 标准库中的 priority_queue 默认实现的是最大堆,基于 vector 和堆算法自动维护堆序性。
基本用法:
priority_queue<int> max_heap;</int>:创建最大堆priority_queue<int vector>, greater<int>> min_heap;</int></int>:创建最小堆push(x):插入元素top():获取堆顶元素pop():删除堆顶元素empty() 和 size():判断是否为空和获取大小示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <queue>
using namespace std;
<p>int main() {
priority_queue<int> max_heap;
max_heap.push(10);
max_heap.push(30);
max_heap.push(20);</p><pre class="brush:php;toolbar:false;">while (!max_heap.empty()) {
cout << max_heap.top() << " ";
max_heap.pop();
}
// 输出:30 20 10
return 0;}
手动实现堆可以加深对上浮(shift up)和下沉(shift down)操作的理解。通常使用数组存储完全二叉树。
关键操作:
简单实现示例:
#include <iostream>
#include <vector>
using namespace std;
<p>class MaxHeap {
private:
vector<int> heap;</p><pre class="brush:php;toolbar:false;">void shiftUp(int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (heap[index] <= heap[parent]) break;
swap(heap[index], heap[parent]);
index = parent;
}
}
void shiftDown(int index) {
int n = heap.size();
while (index < n) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int maxIndex = index;
if (left < n && heap[left] > heap[maxIndex])
maxIndex = left;
if (right < n && heap[right] > heap[maxIndex])
maxIndex = right;
if (maxIndex == index) break;
swap(heap[index], heap[maxIndex]);
index = maxIndex;
}
}public: void push(int val) { heap.push_back(val); shiftUp(heap.size() - 1); }
void pop() {
if (heap.empty()) return;
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty())
shiftDown(0);
}
int top() {
return heap.empty() ? -1 : heap[0];
}
bool empty() {
return heap.empty();
}
int size() {
return heap.size();
}};
这个类实现了基本的最大堆功能,可用于替代 priority_queue 理解内部机制。
堆常用于以下场景:
例如,找数组中最大的 K 个数,可以用最小堆维护 K 个元素,遍历过程中只保留较大的值。
使用堆时需要注意:
基本上就这些。掌握 priority_queue 的使用和堆的手动实现,能更好应对算法题和实际开发中的优先级管理需求。堆的核心在于维护堆序性,理解 shiftUp 和 shiftDown 是关键。
以上就是C++怎么实现一个堆(Heap)_C++数据结构与优先队列(priority_queue)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号