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, |
(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, |
(4) | (C++17以降) |
範囲 [first, last) の要素を非降順にソートします。等価な要素の順序は保持されることが保証されます。
|
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true である。 |
(C++20まで) |
|
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> は true です。 |
(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; // Does not participate in comparisons }; 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
[編集] 関連項目
| 範囲を昇順にソートする (関数テンプレート) | |
| 範囲の最初のN個の要素をソートする (関数テンプレート) | |
| 相対的な順序を維持しながら要素を2つのグループに分割する (関数テンプレート) | |
| (C++20) |
等しい要素間の順序を維持しながら要素の範囲をソートする (アルゴリズム関数オブジェクト) |