/* STL 最大堆、最小堆的應用 */ #include <iostream> #include <vector> #include <algorithm> // using namespace std; /* STL 堆操做 (1)make_heap()構造堆 void make_heap(first_pointer,end_pointer,compare_function); 默認比較函數是(<),即最大堆。 函數的做用是將[begin,end)內的元素處理成堆的結構 (2)push_heap()添加元素到堆 void push_heap(first_pointer,end_pointer,compare_function); 新添加一個元素在末尾,而後從新調整堆序。該算法必須是在一個已經知足堆序的條件下。 先在vector的末尾添加元素,再調用push_heap (3)pop_heap()從堆中移出元素 void pop_heap(first_pointer,end_pointer,compare_function); 把堆頂元素取出來,放到了數組或者是vector的末尾。 要取走,則可使用底部容器(vector)提供的pop_back()函數。 先調用pop_heap再從vector中pop_back元素 (4)sort_heap()對整個堆排序 排序以後的元素就再也不是一個合法的堆了。 */ //最大堆 struct MaxHeapCmp { inline bool operator()(const int &x,const int &y) { return x < y; } }; //最小堆 struct MinHeapCmp { inline bool operator()(const int &x, const int &y) { return x > y; } }; void test() { std::vector<int> data{ 3,1,7,4,99,75,34,10 }; //堆排序 std::make_heap(data.begin(), data.end(), MinHeapCmp()); for (int n : data) { cout << n << endl; } printf("------------------\n"); //添加元素 data.push_back(111); //再次堆排序 std::push_heap(data.begin(), data.end(), MaxHeapCmp()); for (int n : data) { cout << n << endl; } } int main() { test(); printf("-ok-\n"); getchar(); return 0; }