基本函数用法:
make_heap(_First, _Last, _Comp);//建立堆
push_heap (_First, _Last);//在堆中添加数据
pop_heap(_First, _Last);//在堆中删除数据
pop_heap(_First, _Last);//在堆中删除数据
sort_heap(_First, _Last) ;//堆排序
示例代码:
#include <time.h>
#include <string>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <functional>
#include<iostream>
#include<iomanip>
using namespace std;
void DispVec(string Str, vector<int>& Vec){
cout << Str << endl;
cout << "*************************************************************" << endl;
for(vector<int>::iterator it = Vec.begin(); it != Vec.end(); it++){
cout << setw(3) << (*it);
}
cout << endl << endl;
}
void main()
{
const int iSize = 20;
int Arr[iSize]; memset(Arr, 0, sizeof(int)*iSize);
srand(time(NULL));
for(int i = 0; i < iSize; i++){
Arr[i] = rand() % (iSize*2);
}
//动态申请vector 并对vector建堆
vector<int>* pVec = new vector<int>(40);
pVec->assign(Arr, Arr+iSize);
DispVec("建堆:", *pVec);//Insert And Get
//建堆
make_heap(pVec->begin(), pVec->end());
//加入新数据 先在容器中加入,再调用push_heap()
pVec->push_back(26);
push_heap(pVec->begin(), pVec->end());
DispVec("尾部追加数据26:", *pVec);
//删除数据 要先调用pop_heap(),再在容器中删除
pop_heap(pVec->begin(), pVec->end());
pVec->pop_back();
pop_heap(pVec->begin(), pVec->end());
pVec->pop_back();
DispVec("尾部删除两个数据:", *pVec);
//堆排序
sort_heap(pVec->begin(), pVec->end());
DispVec( "堆排序:", *pVec);
delete pVec; pVec = NULL;
}