std::make_heap
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class RandomIt > void make_heap( RandomIt first, RandomIt last ); |
(1) | (C++20 起為 constexpr) |
template< class RandomIt, class Compare > void make_heap( RandomIt first, RandomIt last, Compare comp ); |
(2) | (C++20 起為 constexpr) |
在範圍 [
first,
last)
中構造一個堆。
2) 構造的堆使用 comp。
如果滿足以下任何條件,則行為是未定義的:
|
(C++11 前) |
|
(C++11 起) |
目錄 |
[編輯] 引數
first, last | - | 定義要構成二叉堆的元素範圍的迭代器對 |
comp | - | 比較函式物件(即滿足比較 (Compare)要求的物件),如果第一個引數“小於”第二個,則返回true。 比較函式的簽名應等效於以下內容 bool cmp(const Type1& a, const Type2& b); 雖然簽名不需要包含 const&,但函式不得修改傳遞給它的物件,並且必須能夠接受 |
型別要求 | ||
-RandomIt 必須滿足遺留隨機訪問迭代器 (LegacyRandomAccessIterator)的要求。 | ||
-Compare 必須滿足 Compare 的要求。 |
[編輯] 複雜度
給定 N 為 std::distance(first, last)
2) 最多 3N 次應用比較函式 comp。
[編輯] 示例
執行此程式碼
#include <algorithm> #include <functional> #include <iostream> #include <string_view> #include <vector> void print(std::string_view text, const std::vector<int>& v = {}) { std::cout << text << ": "; for (const auto& e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { print("Max heap"); std::vector<int> v{3, 2, 4, 1, 5, 9}; print("initially, v", v); std::make_heap(v.begin(), v.end()); print("after make_heap, v", v); std::pop_heap(v.begin(), v.end()); print("after pop_heap, v", v); auto top = v.back(); v.pop_back(); print("former top element", {top}); print("after removing the former top element, v", v); print("\nMin heap"); std::vector<int> v1{3, 2, 4, 1, 5, 9}; print("initially, v1", v1); std::make_heap(v1.begin(), v1.end(), std::greater<>{}); print("after make_heap, v1", v1); std::pop_heap(v1.begin(), v1.end(), std::greater<>{}); print("after pop_heap, v1", v1); auto top1 = v1.back(); v1.pop_back(); print("former top element", {top1}); print("after removing the former top element, v1", v1); }
輸出
Max heap: initially, v: 3 2 4 1 5 9 after make_heap, v: 9 5 4 1 2 3 after pop_heap, v: 5 3 4 1 2 9 former top element: 9 after removing the former top element, v: 5 3 4 1 2 Min heap: initially, v1: 3 2 4 1 5 9 after make_heap, v1: 1 2 4 3 5 9 after pop_heap, v1: 2 3 4 9 5 1 former top element: 1 after removing the former top element, v1: 2 3 4 9 5
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3032 | C++98 | [ first, last) 的元素不需要可交換 |
需要 |
[編輯] 參閱
(C++11) |
檢查給定的範圍是否是一個最大堆 (函式模板) |
(C++11) |
尋找是一個最大堆的最大子範圍 (函式模板) |
向一個最大堆新增一個元素 (函式模板) | |
從一個最大堆中移除最大的元素 (函式模板) | |
將一個最大堆轉換成一個按升序排序的元素範圍 (函式模板) | |
適配容器以提供優先順序佇列 (類模板) | |
(C++20) |
從一個元素範圍建立一個最大堆 (演算法函式物件) |