文法:
#include <list> void sort(); void sort( BinPred p );
sort()関数はリストを昇順でソートするのに使用します。順序は < 演算子を利用して行われます。また、p関数が指定されていた場合には、要素が他の要素よりも小さいかどうかを決定するのに使用されます。
ソートはN log N回行われます。
関連トピック: reverse
シンプルなサンプル:
#include <iostream> #include <list> using namespace std; // T t; cout << t;がエラー無くコンパイルできると想定しています template<class T> inline ostream & operator<< ( ostream & theOstream, const list<T> & theList ) { typename list<T>::const_iterator listIterator = theList.begin(); for ( int i = 0; listIterator != theList.end(); ++listIterator, i ++ ) theOstream << " [" << i << "]: \"" << (*listIterator) << "\"" << endl; return theOstream; } struct Functor { bool operator()( const char * a, const char * b ) { return strcmp(a,b) < 0; } }; int main() { list<char*> l; /* サンプルのテストデータをロードします。 */ char s[3]; s[2] = '\0'; for ( s[0]='c'; s[0]>='a'; s[0]-- ) for ( s[1]='c'; s[1]>='a'; s[1]-- ) l.push_back(strdup(s)); /* テストデータを表示します */ cout << l << endl; /* リストをソートします */ Functor f; l.sort(f); /* ソート後の結果を表示 */ cout << l << endl; }