C++ Algorithm unique_copy()
C++ Algorithm unique_copy() function is used to copy a sequence such as each duplicate consecutive element becomes a unique element.
first: A forward iterator pointing the position of the first element in the range to be copied.
last: A forward iterator pointing the position one past the final element in the range to be copied.
pred: A user-defined predicate function object that defines the condition to be satisfied if two elements in a range are to be taken as equivalent. A binary predicate returns two arguments and returns true when satisfied and false when not satisfied.
result: An output iterator pointing the position of the first element in the copied range that is receiving the copy with consecutive duplicates removed.
An iterator pointing to the new end of the copied range[first, last) that contains no consecutive duplicates.
Complexity is linear in the range [first, last): compares each pairs of consecutive elements, and performs assignment operation on some of them.
The object in the range [first, last) are accessed and the objects in the range between result and the returned value are modified.
This function throws an exception if any of pred, the element comparisons, the element assignments or the operations on iterator throws an exception.
Please note that invalid parameters cause an undefined behavior.
Let's see the simple example to demonstrate the use of unique_copy() where elements will be compared by operator==:
Before: 100 100 300 300 300 500 100 300 300 600 600 700 After: 100 300 500 100 300 600 700
In the above example, all the sub-group of consecutive duplicate elements from vector v have been reduced to only one element and copied to new vector v1.
Let's see another simple example to illustrate the use of unique_copy() where elements will be compared by pre-defined function:
Before: You arre vvvisiting vvvogie bbogie After: You arre visiting vogie bbogie
Let's see another simple example to check whether the container contains duplicates elements or not:
v1 contains only unique elements
In the above example, first we remove the duplicate elements from vector v and store the resultant elements into another vector v1 and then compare the v1 to v, if both are the same. (Means previous vector v contains only unique elements and there is no duplicate element).
Let's see another simple example to remove all the spaces from the given statement:
before: The string with many spaces! after: The string with many spaces!