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.
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.
The unique()
function returns an iterator pointing to the element that follows the last element that was not removed.
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;}
unique()
function and pass the required parameters.unique()
function only removes the consecutive duplicates).