How to Remove Duplicates from a Vector While Preserving Order in C++?
Last Updated :
05 Feb, 2024
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.
- Create an unordered_set and then iterate through the vector and keep checking whether the element exists in a set or not.
- If it does not exist, then insert it in the set and move to the next vector element.
- 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++
#include <algorithm>
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
void removeDuplicates(vector< int >& myVector)
{
unordered_set< int > seen;
auto newEnd = remove_if(
myVector.begin(), myVector.end(),
[&seen]( int & value) {
if (seen.find(value) == seen.end()) {
seen.insert(value);
return false ;
}
return true ;
});
myVector.erase(newEnd, myVector.end());
}
int main()
{
vector< int > myVector = { 1, 2, 5, 4, 3, 2, 1, 5, 6, 5 };
removeDuplicates(myVector);
for ( int x : myVector) {
cout << x << " " ;
}
cout << endl;
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...