1.建堆
对于堆的操作是一些算法,而不是单独的数据结构,堆是对vector进行的操作。
建堆使用 make_heap()函数
建堆之前引入库
#include<stdio.h>
#include<algorithm> 堆算法
#include<functional> 堆算法中要用的到greater函数
using namespace std;
建堆
double a1[6]= {2.5,10.0,3.5,6.5,8.0,12.0};
vector<double> test(a1,a1+6);
make_heap(test.begin(),test.end(),greater<int>()); //greater函数是在 functional 库中的,默认使用的为less函数建立大顶堆,greater函数建立小顶堆
for(int i=0;i<test.size();i++){
printf("%f\n",test[i]);
}
//输出结果为建堆时对每一层的 遍历
2.向堆中添加元素
test.push_back(0.5);
push_heap(test.begin(),test.end(),greater<double>());
先向vector中添加元素,然后在指定范围用push_heap()向堆中添加内容
注意!!在建堆和push_heap()是使用的比较函数要一样,是greater就都是greater
3.从堆中删除堆顶
pop_heap(test.begin(),test.end(),greater<double>());
printf("%f\n",test[test.size()-1]); //读取堆顶元素