並べ替え
nondescending 順序にまたは二項述語で指定された順序の基準に従って指定された span 要素を配置します。
template<class RandomAccessIterator>
void sort(
RandomAccessIterator first,
RandomAccessIterator last
);
template<class RandomAccessIterator, class Predicate>
void sort(
RandomAccessIterator first,
RandomAccessIterator last,
Predicate comp
);
パラメーター
first
並べ替えられる範囲内の先頭の要素の位置を示すランダム アクセス反復子。last
並べ替えられる範囲の最後の要素の一つ前の位置 1 を示すランダム アクセス反復子。comp
順序の中で要素を満たす比較の条件を定義するユーザー定義の述語関数オブジェクト。 この二項述語は 2 個の引数を順序と false で異なる設定では、2 番目の引数を受け取り、true を返します。 この比較子関数は、シーケンスの要素のペアに厳密な弱い順序付けを課さなければ必要があります。 詳細については、「アルゴリズム」を参照してください。
解説
参照される範囲が有効である必要があります。; すべてのポインターは dereferenceable なり、シーケンス内で最後の位置は incrementation してプログラムからアクセスできます。
要素は、いずれも他未満である、同等ですが、必ずしも等しくなります。 sort アルゴリズムは安定していないため、同等の要素の相対的な順序を保持することは保証されません。 このアルゴリズム stable_sort は元の順序を維持します。
平均一種の複雑さは O (log n) N の ログ、N = *最初と最後の–*です。
使用例
// alg_sort.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional> // For greater<int>( )
#include <iostream>
// Return whether first element is greater than the second
bool UDgreater ( int elem1, int elem2 )
{
return elem1 > elem2;
}
int main( )
{
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1;
int i;
for ( i = 0 ; i <= 5 ; i++ )
{
v1.push_back( 2 * i );
}
int ii;
for ( ii = 0 ; ii <= 5 ; ii++ )
{
v1.push_back( 2 * ii + 1 );
}
cout << "Original vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
sort( v1.begin( ), v1.end( ) );
cout << "Sorted vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
// To sort in descending order. specify binary predicate
sort( v1.begin( ), v1.end( ), greater<int>( ) );
cout << "Resorted (greater) vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
// A user-defined (UD) binary predicate can also be used
sort( v1.begin( ), v1.end( ), UDgreater );
cout << "Resorted (UDgreater) vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
}
必要条件
ヘッダー: <algorithm>
名前空間: std