unique

Syntax:

    #include <algorithm>
    forward_iterator p_end unique( forward_iterator start, forward_iterator end );
    forward_iterator p_end unique( forward_iterator start, forward_iterator end, BinPred p );

The unique() algorithm removes all consecutive duplicate elements from the range [start, end]. The duplicate values are moved to the sequence's end.

If the binary predicate p is given, then it is used to test two elements to see if they are duplicates.

The return value of unique() is an iterator to the end of the modified range.

unique() runs in linear time. Example

// unique algorithm example
#include <iostream>
#include <algorithm>
#include <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<int> myvector (myints,myints+9);
  vector<int>::iterator it;
 
  // using default comparison:
  it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 30 20 20 10
                                                  //                ^
 
  myvector.resize( it - myvector.begin() );       // 10 20 30 20 10
 
  // using predicate comparison:
  unique (myvector.begin(), myvector.end(), myfunction);   // (no changes)
 
  // print out content:
  cout << "myvector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;
 
  cout << endl;
 
  return 0;
}

Output: myvector contains: 10 20 30 20 10

Related Topics: adjacent_find, remove, unique_copy