Learn how to remove first element from a vector in C++ using erase() function.

In C++, the vector class provides a member function erase(), to remove a single or multiple elements.

iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);

To delete single element from a vector using erase() function, pass the iterator of the element to it, like erase(it). It will delete the element pointed by the iterator. It returns an iterator pointing to the new location of the next entity in vector i.e. the element followed the last deleted element.

To delete the first element from vector pass the iterator of the first element to erase() function i.e.

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

//Remove first element from vector
vecObj.erase(vecObj.begin()); 

It will delete the first element from vector. The vector::begin() function returns the iterator of the first element in vector and we passed that to the erase() function. Therefore it deleted the first element from vector.

Checkout the complete example,

#include <vector>
#include <iostream>

using namespace std;

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

    // Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;

    //Remove first element from vector
    vecObj.erase(vecObj.begin()); 

    // Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;
}

Output:

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

It removed the first element from vector.

Summary

Today, we leaned about removing the first element from vector using erase() & begin() in C++.

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.