STL heap底层及使用
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
/*
heap的隐式表达法 数组0下标位置 保留则用数组存储完全二叉树时
根节点位于i 则左孩子为2*i 右孩子为2*i+1 不过SGI STL并未使用这一技巧
我个人也不提倡使用这一技巧 因为这会在排序时带来不便
*/
/*
heap是与vector结合起来使用的 其容器为vector
heap 只提供算法 当然只要是 RandomAccessIterator 的容器都可以
*/
/*
成员函数:
//以下的less<T>() 为默认的函数对象(即形成 大根堆) 改为greater<T>() 为小根堆
//当然也可以自定义这个函数对象
make_heap(f,l,less<T>());
//push_heap 之前必须将 新增元素添加至 vector末尾
push_heap(f,l,less<T>());
pop_heap(f,l,less<T>());将根值临时保存 然后对对begin() -end()-1-1 进行堆调整
//使末尾值为最值 前边元素构成一个堆
sort_heap(f,l,less<T>());
*/
template<class T>
struct Compare
{
bool operator()(const T& val1, const T& val2)
{
return val1 > val2;
//小于为大根堆 大于为小根堆
}
};
int main(void)
{
int array[] = {4,45,21,89,-45,5,8,1};
int len = sizeof(array) / sizeof(array[0]);
vector<int> Vec(array,array+len);
make_heap(Vec.begin(),Vec.end(), Compare<int>());
//less<T>() 表明建立大根堆 greater<T>() 表明建立小根堆
//前提是 基本类型 自定义类型时 可重载运算符(有元、全局)或者函数对象
sort_heap(Vec.begin(),Vec.end(),Compare<int>());
//小根堆得排序 也需要加上 函数对象(这个非常容易忘记)
copy(Vec.begin(),Vec.end(),ostream_iterator<int>(cout," "));
puts("");
Vec.push_back(-8);
//push_heap(Vec.begin(),Vec.end(), Compare<int>());
//小根堆的 push_heap 有问题啊
copy(Vec.begin(), Vec.end(), ostream_iterator<int>(cout, " "));
puts("\n--------------------大根堆---------------------");
vector<int> Vec1(array, array + len);
make_heap(Vec1.begin(), Vec1.end());
//判断某个区间是否为 大根堆或者小根堆
bool bHeap = is_heap(Vec1.begin(), Vec1.end()/*,Compare<int>()*/);
if (bHeap)
{
cout << "this is a heap!" << endl;
}
puts("演示堆排序过程");
//pop_heap 将根值放在 vctor末尾 然后再对 从begin() 到end()-1 位置再次pop_heap
while (Vec1.begin() != Vec1.end())
{
pop_heap(Vec1.begin(), Vec1.end());
cout<<*--Vec1.end() <<" ";
//这么做的好处是不需要 保存上一个迭代器 因为上一个迭代器会失效
Vec1.pop_back();
}
sort_heap(Vec1.begin(), Vec1.end());
copy(Vec1.begin(), Vec1.end(), ostream_iterator<int>(cout, " "));
Vec1.push_back(100);
//push_heap(Vec1.begin(),Vec1.end());
return 0;
}