Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4733144
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: C/C++

2010-08-08 12:31:38

heap的常用操作可以使用stl的四种函数实现

1. 头文件如下

#include
#include
#include    
#include    
using namespace std;   

2. 建堆:
vector a(n);    
   for(i=0;i{
   int y;
   cin>>y;
   a[i]=y;
}
make_heap(a.begin(),a.end(), cmp);   
  

3. 取最小值(后两句一定要成对出现!!)   
x=a.front();  
pop_heap(a.begin(),a.end(), less() );    
a.pop_back(); // 删除最后一个数据    

4. 在堆中插入元素   
cin>>x;
a.push_back(x);   
push_heap(a.begin(),a.end(),cmp);

5. 堆排序    
sort_heap(a.begin(),a.end(),cmp);    

ps1:cmp函数与sort()中的cmp用法类似,参数为比较元素的类型,如cmp(int a,int b), cmp(node a, node b)。cmp是bool型,if (a < b ) return true; else return false。这里可以参看help中的说明:

_Comp

User-defined predicate function object that defines sense in which one element is less than another. A binary predicate takes two arguments and returns true when satisfied and false when not satisfied.

ps2: less()是系统封装的对int使用的cmp(),可以使用

再附上我自己的调试程序,可以看看

#include
#include
#include    
#include    
using namespace std;   


int main()
{

int n;
int i;
int j;
int x;
cin>>n;
vector a(n);   
    //建堆
for(i=0;i{
   int y;
   cin>>y;
   a[i]=y;
}
make_heap(a.begin(),a.end(), less());  
    //取最小值   
    x=a.front();
cout<cin.get();
    pop_heap(a.begin(),a.end(), less() );   
    a.pop_back(); // 删除最后一个数据   
    //插入元素   
cin>>x;
    a.push_back(x);   
//    push_heap(a.begin(),a.end(),cmp);
push_heap(a.begin(),a.end(),less());
    //堆排序   
//    sort_heap(a.begin(),a.end(),cmp);   
sort_heap(a.begin(),a.end(),less());
for(i=0;i   cout<return 0;
}

阅读(1785) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~