◐ Shell
clean mode source ↗

std::sort_heap - cppreference.com

提供: cppreference.com

<tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody>

ヘッダ <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 & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、値カテゴリに関わらず Type1 および Type2 型 (およびそれらの const 修飾された型) のすべての値を受理できなければなりません (そのため Type1 & は許されません。 また Type1 に対してムーブがコピーと同等でなければ Type1 も許されません (C++11以上))。
Type1 および Type2 は、どちらも RandomIt 型のオブジェクトの逆参照から暗黙に変換可能なものでなければなりません。 ​

型の要件
-RandomItValueSwappable および 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);
}

#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

関連項目