Open In App

How to Remove Duplicates from a Vector While Preserving Order in C++?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A vector in C++ is used for storing values of certain data types in contiguous memory locations like arrays. In this article, we will learn how to remove duplicates from an unsorted vector while keeping the original order of elements in C++.

Example

Input:
myVector = {1, 2, 5, 4, 3, 2, 1, 5, 6, 5}
Output:
myVector = { 1, 2, 5, 4, 3, 6 }

Remove Duplicates from Vector in C++

To remove duplicates from the vector while preserving the order we can use the unordered_set() combined with std::remove_if algorithm.

  1. Create an unordered_set and then iterate through the vector and keep checking whether the element exists in a set or not.
  2. If it does not exist, then insert it in the set and move to the next vector element.
  3. If it does exist in the set, then remove it from the vector using std::vector else remove it.

C++ Program to Remove Duplicates from Vector while Keeping the Original Order

The below example demonstrates how we can remove duplicates from vectors while preserving the order.

C++




// C++ Program to Remove Duplicates from a Vector
#include <algorithm>
#include <iostream>
#include <unordered_set>
#include <vector>
  
using namespace std;
  
void removeDuplicates(vector<int>& myVector)
{
    unordered_set<int> seen;
  
    // Using remove_if to eliminate duplicates and get the
    // new end iterator
    auto newEnd = remove_if(
        myVector.begin(), myVector.end(),
        [&seen](int& value) {
            // Checking if value has been seen; if not, add
            // to seen and keep in vector
            if (seen.find(value) == seen.end()) {
                seen.insert(value);
                return false; // Don't remove the item
            }
            return true; // Remove the item
        });
  
    // Erase the non-unique elements
    myVector.erase(newEnd, myVector.end());
}
  
int main()
{
    // Sample vector with duplicates
    vector<int> myVector = { 1, 2, 5, 4, 3, 2, 1, 5, 6, 5 };
  
    // Remove duplicates from the vector
    removeDuplicates(myVector);
  
    // Display the vector after removing duplicates
    for (int x : myVector) {
        cout << x << " ";
    }
    cout << endl;
  
    return 0;
}


Output

1 2 5 4 3 6 

Time Complexity: O(n), where n is the number of elements in the vector.
Space Complexity: O(K), where K is the number of unique elements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads