C++进阶:STL算法19--堆算法

1. 简介

函数 作用 文档
make_heap(beg,end) 把[beg,end)内的元素生成一个堆。 make_heap()
make_heap(beg,end,comp) 将函数comp代替<操作符,执行make_heap() make_heap()
pop_heap(beg,end) 重新排序堆。它把first和last-1交换,然后重新生成一个堆。可使用容器的back来访问被"弹出"的元素或者使用pop_back进行真正的删除。并不真正把最大元素从堆中弹出。 pop_heap()
pop_heap(beg,end,comp) 将函数comp代替<操作符,执行pop_heap() pop_heap()
push_heap(beg,end) 假设first到last-1是一个有效堆,要被加入到堆的元素存放在位置last-1,重新生成堆。在指向该函数前,必须先把元素插入容器后。 push_heap()
push_heap(beg,end,comp) 将函数comp代替<操作符,执行push_heap() push_heap()
sort_heap(beg,end) 对[beg,end)内的序列重新排序。 sort_heap()
sort_heap(beg,end,comp) 将函数comp代替<操作符,执行sort_heap() sort_heap()

2. 示例代码

// range heap example
#include      // std::cout
#include     // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include        // std::vector

int main () {
  int myints[] = {10,20,30,5,15};
  std::vector v(myints,myints+5);

  std::make_heap (v.begin(),v.end());
  std::cout << "initial max heap   : " << v.front() << '\n';

  std::pop_heap (v.begin(),v.end()); v.pop_back();
  std::cout << "max heap after pop : " << v.front() << '\n';

  v.push_back(99); std::push_heap (v.begin(),v.end());
  std::cout << "max heap after push: " << v.front() << '\n';

  std::sort_heap (v.begin(),v.end());

  std::cout << "final sorted range :";
  for (unsigned i=0; i

3. 练习

你可能感兴趣的:(C++进阶:STL算法19--堆算法)