STL里面的堆操作一般用到的只有4个。
分别是make_heap();pop_heap();push_heap();sort_heap();
他们的头文件是algorithm
1、make_heap();
函数原型是:
void make_heap(first_pointer,end_pointer,compare_function);
一个参数是数组或向量的头指针,第二个向量是尾指针。第三个参数是比较函数的名字。在缺省的时候,默认是大顶堆。(下面的参数都一样)
作用:把这一段的数组或向量做成一个堆的结构。范围是[first,last)
2、pop_heap();
函数原型是:
void pop_heap(first_pointer,end_pointer,compare_function);
作用:pop_heap()不是真的把最大(最小)的元素从堆中弹出来。而是重新排序堆。它
把first和last交换,然后将[first,last-1)的数据再做成一个堆。
3、push_heap()
函数原型是:
void pushheap(first_pointer,end_pointer,compare_function);
作用:push_heap()假设由[first,last-1)是一个有效的堆,然后,再把堆中的新元素加进来,做成一个堆。
4、sort_heap()
函数原型:
void sort_heap(first_pointer,end_pointer,compare_function);
作用:sort_heap对[first,last)中的序列进行排序。它假设这个序列是有效堆。(当然,经过排序之后就不是一个有效堆了)
//STL heap 堆
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(){
int i;
vector <int> v;
for(int i=5;i>0;i--)
v.push_back(i+2);
make_heap(v.begin(),v.end(),cmp); //构建小顶堆
//结果是3、4、5、7、6
for(int i=0;i<5;i++)
cout<<v[i]<<" ";
cout<<endl;
v.push_back(2);
push_heap(v.begin(),v.end(),cmp); //加入2,重新建堆
//结果是2、4、3、7、6、5
for(int i=0;i<6;i++)
cout<<v[i]<<" ";
cout<<endl;
pop_heap(v.begin(),v.end(),cmp); //弹出元素
v.pop_back();
//结果是:3、4、5、7、6
for(int i=0;i<6;i++)
cout<<v[i]<<" ";
cout<<endl;
sort_heap(v.begin(),v.end(),cmp); //对堆中元素排序
//结果是:7,6,5,4,3
for(int i=0;i<5;i++)
cout<<v[i]<<" ";
cout<<endl;
return 0;
}
434

被折叠的 条评论
为什么被折叠?



