C++ Remove First Element from Vector

Last Updated On Monday 29th Nov 2021

Remove element from vector c++

An element can be removed from a vector using erase.

  • This function takes in an iterator to the position in the vector not the index.

The function begin() returns an iterator to the first element of the vector and can be added to to pass in subsequent positions.

Note : The erase does not check if the element exists or not, so be sure when erasing.

Remove first element from vector c++

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

int main() {
   vector<int> particles;
   particles.push_back(1);
   particles.push_back(2);
   particles.push_back(3);
   particles.push_back(4);
   particles.push_back(5);
   particles.push_back(6);

   particles.erase(particles.begin());  // erase first element

   for (int particle: particles)
        cout << particle << endl;
}
	
	2
3
4
5
6
	

Remove first 2 elements

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

int main() {
   vector<int> particles;
   particles.push_back(1);
   particles.push_back(2);
   particles.push_back(3);
   particles.push_back(4);
   particles.push_back(5);
   particles.push_back(6);

   particles.erase(particles.begin(), particles.begin()+2); // remove first 2 elements

   for (int particle: particles)
        cout << particle << endl;
}
	
	3
4
5
6
	

C++ vector remove element

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

int main() {
   vector<int> particles;
   particles.push_back(1);
   particles.push_back(2);
   particles.push_back(3);
   particles.push_back(4);
   particles.push_back(5);
   particles.push_back(6);

   particles.erase(particles.begin() + 3); // remove third element

   for (int particle: particles)
        cout << particle << endl;
}
	
	1
2
3
5
6
	

Clear All

Clear removes all elements in the vector reducing its size to 0.

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

int main() {
   vector<int> particles;
   particles.push_back(1);
   particles.push_back(2);
   particles.push_back(3);
   particles.push_back(4);
   particles.push_back(5);
   particles.push_back(6);

   particles.clear();

   for (int particle: particles)
        cout << particle << endl;
}