How to Remove Duplicates from a Vector in C++?
Last Updated :
29 Jan, 2024
In C++, vectors are sequence containers that can contain duplicate elements. In this article, we will discuss how to remove all the duplicate elements from a given vector.
Example
Input: vec = {1,2,3,2,2,1,4,5,6,5,7}
Output: 1 2 3 4 5 6 7
Removing Duplicates from a Vector in C++
To remove duplicates from the vector, we can use the combination of std::erase and std::unique algorithms. The std::unique moves all the duplicate elements to the end and it returns an iterator pointing to the new end of the current vector. Then we can use the std::erase method to remove all the duplicate elements that are stored at the end of the vector.
Example
The below example demonstrates the removal of duplicates from a vector using unique and erase methods.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > elements
= { 9, 8, 1, 3, 7, 11, 20, 1, 1, 2, 3, 2 };
sort(elements.begin(), elements.end());
auto it
= unique(elements.begin(), elements.end());
elements.erase(it, elements.end());
for ( auto & element : elements) {
cout << element << " " ;
}
return 0;
}
|
Time Complexity: O(N log N)
Auxiliary Space: O(1)
We can also use set to remove duplicates from vector and unordered_set when the order of the elements do not matter and we want want a solution which is faster.
Share your thoughts in the comments
Please Login to comment...