Name

unique function template — Removes adjacent, equal values from a range

Synopsis

template<typename FwdIter> 
  FwdIter unique(FwdIter first, FwdIter last);
template<typename FwdIter, typename BinaryPredicate>
  FwdIter unique(FwdIter first, FwdIter last, BinaryPredicate pred);

The unique function template “removes” repetitions of adjacent, identical elements from the range [first, last). The return value is one past the new end of the range. For each sequence of identical elements, only the first is kept. The input range does not have to be sorted, but if it is, all duplicates are “removed,” leaving only unique values (hence the function’s name).

Nothing is actually erased from the underlying container; instead, items to the right are copied to new positions at lower indices (to the left) so they overwrite the elements that are duplicates. See Figure 13-21 (under unique_copy) for an example of the removal process.

The first form compares items with the == operator. The second form calls pred(a, b).

Technical Notes

The unique function template assigns *(first + n++) = *(first + m) for all m in [0, last - first), in which m == 0 or *(first +m) == *(first + m - 1) is false. It returns first + n.

Complexity is linear: exactly max(0, last - first - 1) comparisons are performed.

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.