std::list<T,Allocator>::sort
提供: cppreference.com
void sort(); |
(1) | |
template< class Compare > void sort( Compare comp ); |
(2) | |
要素を昇順にソートします。 等しい要素の順序は維持されます。 最初のバージョンは要素の比較に operator< を使用し、2番目のバージョンは指定された比較関数 comp
を使用します。
例外が投げられた場合、 *this 内の要素の順序は未規定です。
目次 |
[編集] 引数
comp | - | 最初の要素が2番目の要素より小さい (前に順序づけられる) 場合に true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。 比較関数のシグネチャは以下と同等なものであるべきです。 bool cmp(const Type1 &a, const Type2 &b); シグネチャが const & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、 |
[編集] 戻り値
(なし)
[編集] 計算量
およそ N log N 回の比較、ただし N はリスト内の要素の数です。
[編集] ノート
std::sort はランダムアクセスイテレータを要求するため、 list
で使用することはできません。 この関数は std::sort と異なり、 list
の要素型が swap 可能であることを要求せず、すべてのイテレータの値を維持し、安定なソートを行います。
[編集] 例
Run this code
#include <iostream> #include <functional> #include <list> std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list) { for (auto &i : list) { ostr << " " << i; } return ostr; } int main() { std::list<int> list = { 8,7,5,9,0,1,3,2,6,4 }; std::cout << "before: " << list << "\n"; list.sort(); std::cout << "ascending: " << list << "\n"; list.sort(std::greater<int>()); std::cout << "descending: " << list << "\n"; }
出力:
before: 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