STL中heap相關函式用法

2021-08-18 16:50:46 字數 2367 閱讀 8580

這個函式用來將一段現有的資料轉化為乙個heap

template1: make_heap(randomaccessiterator first, randomaccessiterator last)

2: make_heap(randomaccessiterator first, randomaccessiterator last, cmpobject)

將[first, last)範圍進行堆排序,預設使用使用最大堆排序,其中改為最小堆時,使用greater,注意greater在#include 標頭檔案中。

template1: sort_heap(randomaccessiterator first, randomaccessiterator last) 

2: sort_heap(randomaccessiterator first, randomaccessiterator last, cmpobject)

將乙個堆排序,運用這個函式時,首先必須是乙個堆,如果不是乙個堆的資料用這個函式,會出現錯誤,因此在用這個函式之前可以先做一次make_heap。

特別注意: 

如果乙個資料是最大堆排序的,sort_heap 也要用最大堆排序; 

如果乙個資料是最小堆排序的,sort_heap 也要用最小堆排序,否則會報錯

即:make_heap(first, last, less()) 要於 sort_heap(first, last, less()) 對應 

make_heap(first, last, greater()) 要於 sort_heap(first, last, greater()) 對應

對剛插入的(尾部)元素做堆排序。

template1: push_heap(randomaccessiterator first, randomaccessiterator last)  

2: push_heap(randomaccessiterator first, randomaccessiterator last, cmpobject)

將front(即第乙個最大元素)移動到end的前部,同時將剩下的元素重新構造成(堆排序)乙個新的heap。

template1: pop_heap(randomaccessiterator first, randomaccessiterator last)   

2: pop_heap(randomaccessiterator first, randomaccessiterator last, cmpobject)

#include #include #include #include using namespace std;

int main()

; vectorivec(ia, ia + 9);

make_heap(ivec.begin(), ivec.end(), greater());

for (int i = 0; i < ivec.size(); ++i)

cout << ivec[i] << " "; //輸出結果為:0 1 2 3 4 8 9 3 5

cout << endl;

make_heap(ivec.begin(), ivec.end());

for (int i = 0; i < ivec.size(); ++i)

cout << ivec[i] << " ";//輸出結果為:9 5 8 3 4 0 2 3 1

cout << endl;

ivec.push_back(7);

push_heap(ivec.begin(), ivec.end());

for (int i = 0; i < ivec.size(); ++i)

cout << ivec[i] << " ";//輸出結果為:9 7 8 3 5 0 2 3 1 4

cout << endl;

pop_heap(ivec.begin(), ivec.end());//只是將第一元素和最後乙個元素換了乙個位置,並沒有刪除

for (int i = 0; i < ivec.size(); ++i)

cout << ivec[i] << " ";//輸出結果為:8 7 4 3 5 0 2 3 1 9

cout << endl;

ivec.pop_back();

sort_heap(ivec.begin(), ivec.end());

for (int i = 0; i < ivec.size(); ++i)

cout << ivec[i] << " ";//輸出結果為:0 1 2 3 4 5 7 8

cout << endl;

}

STL中heap相關函式

heap並不是屬於stl中的containers,而是在下提供了相關的函式make heap,sort heap,pop heap,push heap 函式的說明 make heap first,last,comp 預設是建立最大堆的。對int型別,可以在第三個引數傳入greater 得到最小堆,傳...

STL中關於heap的函式

在stl中,如果要用到堆,則有五個函式,make heap,pop heap,push heap,heap sort,和is heap,其中is heap和heap sort就是判斷容器是否符合堆的條件和把容器中元素進行堆排序。mak heap是把容器中制定迭代器之間的元素進行建堆操作。push h...

STL中堆 heap 函式的使用

所需標頭檔案 algorithm 語言環境 c 一般只用到四個make heap sort heap pop heap push heap。首先這四個函式的引數都一樣 first 首元素的位址 last 尾元素的位址 cmp比較函式 返回值都為void 這四個函式都是建立在陣列的基礎上的 cmp引數...