list::unique | member function |
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 specially 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.
Paramaters
- BinaryPredicate
- Binary predicate that, taking two values of the same type than those contained in the list object, returns true to remove from the container the element passed as first argument, and false otherwise.
Return value
noneExample
// 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
list::remove | Remove elements with specific value (public member function) |
list::remove_if | Remove elements fulfilling condition (public member function template) |
list::erase | Erase elements (public member function) |
list::pop_back | Delete last element (public member function) |
list::pop_front | Delete first element (public member function) |