首页 关于我们 成功案例 网络营销 电商设计 新闻中心 联系方式
QQ联系
电话联系
手机联系

C++怎么实现一个堆(Heap)_C++数据结构与优先队列(priority_queue)

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

c++怎么实现一个堆(heap)_c++数据结构与优先队列(priority_queue)

在C++中,堆(Heap)是一种基于完全二叉树的数据结构,常用于实现优先队列。堆分为最大堆(大根堆)和最小堆(小根堆),其中最大堆的父节点值不小于子节点,最小堆则相反。C++标准库提供了 priority_queue 来方便使用堆,但理解手动实现堆有助于掌握其底层原理。

1. 使用 STL 的 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():判断是否为空和获取大小

示例代码:

#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;

}

2. 手动实现最大堆

手动实现堆可以加深对上浮(shift up)和下沉(shift down)操作的理解。通常使用数组存储完全二叉树。

关键操作:

  • 插入(push):将元素添加到末尾,然后执行上浮操作维护堆性质
  • 删除堆顶(pop):将最后一个元素移到堆顶,然后执行下沉操作
  • 上浮(shiftUp):比较当前节点与父节点,若大于父节点则交换
  • 下沉(shiftDown):比较父节点与两个子节点,与较大者交换直到满足堆性质

简单实现示例:

Openflow Openflow

一键极速绘图,赋能行业工作流

Openflow 88 查看详情 Openflow
#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 理解内部机制。

3. 堆的应用场景

堆常用于以下场景:

  • 优先队列:任务调度、事件处理等需要按优先级出队的场合
  • 求 Top K 元素:例如找出最大或最小的 K 个数,使用大小为 K 的堆效率高
  • 堆排序:时间复杂度 O(n log n),原地排序
  • Dijkstra 算法:结合最小堆可高效提取最短路径节点

例如,找数组中最大的 K 个数,可以用最小堆维护 K 个元素,遍历过程中只保留较大的值。

4. 注意事项

使用堆时需要注意:

  • STL 的 priority_queue 不支持遍历和删除非堆顶元素
  • 手动实现时注意数组越界,特别是左右子节点索引计算
  • 自定义类型需重载比较函数或提供仿函数
  • 堆的插入和删除时间复杂度为 O(log n),建堆过程可优化至 O(n)

基本上就这些。掌握 priority_queue 的使用和堆的手动实现,能更好应对算法题和实际开发中的优先级管理需求。堆的核心在于维护堆序性,理解 shiftUp 和 shiftDown 是关键。

以上就是C++怎么实现一个堆(Heap)_C++数据结构与优先队列(priority_queue)的详细内容,更多请关注其它相关文章!


# ai  # c++  # ios  # stream  # 标准库  # 数据结构  # 大堆  # 遍历  # 游戏开发  # 自定义  # 不支持  # 二叉树  # 的是  # 边缘  # 是一种  # 湖南SEO分享岚鸿  # 辽宁推广全域营销价位  # 凤城网站优化快照  # seo内容添加图片  # 营口抖音seo运营  # 龙华营销型网站建设价格  # 黄州seo优化怎么做  # 网站编辑和seo区别  # 俄语SEO什么意思  # 榆林市 网站建设