std::stable_sort
| ヘッダ <algorithm>
|
||
template< class RandomIt >
void stable_sort( RandomIt first, RandomIt last );
|
で定義 (1) | (C++26 から constexpr) |
template< class ExecutionPolicy, class RandomIt >
void stable_sort( ExecutionPolicy&& policy,
RandomIt first, RandomIt last );
|
(2) | (C++17 から) |
template< class RandomIt, class Compare >
void stable_sort( RandomIt first, RandomIt last, Compare comp );
|
(3) | (C++26 から constexpr) |
template< class ExecutionPolicy, class RandomIt, class Compare >
void stable_sort( ExecutionPolicy&& policy,
RandomIt first, RandomIt last, Compare comp );
|
(4) | (C++17 から) |
範囲 [first, last) 内の要素を非降順にソートします。同等の要素の順序は保持されることが保証されます。
comp に関してソートされます。policy に従って実行されます。true である場合にのみオーバーロード解決に参加します。
|
|
(C++20まで) |
|
|
(C++20から) |
次の条件のいずれかが満たされた場合、動作は未定義です。
|
(C++11まで) |
|
(C++11から) |
パラメータ
| first, last | - | ソートする要素の範囲を定義するイテレータのペア |
| policy | - | 使用する実行ポリシー |
| comp | - |
比較関数オブジェクト(つまり、
Compare
の要件を満たすオブジェクト)。最初の引数が2番目の引数より
小さい
(つまり、
前に順序付けられる
)場合に
true
を返す。
比較関数のシグネチャは以下と同等であるべき: bool cmp ( const Type1 & a, const Type2 & b ) ;
シグネチャが
const
&
を持つ必要はないが、関数は渡されたオブジェクトを変更してはならず、
値カテゴリ
に関係なく型(おそらくconstの)
|
| 型要件 | ||
-
RandomIt
は
LegacyRandomAccessIterator
の要件を満たさなければならない。
|
||
-
Compare
は
Compare
の要件を満たさなければならない。
|
||
計算量
与えられた N を last - first として:
(N)) 回の比較を使用して実行されます。
(N)) 回の適用。
例外
ExecutionPolicyという名前のテンプレートパラメータを持つオーバーロードは、
以下のようにエラーを報告します:
-
アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、
ExecutionPolicyが 標準ポリシー のいずれかであるとき、 std::terminate が呼び出される。それ以外のExecutionPolicyについては、動作は実装定義である。 - アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされる。
実装例
実装については libstdc++ および libc++ も参照してください。
注記
この関数は、ソート対象のシーケンスと同等のサイズの一時バッファの割り当てを試みます。割り当てに失敗した場合、効率の低いアルゴリズムが選択されます。
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_constexpr_algorithms
|
202306L
|
(C++26) | constexpr 安定ソート、オーバーロード ( 1 ) , ( 3 ) |
例
#include <algorithm> #include <array> #include <iostream> #include <string> #include <vector> struct Employee { int age; std::string name; // 比較には関与しない }; bool operator<(const Employee& lhs, const Employee& rhs) { return lhs.age < rhs.age; } #if __cpp_lib_constexpr_algorithms >= 202306L consteval auto get_sorted() { auto v = std::array{3, 1, 4, 1, 5, 9}; std::stable_sort(v.begin(), v.end()); return v; } static_assert(std::ranges::is_sorted(get_sorted())); #endif int main() { std::vector<Employee> v{{108, "Zaphod"}, {32, "Arthur"}, {108, "Ford"}}; std::stable_sort(v.begin(), v.end()); for (const Employee& e : v) std::cout << e.age << ", " << e.name << '\n'; }
出力:
32, Arthur 108, Zaphod 108, Ford
関連項目
| 範囲の要素をソートする (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20) |
|
| 範囲の最初のN個の要素をソートする (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20) |
|
| 要素を2つのグループに分割し、各グループ内の相対的な順序を保持する (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20) |
|
(C++20) |
等価な要素間の相対的な順序を保持しながら範囲の要素をソートする (アルゴリズム関数オブジェクト) |