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]); //讀取堆頂元素