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.

  • It will not alter the original range and copy the result into another container.
  • The first version uses operator== to compare the elements and the second version uses the given binary predicate pred.

Syntax

Parameter

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.

Return value

An iterator pointing to the new end of the copied range[first, last) that contains no consecutive duplicates.

Complexity

Complexity is linear in the range [first, last): compares each pairs of consecutive elements, and performs assignment operation on some of them.

Data races

The object in the range [first, last) are accessed and the objects in the range between result and the returned value are modified.

Exception safety

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.

Example 1

Let's see the simple example to demonstrate the use of unique_copy() where elements will be compared by operator==:

Output:

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.

Example 2

Let's see another simple example to illustrate the use of unique_copy() where elements will be compared by pre-defined function:

Output:

Before: You arre vvvisiting vvvogie bbogie
After: You arre visiting vogie bbogie

Example 3

Let's see another simple example to check whether the container contains duplicates elements or not:

Output:

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).

Example 4

Let's see another simple example to remove all the spaces from the given statement:

Output:

before:  The      string    with many       spaces!
after:    The string with many spaces!

Next TopicC++ Algorithm




Latest Courses