【STL】堆

本文总结了STL中的堆算法,强调堆不是容器而是以算法方式存在。堆分为max heap和min heap,STL默认为max heap,并通过实例介绍了如何使用堆进行排序。此外,还提及了STL中的优先级队列priority_queue,其底层基于堆算法,但不支持遍历和迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【STL】常用容器总结,带有复习性质的学习更有效率;


Heap】 在STL中不是以容器的方式呈现的,而是以算法的方式;

所谓堆,其实就是将数组假想成完全二叉树,满足某种规则的呈现。
某种规则就是堆顶(数组第一个元素)始终为最大或者最小的元素,还可以结合数组连续性的特性进行堆排序;

堆分为 max heap 和 min heap, STL默认的是 max heap , 所以下面实现的时候也会实现为最大堆;

在自己再次去实现它的时候,我们先来使用一下它;

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

int main()
{
    int arr[] = {
  
  2,31,5,7,45,87};
    vector<int> v(arr, arr+6);
    make_heap(v.begin(), v.end());          //构造堆,看看第一个位置是否发生变化;
    cout<<v[0]<<endl;

    v.push_back(99);
    push_heap(v.begin(), v.end());
    cout<<v[0]<<endl;                //新加入一个99


    sort_heap(v.begin(), v.end());   //堆排序
    for(int i = 
03-10
### C++ STL Heap Usage and Implementation In the context of the C++ Standard Template Library (STL), heaps are data structures that satisfy the heap property. A max-heap ensures every parent node is greater than or equal to its children, while a min-heap has each parent node less than or equal to its children[^1]. The primary operations supported by heaps include insertion, deletion, and finding the maximum element. To work with heaps in C++, one can use several functions provided within `<algorithm>` header: #### Creating Heaps Functions such as `std::make_heap` transform an existing range into a valid heap structure without sorting all elements fully. ```cpp #include <vector> #include <algorithm> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9}; // Transform vector 'v' into a max-heap std::make_heap(v.begin(), v.end()); } ``` #### Inserting Elements When adding new items to a heap, after inserting at the end of underlying container, call `push_heap`. ```cpp // Add another number to our heap from previous example v.push_back(2); std::push_heap(v.begin(), v.end()); ``` #### Removing Top Element Removing the largest item requires swapping this value with last position followed by calling `pop_heap`, which restores heap properties but leaves removed item unsorted outside original bounds. ```cpp if (!v.empty()) { std::pop_heap(v.begin(), v.end()); v.pop_back(); // Remove topmost element now located at back } ``` Heaps provide efficient access times when repeatedly needing smallest/largest values among dynamic sets; however, they do not support fast lookups for arbitrary members like balanced binary search trees would offer instead.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值