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 <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,5,15};
  std::vector<int> 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<v.size(); i++)
    std::cout << ' ' << v[i];

  std::cout << '\n';

  return 0;
}

3. 练习

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,268评论 25 709
  • 在我们开发日常工作中,经常需要对一些对象进行保存,当然这是一些很轻量级的,我们首先会想到使用NSUserDef...
    jiangamh阅读 3,590评论 0 8

友情链接更多精彩内容