Namespaces
Variants

std::sort

ja.cppreference.net より
 
 
アルゴリズムライブラリ
制約付きアルゴリズムとレンジに関するアルゴリズム (C++20)
制約付きアルゴリズム、例: ranges::copy, ranges::sort, ...
ソートと関連操作
分割操作
(C++11)    

ソート操作
二分探索操作
(分割された範囲に対して)
集合操作 (ソート済み範囲に対して)
マージ操作 (ソート済み範囲に対して)
ヒープ操作
最小/最大操作
(C++11)
(C++17)
辞書式比較操作
順列操作


 
ヘッダ <algorithm>
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
で定義 (1) (C++20 から constexpr)
template< class ExecutionPolicy, class RandomIt >
void sort( ExecutionPolicy&& policy,
           RandomIt first, RandomIt last );
(2) (C++17 から)
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
(3) (C++20 から constexpr)
template< class ExecutionPolicy, class RandomIt, class Compare >
void sort( ExecutionPolicy&& policy,
           RandomIt first, RandomIt last, Compare comp );
(4) (C++17 から)

範囲 [first, last) 内の要素を非降順にソートします。等しい要素の順序は保持されることは保証されません。

1) 要素は に関して ソートoperator<されます (C++20 まで)std::less{}(C++20 から)。
3) 要素は comp に関してソートされます。
2,4) (1,3) と同じですが、policy に従って実行されます。
これらのオーバーロードは、次の式の値が true である場合にのみオーバーロード解決に参加します:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20 まで)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20 から)

次の条件のいずれかが満たされる場合、動作は未定義です:

  • *first の型が Swappable ではない場合。
(C++11 まで)
(C++11 から)

パラメータ

first, last - ソートする要素の範囲を定義するイテレータのペア
policy - 使用する実行ポリシー
comp - 比較関数オブジェクト(つまり、 Compare の要件を満たすオブジェクト)。最初の引数が2番目の引数より 小さい (つまり、 前に 順序付けられる)場合に​ true を返す。

比較関数のシグネチャは以下と同等であるべき:

bool cmp ( const Type1 & a, const Type2 & b ) ;

シグネチャが const & を持つ必要はないが、関数は渡されたオブジェクトを変更してはならず、 値カテゴリ に関係なく型(おそらくconstの) Type1 と Type2 のすべての値を受け入れられなければならない(したがって、 Type1& は許可されない 、 Type1 も Type1 に対してムーブがコピーと等価でない限り許可されない (C++11以降) )。
型 Type1 と Type2 は、 RandomIt 型のオブジェクトが間接参照され、それら両方に暗黙的に変換可能でなければならない。 ​

型要件
-
RandomIt は LegacyRandomAccessIterator の要件を満たさなければならない。
-
Compare は Compare の要件を満たさなければならない。

計算量

N が last - first として与えられる:

1,2) O(N·log(N)) 回の比較を operator < (C++20まで) std:: less { } (C++20以降) を使用して行う。
3,4) O(N·log(N)) 回の比較子 comp の適用。

例外

ExecutionPolicyという名前のテンプレートパラメータを持つオーバーロードは、 以下のようにエラーを報告します:

  • アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、 ExecutionPolicy が 標準ポリシー のいずれかであるとき、 std::terminate が呼び出される。それ以外の ExecutionPolicy については、動作は実装定義である。
  • アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされる。

実装例

実装については libstdc++ および libc++ も参照してください。

注記

LWG713以前は、計算量要件により LWG713 の実装が Quicksort のみを使用することを許可しており、最悪の場合 O(N 2
)
回の比較が必要となる可能性がありました。

**翻訳のポイント:** - HTMLタグ、属性、コードブロックは完全に保持 - C++専門用語(LWG713, Quicksort, sort())は非翻訳 - 数学表記(O(N²))は原文のまま維持 - 技術文書としての正確性と専門性を確保 - 自然な日本語の技術文書表現を使用

Introsort はすべてのケースを O(N·log(N)) 回の比較で処理でき(平均ケースで追加のオーバーヘッドを発生させない)、したがって通常 sort() の実装に使用されます。

libc++は、修正された時間計算量の要件を LLVM 14まで 実装していません。

例

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <string_view>
int main()
{
    std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    auto print = [&s](std::string_view const rem)
    {
        for (auto a : s)
            std::cout << a << ' ';
        std::cout << ": " << rem << '\n';
    };
    std::sort(s.begin(), s.end());
    print("sorted with the default operator<");
    std::sort(s.begin(), s.end(), std::greater<int>());
    print("sorted with the standard library compare function object");
    struct
    {
        bool operator()(int a, int b) const { return a < b; }
    }
    customLess;
    std::sort(s.begin(), s.end(), customLess);
    print("sorted with a custom function object");
    std::sort(s.begin(), s.end(), [](int a, int b)
                                  {
                                      return a > b;
                                  });
    print("sorted with a lambda expression");
}

出力:

0 1 2 3 4 5 6 7 8 9 : sorted with the default operator<
9 8 7 6 5 4 3 2 1 0 : sorted with the standard library compare function object
0 1 2 3 4 5 6 7 8 9 : sorted with a custom function object
9 8 7 6 5 4 3 2 1 0 : sorted with a lambda expression

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 713 C++98 O(N·log(N)) 時間計算量は平均でのみ要求されていた 最悪ケースでも要求される

関連項目

範囲の最初のN個の要素をソートする
(関数テンプレート & アルゴリズム関数オブジェクト)
等価な要素間の相対的な順序を保持しながら範囲の要素をソートする
(関数テンプレート & アルゴリズム関数オブジェクト)
範囲の要素をソートする
(アルゴリズム関数オブジェクト)