SGI

unique_copy

Category: algorithms Component type: function

Prototype

Unique_copy is an overloaded name; there are actually two unique_copy functions.
template <class InputIterator, class OutputIterator>
OutputIterator unique_copy(InputIterator first, InputIterator last,
                           OutputIterator result);

template <class InputIterator, class OutputIterator, class BinaryPredicate>
OutputIterator unique_copy(InputIterator first, InputIterator last,
                           OutputIterator result,
                           BinaryPredicate binary_pred);

Description

Unique_copy copies elements from the range [first, last) to a range beginning with result, except that in a consecutive group of duplicate elements only the first one is copied. The return value is the end of the range to which the elements are copied. This behavior is similar to the Unix filter uniq.

The reason there are two different versions of unique_copy is that there are two different definitions of what it means for a consecutive group of elements to be duplicates. In the first version, the test is simple equality: the elements in a range [f, l) are duplicates if, for every iterator i in the range, either i == f or else *i == *(i-1). In the second, the test is an arbitrary Binary Predicate binary_pred: the elements in [f, l) are duplicates if, for every iterator i in the range, either i == f or else binary_pred(*i, *(i-1)) is true. [1]

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

For the first version: For the second version:

Preconditions

Complexity

Linear. Exactly last - first applications of operator== (in the case of the first version of unique) or of binary_pred (in the case of the second version), and at most last - first assignments.

Example

Print all of the numbers in an array, but only print the first one in a consecutive group of identical numbers.
const int A[] = {2, 7, 7, 7, 1, 1, 8, 8, 8, 2, 8, 8};
unique_copy(A, A + sizeof(A) / sizeof(int), 
            ostream_iterator<int>(cout, " "));
// The output is "2 7 1 8 2 8".

Notes

[1] Strictly speaking, the first version of unique_copy is redundant: you can achieve the same functionality by using an object of class equal_to as the Binary Predicate argument. The first version is provided strictly for the sake of convenience: testing for equality is an important special case.

[2] BinaryPredicate is not required to be an equivalence relation. You should be cautious, though, about using unique_copy with a Binary Predicate that is not an equivalence relation: you could easily get unexpected results.

See also

Binary Predicate, unique, remove_copy, remove_copy_if, adjacent_find
[Silicon Surf] [STL Home]
Copyright © 1999 Silicon Graphics, Inc. All Rights Reserved. TrademarkInformation