std::ranges::sort_heap
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > |
(1) | (C++20 起) |
template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > |
(2) | (C++20 起) |
根據 comp 和 proj 對指定範圍內的元素進行堆排序,其中該範圍最初是根據 comp 和 proj 構建的堆。排序後的範圍不再保持堆屬性。
1) 指定範圍為
[
first,
last)
。2) 指定範圍為 r。
如果指定範圍不是一個符合 comp 和 proj 規則的堆,則行為未定義。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要修改的元素範圍的迭代器-哨兵對 |
r | - | 要修改的元素範圍 |
comp | - | 應用於投影元素的比較器 |
proj | - | 應用於元素的投影 |
[編輯] 返回值
1) last
2) ranges::end(r)
[編輯] 複雜度
最多 2N⋅log(N) 次 comp 應用和 4N⋅log(N) 次 proj 應用,其中 N 是
1) ranges::distance(first, last)
2) ranges::distance(r)
[編輯] 可能的實現
struct sort_heap_fn { template<std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<I, Comp, Proj> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { auto ret{ranges::next(first, last)}; for (; first != last; --last) ranges::pop_heap(first, last, comp, proj); return ret; } template<ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr sort_heap_fn sort_heap{}; |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <array> #include <iostream> void print(auto const& rem, const auto& v) { std::cout << rem; for (const auto i : v) std::cout << i << ' '; std::cout << '\n'; } int main() { std::array v{3, 1, 4, 1, 5, 9}; print("original array: ", v); std::ranges::make_heap(v); print("after make_heap: ", v); std::ranges::sort_heap(v); print("after sort_heap: ", v); }
輸出
original array: 3 1 4 1 5 9 after make_heap: 9 5 4 1 1 3 after sort_heap: 1 1 3 4 5 9
[編輯] 參見
(C++20) |
檢查給定的範圍是否是一個最大堆 (演算法函式物件) |
(C++20) |
尋找是一個最大堆的最大子範圍 (演算法函式物件) |
(C++20) |
從一個元素範圍建立一個最大堆 (演算法函式物件) |
(C++20) |
從一個最大堆中移除最大的元素 (演算法函式物件) |
(C++20) |
向一個最大堆新增一個元素 (演算法函式物件) |
將一個最大堆轉換成一個按升序排序的元素範圍 (函式模板) |