Home » C++ algorithm unique() function

C++ algorithm unique() function

by Online Tutorials Library

C++ Algorithm unique()

C++ Algorithm unique() function is used to transform a sequence in such a way that each duplicate consecutive element becomes a unique element.

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 scanned for duplicate removal.

last: A forward iterator pointing the position one past the final element in the range to be scanned for duplicate removal.

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

Return value

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

Complexity

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

Data races

The object in the range [first, last) are accessed and potentially 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.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let’s see the simple example to demonstrate the use of unique():

Output:

1 2 3 4 5 6 7  

Example 2

Let’s see another simple example:

Output:

myvector contains: 10 20 30 20 10  

Example 3

Let’s see another simple example:

Output:

unsorted unique : 2,5,3,1,2,4,2,1,4,3  sorted unique : 1,2,3,4,5  

Example 4

Let’s see another simple example:

Output:

1 2 3 4 5 6 7   wanna go to space?  

Example 5

Let’s see another example:

Output:

Vector v1 is ( 5 -5 5 -5 5 -5 5 -5 4 4 4 4 7 ).  Removing adjacent duplicates from vector v1 gives   ( 5 -5 5 -5 5 -5 5 -5 4 7 ).  Removing adjacent duplicates from vector v1 under the    binary predicate mod_equal gives   ( 5 4 7 ).  Removing adjacent elements satisfying the binary    predicate mod_equal from vector v1 gives ( 5 7 ).  

Next TopicC++ Algorithm

You may also like