How to use the unique() function in C++

The unique() function in C++ helps remove all the consecutive duplicate elements from the array or vector. This function cannot resize the vector after removing the duplicates, so we will need to resize our vector once the duplicates are removed. This function is available in the <algorithm.h> header file.

Parameters

The find() function accepts the following parameters:

  • first: This is an iterator that points to the first index of the array or vector where we want to perform the search operation.

  • last: This is an iterator that points to the last index of the array or vector to where we want to perform the search operation.

Return

The unique() function returns an iterator pointing to the element that follows the last element that was not removed.

Code

Let’s look at the code below:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {10,20,20,20,30,30,20,20,10};
auto it = unique(vec.begin(), vec.end());
vec.resize(distance(vec.begin(), it));
for (it = vec.begin(); it!=vec.end(); ++it)
cout << ' ' << *it;
}

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In line 8, we create a vector containing integer elements.
  • In line 10, we call the unique() function and pass the required parameters.
  • In line 12, we need to resize the vector. We resized it to the iterator, pointing to the last element not being removed as a duplicate.
  • In lines 14 and 15, we print the new vector. (Note that here 20 occurs twice because the unique() function only removes the consecutive duplicates).

Free Resources