unique(), unique_copy()
All consecutive groups of elements containing either the same value (using the equality operator) or evaluating as true when passed an optional alternative comparison operation are collapsed into a single element. In the word Mississippi, the semantic result is "Misisipi." Because the three i's are not consecutive, they are not collapsed, nor are the two pairs of s's. To guarantee that all duplicated elements are collapsed, we would first sort the container.
As with remove(), the container's actual size is not changed. Each unique element is assigned in turn to the next free slot, beginning with the first element of the container. In our example, the physical result is "Misisipippi," where the character sequence ppi represents the leftover piece of the algorithm. The returned iterator marks the beginning of the refuse. Typically this iterator is then passed to erase(). (Because the built-in array does not support the erase() operation, unique() is less suitable for arrays; unique_copy() is more appropriate.)
#include <algorithm>
int ia[] = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5 };
vector<int> vec( ia, ia+10 );
sort( vec.begin(), vec.end() );
iter = unique( vec.begin(), vec.end() );
vec.erase( vec_iter, vec.end() ); // vec: 0 1 2 3 4 5
int ia2[10];
sort( ia, ia+10 );
unique_copy( ia, ia+10, ia2 );
|