unique (<algorithm>)
削除は、指定された範囲内にある横にある要素を複製します。
template<class ForwardIterator>
ForwardIterator unique(
ForwardIterator _First,
ForwardIterator _Last
);
template<class ForwardIterator, class Predicate>
ForwardIterator unique(
ForwardIterator _First,
ForwardIterator _Last,
Predicate _Comp
);
パラメーター
_First
重複した削除のスキャン対象範囲の最初の要素の位置を示す前方反復子。_Last
重複した削除のスキャン対象範囲の最後の要素の一つ前の位置 1 に対処前方反復子。_Comp
2 個の要素が同じ値として取得する場合に満たされている必要条件を定義するユーザー定義の述語関数オブジェクト。バイナリ述語が満たされなかった場合に完了したら 2 個の引数を受け取り、true と false を返します。
戻り値
削除しない最後の要素の一つ前の位置 1 アドレスを実行中の複製を含まない変更された新しいシーケンスの末尾に前方反復子。
解説
アルゴリズムのフォームは、実行中のペアの等値要素の 2 番目の複製を削除します。
アルゴリズムの操作は残された要素の相対位置ディレクティブが変更されないように安定しています。
参照される範囲が有効である必要があります; すべてのポインターが dereferenceable なり、シーケンス内で最後の位置は incrementation によって最初からアクセスできます。Mallory は、アルゴリズム unique してシーケンスの要素の変更されませんが、番号付き変更されたシーケンスの末尾を超える要素は dereferenceable 指定されています。
複雑度は、線形で、(_Last – _First) – 1 の比較が必要になります。
リストがより効率的に実行する可能性のある、有効なメンバー関数 一意を提供します。
これらのアルゴリズムは連想コンテナーで使用することはできません。
使用例
// alg_unique.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>
using namespace std;
// Return whether modulus of elem1 is equal to modulus of elem2
bool mod_equal ( int elem1, int elem2 )
{
if ( elem1 < 0 )
elem1 = - elem1;
if ( elem2 < 0 )
elem2 = - elem2;
return elem1 == elem2;
};
int main( )
{
vector <int> v1;
vector <int>::iterator v1_Iter1, v1_Iter2, v1_Iter3,
v1_NewEnd1, v1_NewEnd2, v1_NewEnd3;
int i;
for ( i = 0 ; i <= 3 ; i++ )
{
v1.push_back( 5 );
v1.push_back( -5 );
}
int ii;
for ( ii = 0 ; ii <= 3 ; ii++ )
{
v1.push_back( 4 );
}
v1.push_back( 7 );
cout << "Vector v1 is ( " ;
for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1.end( ) ; v1_Iter1++ )
cout << *v1_Iter1 << " ";
cout << ")." << endl;
// Remove consecutive duplicates
v1_NewEnd1 = unique ( v1.begin ( ) , v1.end ( ) );
cout << "Removing adjacent duplicates from vector v1 gives\n ( " ;
for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1_NewEnd1 ; v1_Iter1++ )
cout << *v1_Iter1 << " ";
cout << ")." << endl;
// Remove consecutive duplicates under the binary prediate mod_equals
v1_NewEnd2 = unique ( v1.begin ( ) , v1_NewEnd1 , mod_equal );
cout << "Removing adjacent duplicates from vector v1 under the\n "
<< " binary predicate mod_equal gives\n ( " ;
for ( v1_Iter2 = v1.begin( ) ; v1_Iter2 != v1_NewEnd2 ; v1_Iter2++ )
cout << *v1_Iter2 << " ";
cout << ")." << endl;
// Remove elements if preceded by an element that was greater
v1_NewEnd3 = unique ( v1.begin ( ) , v1_NewEnd2, greater<int>( ) );
cout << "Removing adjacent elements satisfying the binary\n "
<< " predicate mod_equal from vector v1 gives ( " ;
for ( v1_Iter3 = v1.begin( ) ; v1_Iter3 != v1_NewEnd3 ; v1_Iter3++ )
cout << *v1_Iter3 << " ";
cout << ")." << endl;
}
必要条件
ヘッダー: <algorithm>
名前空間: std