在STL中,如果要用到堆,则有五个函数,make_heap,pop_heap,push_heap,heap_sort,和is_heap,其中is_heap和heap_sort就是判断容器是否符合堆的条件和把容器中元素进行堆排序。
mak_heap是把容器中制定迭代器之间的元素进行建堆操作。
push_heap,把容器最末尾的元素进行上调,即相当于是插入一个元素,因此如果要往堆中插入元素,例如vector构成的堆,应该先用push_back()函数将一个元素插入到vector容器的末尾,然后调用push_heap()函数进行上调。
pop_heap,把堆顶元素删除,此时的删除是把对顶的元素,和最末尾的元素进行交换,然后进行下虑操作。此后,vector中最后一个元素就是刚才从堆中pop出来的元素,此时只需要将这个元素在vector中进行pop_back()即可删除,维护这个堆。
总结:插入时,先用vector插入,然后调用push_heap()函数上虑,删除时,先用pop_heap()函数进行下虑,然后用vector的pop_back()函数进行删除即可,以下是这几个函数应用的代码,可以体会一下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
const int N=100;
int A[N];
generate(A,A+N,rand);
int k=20;
vector<int> result;
for(int i=0;i<k;i++)
result.push_back(A[i]);
make_heap(result.begin(),result.end());
for(int i=k;i<N;i++)
{
if(A[i]<result.front())
{
result.push_back(A[i]);
push_heap(result.begin(),result.end());
pop_heap(result.begin(),result.end());
result.pop_back();
}
}
system("pause");
return 0;
}