堆有大堆和小堆,一般是在二叉树的结构中使用,当然也可以把一个数组来构建堆,因为可以把一维数组看成是二叉树,如:a[6]={1,2,3,4,5,6}可以看成如下图:
在实际运用中,heap一般用于在大范围内的数中找出最大的几个数或者最小的几个数,速度比其它算法快
在stl中,可以用make_heap, push_heap,pop_heap来使用堆,代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct int_print: public unary_function<int, void>
{
void operator() (const int& t) const
{
cout << t << '\t';
}
};
int main()
{
int myints[] = {10,20,30,5,15};
vector<int> v(myints,myints+5);
make_heap (v.begin(),v.end());
cout << "initial max heap :" << endl;
for_each(v.begin(), v.end(), int_print());
cout << endl;
pop_heap (v.begin(),v.end()); v.pop_back();
cout << "max heap after pop : " << endl;
for_each(v.begin(), v.end(), int_print());
cout << endl;
v.push_back(99); push_heap (v.begin(),v.end());
cout << "max heap after push: " << endl;
for_each(v.begin(), v.end(), int_print());
cout << endl;
sort_heap (v.begin(),v.end());
cout << "final sorted range :" << endl;
for_each(v.begin(), v.end(), int_print());
cout << endl;
return 0;
}
输出如下:
我们可以画出堆的变化过程,调用make_heap建好堆后如下图:
之后pop的过程如下图:
即after pop: 20 15 10 5
push 99的过程如下图:
即after push: 99 20 10 5 15
sort就不用说了,大堆的话就是从小到大排序,小堆就是从大到小排序
对于 int类型,系统自己已经实现了比较函数,对于自己定义的结构的话,需要自己实现,如下代码:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct time_stru
{
int second;
};
struct time_print: public unary_function<time_stru, void>
{
void operator() (const time_stru& t) const
{
cout << t.second << '\t';
}
};
struct time_compare: public binary_function<time_stru,time_stru, bool>
{
bool operator() (const time_stru& t1, const time_stru& t2) const
{
return t1.second < t2.second;
}
};
int main()
{
time_stru mytimes[] = {{100},{200},{50},{111},{25}};
vector<time_stru> v(mytimes,mytimes+5);
make_heap (v.begin(),v.end(), time_compare());
cout << "initial max heap :" << endl;
for_each(v.begin(), v.end(), time_print());
cout << endl;
pop_heap (v.begin(),v.end(),time_compare());
v.pop_back();
cout << "max heap after pop : " << endl;
for_each(v.begin(), v.end(), time_print());
cout << endl;
time_stru a={99};
v.push_back(a);
push_heap (v.begin(),v.end(),time_compare());
cout << "max heap after push: " << endl;
for_each(v.begin(), v.end(), time_print());
cout << endl;
sort_heap (v.begin(),v.end(),time_compare());
cout << "final sorted range :" << endl;
for_each(v.begin(), v.end(), time_print());
cout << endl;
return 0;
}
输出结果如下: