Vector Remove nth Element – C++

You can remove the nth element from a vector in C++ with the help of the erase() function. This function takes an iterator as an argument and removes the element at that position.

To remove the nth element from a vector, you need to:

  • Find the position of the nth element using the distance() function.
  • Use the erase() function to remove the nth element.

This code demonstrates how to remove an element from a vector in C++. The code first creates a vector and then adds 20 elements to it. It then removes the 5th, 10th, and 2nd elements from the vector using the erase function. Finally, it prints out the contents of the vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> myVector = {};

    // put values into the vector 
    for ( int i = 1; i <= 20; i ++ )  myVector.push_back(i) ;

    // remove the 5th element 
    myVector.erase( myVector.begin() + 4 );

    // remove the 10th element 
    myVector.erase(myVector.begin() + 9);

    // remove the 2th element 
    myVector.erase(myVector.begin() + 1);

      for (unsigned i=0; i<newvector.size(); ++i)
        std::cout << ' ' << newvector[i];
    std::cout << '\n';

      return 0;