Name

unique_copy function template — Copies unique values

Synopsis

template<typename InIter, typename OutIter>
  OutIter unique_copy(InIter first, InIter last, OutIter result);
template<typename InIter, typename OutIter, typename BinaryPredicate>
  OutIter unique_copy(InIter first, InIter last, OutIter result,
                      BinaryPredicate pred);

The unique_copy function template copies items from [first, last) to the range that starts at result, removing duplicates. For each sequence of identical elements, only the first is kept. The return value is one past the end of the result range.

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

See Figure 13-21 for an example that calls unique_copy.

Copying unique elements
Figure 13-21. Copying unique elements

Technical Notes

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

Complexity is linear: exactly last - first 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.