![]() |
VOOZH | about |
std::unique is used to remove duplicates of any element present consecutively in a range[first, last). It performs this task for all the sub-groups present in the range having the same element present consecutively. But, what if we don't want to alter with the original range and just want the result of std::unique to be copied into another container, for this we have another function defined in , i.e., std::unique_copy(). In this, only the first element from every consecutive group of equivalent elements in the range [first, last) is copied. It can be used in two ways as shown below:
template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result); first: Forward iterator to the first element in the container. last: Forward iterator to the last element in the container. result: Output iterator to the initial position of the container where the resulting range of values is stored. The value being pointed should be compatible with the value being assigned. Return Value: An iterator pointing to the end of the copied range, which contains no consecutive duplicates.
Before: 10 10 30 30 30 100 10 300 300 70 70 80 After: 10 30 100 10 30 70 80
template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate pred); Here, first, last and result are the same as previous case. 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 (if true, 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: It returns an iterator pointing to the end of the copied range, which contains no consecutive duplicates.
Before: You arre vvvisiting GFG After: You are visiting GFG
Where can it be used ?
v = 1 1 2 2 3 3 3 3 7 7 8 10 v1 = 1 2 3 7 8 10
v1 contains only unique elements