Open In App

How to Remove Duplicates from a Vector in C++?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate the removal of duplicates from
// a vector using unique and erase methods.
  
#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 the vector so that we can bring the duplicate
    // elements together avoid this step if the vector is
    // already sorted.
    sort(elements.begin(), elements.end());
  
    // use unique() to bring all the duplicates to end
    // and get the ierator for the modified vector
    auto it
        = unique(elements.begin(), elements.end());
  
    // Use erase method  to remove all the duplicates
    // from the vector
    elements.erase(it, elements.end());
  
    // Print the updated vector
    for (auto& element : elements) {
        cout << element << " ";
    }
  
    return 0;
}


Output

1 2 3 7 8 9 11 20 

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads