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

  1. Iterate over the elements of given vector using index.
    1. 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.


#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 ( == ) {
            //remove element if already present
            v.erase(v.begin() + i);

   //print vector elements
   for(auto& element: v) {
      cout << element << "  ";


4  0  2  8


In this C++ Tutorial, we learned how to remove duplicates in a given vector.