STL系列之四 heap 堆

原文地址:

http://blog.csdn.net/morewindows/article/details/6967409


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



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值