In C++, vector provides a function vector::erase() to delete an element from vector based on index position. We can pass the iterator pointing to the ith element to the erase() function. It will delete the element at ith index from the vector. For example, let’s see how to delete element at index 3 from a vector in C++,

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> vecObj {11, 22, 33, 44, 55, 66, 77};

    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;

    int i = 3;
    //Remove element at ith index position in vector
    vecObj.erase(vecObj.begin() + i); 

    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;
}

Output:

11, 22, 33, 44, 55, 66, 77,
11, 22, 33, 55, 66, 77,

It deleted the the element at index position 3 from the vector. As indexing starts from 0, so element at index 3 is the 4th element in vector.

How did it work?

In vector the begin() function returned the iterator of first element in vector and then we added i in it (i==3), so it returned the iterator of element at index position 3. Then we passed the iterator of element at index position 3 to the erase() function. So it deleted the element at index position 3 in vector.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.