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
解决仅向前的迭代器通过最终元素的位置一个范围要浏览对复制删除。_Comp
定义要满足条件的用户定义的谓词函数对象,如果两个组件要执行视为等效的。 二进制谓词采用两个参数并返回 true,在满足和 false,在未满足。
返回值
对于不包含行中修改的新的末尾仅向前迭代器副本,寻址未移除的最后一个元素的位置一。
备注
算法的两种形式中移除第二个重复顺序对相等元素。
算法的操作是稳定的,能够更改已撤消删除元素的相对顺序。
引用的范围必须是有效的;所有指针必须dereferenceable,并在该序列中最后位置以访问按增量。 计算该序列中的元素算法不更改他 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