How to Remove First Element of a vector in C++

Hello Coders! In this tutorial, we will be going to learn how we can remove the first element of a vector in C++.

Removing an element from a vector can be done using erase () function.

C++ Code: How to Remove First Element of a vector 

Lets Code It—>

#include <iostream>
#include <vector> //vector header file
using namespace std;
 
int main() {
   vector<int> digits; //initialize vector name
   digits.push_back(9);  //push the elements into the vector
   digits.push_back(8);
   digits.push_back(5);
   digits.push_back(4);   
      
   digits.erase(digits.begin());  //erase function
 
   for (int num: digits)
      cout << num << endl;
}

Output:

8
5
4


Code Discussion:

Firstly we have initialized a vector digits and push the elements ie. digits into the vector using push_back . We will use erase () function and we need to pass our iterator to the first element of the vector using vectorname.begin() and we will run a for loop in our vector and our final vector will be printed in our output screen using cout statement.

Leave a Reply

Your email address will not be published. Required fields are marked *