std::forward_list<T,Allocator>::sort
From cppreference.com
< cpp | container | forward list
| void sort(); |
(1) | (C++11以降) |
| template< class Compare > void sort( Compare comp ); |
(2) | (C++11以降) |
要素をソートし、同値な要素の順序を維持します。参照やイテレータは無効になりません。
1) 要素は operator< を使って比較されます。
2) 要素は comp を使用して比較されます。
例外がスローされた場合、*this の要素の順序は未定義です。
目次 |
[編集] パラメータ
| comp | - | 比較関数オブジェクト(つまり、Compare の要件を満たすオブジェクト)。最初の引数が2番目の引数より小さい(つまり、前に順序付けられる)場合に true を返します。 比較関数のシグネチャは、以下と同等でなければならない。 bool cmp(const Type1& a, const Type2& b); シグネチャは const& を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、値カテゴリ に関係なく、(おそらく const の) |
| 型要件 | ||
-CompareはCompareの要件を満たす必要がある。 | ||
[編集] 戻り値
(なし)
[編集] 計算量
N を std::distance(begin(), end()) とすると、
1) N·log(N) 回の operator< を使用した比較。
2) N·log(N) 回の比較関数 comp の適用。
[編集] 注釈
std::sort はランダムアクセスイテレータを必要とするため、forward_list では使用できません。この関数は、forward_list の要素型が交換可能であることを要求しない点、すべてのイテレータの値を保持する点、および安定ソートを実行する点で std::sort と異なります。
[編集] 例
このコードを実行
#include <functional> #include <iostream> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (const int i : list) ostr << ' ' << i; return ostr; } int main() { std::forward_list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4}; std::cout << "initially: " << list << '\n'; list.sort(); std::cout << "ascending: " << list << '\n'; list.sort(std::greater<int>()); std::cout << "descending:" << list << '\n'; }
出力
initially: 8 7 5 9 0 1 3 2 6 4 ascending: 0 1 2 3 4 5 6 7 8 9 descending: 9 8 7 6 5 4 3 2 1 0
[編集] 関連項目
| 要素の順序を反転する (public member function) |