function template
<algorithm>
std::unique
| equality (1) | template <class ForwardIterator> ForwardIterator unique (ForwardIterator first, ForwardIterator last); |
|---|---|
| predicate (2) | template <class ForwardIterator, class BinaryPredicate> ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate pred); |
Remove consecutive duplicates in range
[first,last).The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.
The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.
The function uses operator== to compare the pairs of elements (or pred, in version (2)).
The behavior of this function template is equivalent to:
|
|
Parameters
- first, last
- Forward iterators to the initial and final positions of the sequence of move-assignable elements. The range used is
[first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. - pred
- Binary function that accepts two elements in the range as argument, and returns a value convertible to
bool. The value returned indicates whether both arguments are considered equivalent (iftrue, they are equivalent and one of them is removed).
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return value
An iterator to the element that follows the last element not removed.The range between first and this iterator includes all the elements in the sequence that were not considered duplicates.
Example
|
|
Output:
myvector contains: 10 20 30 20 10
Complexity
For non-empty ranges, linear in one less than the distance between first and last: Compares each pair of consecutive elements, and possibly performs assignments on some of them.Data races
The objects in the range[first,last) are accessed and potentially modified.Exceptions
Throws if any of pred, the element comparisons, the element assignments or the operations on iterators throws.Note that invalid arguments cause undefined behavior.
See also
- unique_copy
- Copy range removing duplicates (function template)
- adjacent_find
- Find equal adjacent elements in range (function template)
- remove
- Remove value from range (function template)
- remove_if
- Remove elements from range (function template)