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;
}
  

要求

标头: <算法>

命名空间: std

请参见

参考

标准模板库