STL系列 heap 堆-解析

STL中与堆相关的4个函数——建立堆make_heap(),在堆中添加数据push_heap(),在堆中删除数据pop_heap()和堆排序sort_heap():

头文件 #include <algorithm>

下面的_First与_Last为可以随机访问的迭代器(指针),_Comp为比较函数(仿函数),其规则——如果函数的第一个参数小于第二个参数应返回true,否则返回false。

建立堆

make_heap(_First, _Last, _Comp)

默认是建立最大堆的。对int类型,可以在第三个参数传入greater<int>()得到最小堆。

 

在堆中添加数据

push_heap (_First, _Last)

要先在容器中加入数据,再调用push_heap ()

 

在堆中删除数据

pop_heap(_First, _Last)

要先调用pop_heap()再在容器中删除数据

 

堆排序

sort_heap(_First, _Last)

排序之后就不再是一个合法的heap了


下面给出STL中heap相关函数的使用范例:

[cpp]  view plain  copy
  1. #include <cstdio>  
  2. #include <vector>  
  3. #include <algorithm>  
  4. #include <functional>  
  5. using namespace std;  
  6. void PrintfVectorInt(vector<int> &vet)  
  7. {  
  8.     for (vector<int>::iterator pos = vet.begin(); pos != vet.end(); pos++)  
  9.         printf("%d ", *pos);  
  10.     putchar('\n');  
  11. }  
  12. int main()  
  13. {  
  14.     const int MAXN = 20;  
  15.     int a[MAXN];  
  16.     int i;  
  17.     for (i = 0; i < MAXN; ++i)  
  18.         a[i] = rand() % (MAXN * 2);  
  19.   
  20.     //动态申请vector 并对vector建堆  
  21.     vector<int> *pvet = new vector<int>(40);  
  22.     pvet->assign(a, a + MAXN);  
  23.   
  24.     //建堆  
  25.     make_heap(pvet->begin(), pvet->end());  
  26.     PrintfVectorInt(*pvet);  
  27.   
  28.     //加入新数据 先在容器中加入,再调用push_heap()  
  29.     pvet->push_back(25);  
  30.     push_heap(pvet->begin(), pvet->end());  
  31.     PrintfVectorInt(*pvet);  
  32.   
  33.     //删除数据  要先调用pop_heap(),再在容器中删除  
  34.     pop_heap(pvet->begin(), pvet->end());  
  35.     pvet->pop_back();  
  36.     pop_heap(pvet->begin(), pvet->end());  
  37.     pvet->pop_back();  
  38.     PrintfVectorInt(*pvet);  
  39.   
  40.     //堆排序  
  41.     sort_heap(pvet->begin(), pvet->end());  
  42.     PrintfVectorInt(*pvet);  
  43.   
  44.     delete pvet;  
  45.     return 0;  
  46. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值