STL堆之二
#include <iostream>
#include <algorithm>
#include <vector>
#include<functional>
using namespace std;
int main () {
int myints[] = {10,20,30,5,15};
vector<int> v(myints,myints+sizeof(myints)/sizeof(myints[0]));
vector<int>::iterator ite;
//heap各种操作的效果是对参数指向的vector容器里储存的数组myints[]进行变换
//pop_heap,push_heap,sort_heap前提条件是序列已经成堆,否则将出现异常:invalid heap
make_heap (v.begin(),v.end()); //大顶堆,也可写成make_heap (v.begin(),v.end(),less<int>());
//第三个参数缺省,默认是less<int>(),大顶堆,根结点最大
//make_heap(v.begin(), v.end(), greater<int>()); //小顶堆,根结点最小
//如果严格弱排序函数对象cmp(即第三个参数)被指定, 则在比较元素时应用此函数替代<操作符.
cout << "initial max heap : ";
for(ite=v.begin();ite!=v.end();++ite)
cout<<*ite<<" ";cout<<endl;
pop_heap (v.begin(),v.end());v.pop_back();
//pop_heap指的是移除堆顶元素,这样将剩下的结点调整成新的大顶堆,把原来的堆顶结点放在新构成的堆的最后一个结点,总的结点数不变
//pop_back删除序列的最后一个结点
//所以出堆的做法是先调用pop_heap,然后从容器弹出最后的元素。
cout << "max heap after pop : " ;
for(ite=v.begin();ite!=v.end();++ite)
cout<<*ite<<" ";cout<<endl;
v.push_back(99); push_heap (v.begin(),v.end());
//push_back新增一个结点到序列的最后
//函数push_heap()假设原来的元素已经是堆结构了,新加入最后的元素后使得所有元素也成为堆。
//所以进堆是先把要放进堆的元素放到容器的尾端。然后再调用push_heap,把整体的堆区间作为参数传进去,调整好成新堆。
cout << "max heap after push : " ;
for(ite=v.begin();ite!=v.end();++ite)
cout<<*ite<<" ";cout<<endl;
sort_heap (v.begin(),v.end());
cout << "final sorted range : ";
for (int i=0; i<v.size(); i++)
cout << " " << v[i];cout << endl;
return 0;
}