STL学习(六)heap学习

建立堆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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值