void sort(); // (1) C++98
constexpr void sort(); // (1) C++26
template <class Compare>
void sort(Compare comp); // (2) C++98
template <class Compare>
constexpr void sort(Compare comp); // (2) C++26
概要
コンテナを並べ替える
要件
型Tのoperator<もしくはcompが、狭義の弱順序で定義されること。
効果
型Tのoperator<もしくはcompに基いてコンテナの要素を並べ替える。
戻り値
なし
計算量
distance(begin(), end())をNとして、約N logN回の比較
例
#include <iostream>
#include <list>
int main()
{
std::list<int> ls = {2, 1, 3};
ls.sort();
for (int x : ls) {
std::cout << x << std::endl;
}
}
出力
1
2
3
参照
- LWG Issue 2824.
list::sortshould say that the order of elements is unspecified if an exception is thrown- 比較中に例外が送出された場合は
*thisの要素の順序が未規定となることが明記された(forward_list::sortと同様) - この修正は欠陥報告(DR)であり、C++98以降に遡及して適用される。この文言はもともと存在したが編集上の変更で失われたものであり、元の規定でも例外送出時の順序は保証されていなかったため
- 比較中に例外が送出された場合は
- P3372R3 constexpr containers and adaptors