In this C++ tutorial, you shall learn how to remove duplicates in a given vector using nested For loop, with example programs.
Remove duplicates in Vector in C++
To remove duplicates in a vector in C++
- Iterate over the elements of given vector using index.
- If there is an element prior to the current element, delete the current element.
C++ Program
In the following program, we take an integer vector in v
, and remove the duplicate elements in it.
We use For loop to iterate over the elements of the vector, and If statement to compare the elements.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
using namespace std;
int main() {
//initialize a vector
vector<int> v { 4, 0, 4, 2, 8, 2, 2 };
//remove duplicates
for (unsigned int i = 1 ; i < v.size(); ++i) {
for (unsigned int k = 0 ; k < i; ++k) {
if ( v.at(i) == v.at(k) ) {
//remove element if already present
v.erase(v.begin() + i);
--i;
break;
}
}
}
//print vector elements
for(auto& element: v) {
cout << element << " ";
}
}
Output
4 0 2 8
Conclusion
In this C++ Tutorial, we learned how to remove duplicates in a given vector.