STL学习(六)heap学习

来源:互联网 发布:淘宝服务市场推广 编辑:程序博客网 时间:2024/06/05 04:51

建立堆make_heap(),在堆中添加数据push_heap(),在堆中删除数据pop_heap()和堆排序sort_heap():

头文件 #include <algorithm>

void make_heap(first_pointer,end_pointer,compare_function)

void pop_heap(first_pointer,end_pointer,compare_function)

void push_heap(first_pointer,end_pointer,compare_function)

void sort_heap(first_pointer,end_pointer,compare_function)


函数说明:


make_heap
把一段的数组或向量做成一个堆的结构。范围是(first,last)pop_heappop_heap()不是真的把最大(最小)的元素从堆中弹出来。
而是重新排序堆。它把first和last交换,然后将[first,last-1)
的数据再做成一个堆。
push_heappush_heap()假设由[first,last-1)是一个有效的堆,然后,再
把堆中的新元素加进来,做成一个堆。
sort_heapsort_heap对[first,last)中的序列进行排序。它假设这个序列
是有效堆。(当然,经过排序之后就不是一个有效堆了)


#include <iostream>#include <vector>#include <algorithm>using namespace std;void printVector(vector<int> vec){  vector<int>::iterator it = vec.begin();  for(;it!=vec.end();it++)    cout<<*it<<" ";  cout<<endl;  cout<<endl;}int main(){  int num[10] = {101,22,13,96,54,23,204,11,5,14};  vector<int> v1(num,num+10);  printVector(v1);  make_heap(v1.begin(),v1.end());  printVector(v1);  /*first: push_back() second:push_heap()*/  v1.push_back(1000);  push_heap(v1.begin(),v1.end());  printVector(v1);  /*first: pop_heap second: pop_back*/  pop_heap(v1.begin(),v1.end());  v1.pop_back();  printVector(v1);  sort_heap(v1.begin(),v1.end());  printVector(v1);  return 0;}


0 0
原创粉丝点击