STL Heap使用方法

来源:互联网 发布:手机淘宝申诉进度查询 编辑:程序博客网 时间:2024/06/05 00:17

概述

STL中的heap并不是container,默认是最大堆,如果需要最小堆,则需要添加参数greater<type>()
常用堆操作:make_heap(), pop_heap(), push_heap(), sort_heap(), 头文件<algorithm>
1.make_heap(v.begin(), v.end())使序列变成堆
2.push_heap(v.begin(),v.end())假设[first, last-1)有序,新添加元素进堆,需要配合push_back()
3.pop_heap(v.begin(),v.end()) 并不是真正的弹出元素,而是将first、last调换位置,将[first, last-1)做成,需要配合pop_back()
4.sort_heap() 对container进行堆排序。

// range heap example#include <iostream>     // std::cout#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap#include <vector>       // std::vectorint 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;}

输出结果:

initial max heap   : 30max heap after pop : 20max heap after push: 99final sorted range : 5 10 15 20 99
0 0
原创粉丝点击