public member function

std::list::unique

<list>
  void unique ( );
template <class BinaryPredicate>
  void unique ( BinaryPredicate binary_pred );
Remove duplicate values
The first version, with no parameters, removes all but the first element from every consecutive group of equal elements in the list container.

Notice that an element is only removed from the list if it is equal to the element immediately preceding it. Thus, this function is especially useful for sorted lists.

For the second version, accepting a binary predicate, a specific comparison function to determine the "uniqueness" of an element can be specified. In fact, any behavior can be implemented (and not only a plain comparison), but notice that the function will call binary_pred(*i,*(i-1)) for all pairs of elements (where i is an iterator to an element) and remove i from the list if the predicate returns true.

The elements removed have their destructors called and their iterators and references become invalid.

A global algorithm function, unique, exists with a similar behavior but operating between two iterators.

Parameters

binary_pred
Binary predicate that, taking two values of the same type than those contained in the list object as argument, returns true to remove the element passed as first argument from the container, and false otherwise.
BinaryPredicate can either be a function pointer type or a class that overloads operator().

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// list::unique
#include <iostream>
#include <cmath>
#include <list>
using namespace std;

// a binary predicate implemented as a function:
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:
class is_near
{
public:
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
};

int main ()
{
  double mydoubles[]={ 12.15,  2.72, 73.0,  12.77,  3.14,
                       12.77, 73.35, 72.25, 15.3,  72.25 };
  list<double> mylist (mydoubles,mydoubles+10);
  
  mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,
                             // 15.3,  72.25, 72.25, 73.0,  73.35

  mylist.unique();           //  2.72,  3.14, 12.15, 12.77
                             // 15.3,  72.25, 73.0,  73.35

  mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15
                                       // 15.3,  72.25, 73.0

  mylist.unique (is_near());           //  2.72, 12.15, 72.25

  cout << "mylist contains:";
  for (list<double>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}


Output:
mylist contains: 2.72 12.15 72.25

Complexity

Linear in size-1.

See also