📜  C++ STL-algorithm.unique()函数

📅  最后修改于: 2020-10-17 05:11:22             🧑  作者: Mango

C++ STL algorithmunique()

C++ STL algorithm.unique()函数用于转换序列,使每个重复的连续元素成为唯一元素。

第一个版本使用运算符==比较元素,第二个版本使用给定的二进制谓词pred。

句法

equality (1)    template 
                          ForwardIterator unique (ForwardIterator first, ForwardIterator last);

predicate (2)    template 
                          ForwardIterator unique (ForwardIterator first, ForwardIterator last,
                          BinaryPredicate pred); 

参数

first:前向迭代器,指向要进行重复删除的要扫描范围内第一个元素的位置。

last:前向迭代器,将位置指向要扫描的范围中最后一个元素的后面,以进行重复删除。

pred:一个用户定义的谓词函数对象,它定义范围内的两个元素等效时要满足的条件。二进制谓词返回两个参数,满足时返回true,不满足时返回false。 0

返回值

指向不包含连续重复项的范围的新末端的第一个正向迭代器。

复杂度

复杂度在[first,last)范围内是线性的:比较每对连续元素,并对其中一些元素执行赋值操作。

数据竞争

在[first,last)范围内的对象将被访问并可能被修改。

异常安全

如果pred,元素比较,元素分配或迭代器上的任何操作抛出异常,则此函数将引发异常。

注意:无效的参数会导致未定义的行为。

例子1

让我们看一个简单的示例来演示unique()的用法:

#include 
#include 
#include 
#include 
#include 

using namespace std;
 
int main() 
{
    // remove duplicate elements
    vector v{1,2,3,1,2,3,3,4,5,4,5,6,7};
    sort(v.begin(), v.end()); 
    auto last = unique(v.begin(), v.end());
    // v now holds {1 2 3 4 5 6 7 x x x x x x}, where 'x' is indeterminate
    v.erase(last, v.end()); 
    for (int i : v)
      cout << i << " ";
    cout << "\n";
    
    return 0;
}

输出:

1 2 3 4 5 6 7

例子2

让我们看另一个简单的例子:

#include      // std::cout
#include     // std::unique, std::distance
#include        // std::vector

using namespace std;

bool myfunction (int i, int j) {
  return (i==j);
}

int main () {
  int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10
  vector myvector (myints,myints+9);

  // using default comparison:
  vector::iterator it;
  it = unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?
                                                         //                ^

  myvector.resize( distance(myvector.begin(),it) ); // 10 20 30 20 10

  // using predicate comparison:
  unique (myvector.begin(), myvector.end(), myfunction);   // (no changes)

  // print out content:
  std::cout << "myvector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  return 0;
}

输出:

myvector contains: 10 20 30 20 10

例子3

让我们看另一个简单的例子:

#include 
#include 
#include 

using namespace std;

void print(const char* tag, const vector& v) {
  cout << tag << " : ";
  bool first = true;
  for (int x : v) {
    if (first) {
      first = false;
    }
    else {
      cout << ',';
    }
    cout << x;
  }
  cout << endl;
}

int main() {

  {
    vector v = { 2,5,3,3,1,2,4,2,1,1,4,4,3,3,3 };

    decltype(v)::iterator result = unique(v.begin(), v.end());

    v.erase(result, v.end());

    print("unsorted unique", v);
  }

  {
      vector v = { 2,5,3,3,1,2,4,2,1,1,4,4,3,3,3 };

    sort(v.begin(), v.end());
    decltype(v)::iterator result = unique(v.begin(), v.end());

    v.erase(result, v.end());

    print("sorted unique", v);
  }
}

输出:

unsorted unique : 2,5,3,1,2,4,2,1,4,3
sorted unique : 1,2,3,4,5

例子4

让我们看另一个简单的例子:

#include 
#include 
#include 
#include 
#include 

using namespace std;

int main() 
{
    // remove duplicate elements (normal use)
    vector v{1,2,3,1,2,3,3,4,5,4,5,6,7};
    sort(v.begin(), v.end()); // 1 1 2 2 3 3 3 4 4 5 5 6 7 
    auto last = unique(v.begin(), v.end());
    // v now holds {1 2 3 4 5 6 7 x x x x x x}, where 'x' is indeterminate
    v.erase(last, v.end()); 
    for (int i : v)
      cout << i << " ";
    cout << "\n";
 
    // remove consecutive spaces
    string s = "wanna go    to      space?";
    auto end = unique(s.begin(), s.end(), [](char l, char r){
        return isspace(l) && isspace(r) && l == r;
    });
    // s now holds "wanna go to space?xxxxxxxx", where 'x' is indeterminate
    cout << string(s.begin(), end) << '\n';
}

输出:

1 2 3 4 5 6 7 
wanna go to space?

例子5

让我们看另一个例子:

#include   
#include   
#include   
#include   
#include   
  
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  v1;  
   vector ::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( ) );  
  
   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;  
   
   return 0;
}

输出:

Vector v1 is ( 5 -5 5 -5 5 -5 5 -5 4 4 4 4 7 ).
Removing adjacent duplicates from vector v1 gives
 ( 5 -5 5 -5 5 -5 5 -5 4 7 ).
Removing adjacent duplicates from vector v1 under the
  binary predicate mod_equal gives
 ( 5 4 7 ).
Removing adjacent elements satisfying the binary
  predicate mod_equal from vector v1 gives ( 5 7 ).