概述
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::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;
}
输出结果:
initial max heap : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 15 20 99