std::sort_heap
提供: cppreference.com
ヘッダ <algorithm> で定義
|
||
(1) | ||
template< class RandomIt > void sort_heap( RandomIt first, RandomIt last ); |
(C++20未満) | |
template< class RandomIt > constexpr void sort_heap( RandomIt first, RandomIt last ); |
(C++20以上) | |
(2) | ||
template< class RandomIt, class Compare > void sort_heap( RandomIt first, RandomIt last, Compare comp ); |
(C++20未満) | |
template< class RandomIt, class Compare > constexpr void sort_heap( RandomIt first, RandomIt last, Compare comp ); |
(C++20以上) | |
最大ヒープ [first, last)
を昇順にソートされた範囲に変換します。 結果の範囲はもはやヒープの性質を持ちません。
関数の1つめのバージョンは要素を比較するために operator< を使用し、2つめのバージョンは指定された比較関数 comp
を使用します。
目次 |
[編集] 引数
first, last | - | ソートする要素の範囲 |
comp | - | 第1引数が第2引数より小さい場合に true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。 比較関数のシグネチャは以下と同等であるべきです。 bool cmp(const Type1 &a, const Type2 &b); シグネチャが const & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、値カテゴリに関わらず |
型の要件 | ||
-RandomIt は ValueSwappable および LegacyRandomAccessIterator の要件を満たさなければなりません。
| ||
-RandomIt を逆参照した型は MoveAssignable および MoveConstructible の要件を満たさなければなりません。
|
[編集] 戻り値
(なし)
[編集] 計算量
多くとも 2×N×log(N) 回の比較、ただし N=std::distance(first, last) です。
[編集] ノート
最大ヒープは以下の性質を持つ要素の範囲 [f,l)
です。
-
N = l - f
としたとき、すべての0 < i < N
についてf[floor(
が
)]i-1 2 f[i]
より小さくない。 - std::push_heap() を使用して新しい要素を追加できる。
- std::pop_heap() を使用して最初の要素を削除できる。
-
[編集] 欠陥報告
以下の動作変更欠陥報告は以前に発行された C++ 標準に遡って適用されました。
DR | 適用先 | 発行時の動作 | 正しい動作 |
---|---|---|---|
LWG 2444 | C++98 | complexity requirement was wrong by a factor of 2 | corrected |
[編集] 実装例
1つめのバージョン |
---|
template< class RandomIt > void sort_heap( RandomIt first, RandomIt last ) { while (first != last) std::pop_heap(first, last--); } |
2つめのバージョン |
template< class RandomIt, class Compare > void sort_heap( RandomIt first, RandomIt last, Compare comp ) { while (first != last) std::pop_heap(first, last--, comp); } |
[編集] 例
Run this code
#include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9}; std::make_heap(v.begin(), v.end()); std::cout << "heap:\t"; for (const auto &i : v) { std::cout << i << ' '; } std::sort_heap(v.begin(), v.end()); std::cout << "\nsorted:\t"; for (const auto &i : v) { std::cout << i << ' '; } std::cout << '\n'; }
出力:
heap: 9 4 5 1 1 3 sorted: 1 1 3 4 5 9
[編集] 関連項目
指定範囲の要素から最大ヒープを作成します (関数テンプレート) |