STL's unique() algorithm eliminates all but the first element from every consecutive group of equal elements in a sequence of elements. unique() takes two forward iterators, the first of which marks the sequence's beginning and the second marks its end. The algorithm scans the sequence and removes repeated identical values. The duplicate values are moved to the sequence's end. For example, applying unique to the following sequence of integers:
changes their order to:
unique() doesn't really delete the duplicate values; it moves them to the container's end. The third element in the original container is moved one position past the final 2. unique() returns an iterator pointing to the logical end of the container. In other words, it returns an iterator pointing to the element 2, not 0. You can delete all the duplicate elements that were moved past the logical end using the iterator returned from unique(). For example:
vector <int> vi;
vi.push_back(1); // insert elements into vector
//move consecutive duplicates past the end; store new end
// delete all elements past new_end
unique() is useful when you want to make sure that only a single instance of a given value exists in a range, regardless of its distribution. For example, suppose you want to write an automated dictionary containing all the words Shakespeare's texts. First, you scan all the words in his texts and store them in a vector. Next, you sort the vector using the sort() algorithm. Finally, apply the unique() algorithm to the sorted vector to move duplicate words past its logical end and erase the duplicates as shown above.