C++ Standard Library C++ STL Library

C++ <vector> - erase() Function



The C++ vector::erase function is used to delete either a single element or a range of elements from the vector. It reduces the size of the vector by number of elements deleted from the container.

Syntax

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

Parameters

position Iterator specifying position of the element in the vector.
first Iterator specifying position of the first element of the range in the vector. Elements in [first, last) position range will be deleted.
last Iterator specifying position of the last element of the range in the vector. Elements in [first, last) position range will be deleted.

Return Value

A random access iterator pointing to the new position of the element that followed the last element erased.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the vector::erase function is used to delete a single element from the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<string> MyVector{"Alpha","Coding","Skills"};
 
  //deletes element at 0 position
  MyVector.erase(MyVector.begin());

  cout<<"After erase() operation, MyVector contains: ";
  for(int i = 0; i < MyVector.size(); i++)
    cout<<MyVector[i]<<" ";   

  return 0;
}

The output of the above code will be:

After erase() operation, MyVector contains: Coding Skills

Example:

Lets see another example where MyVector contains integer values and vector::erase function is used to delete a range of elements.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};

  //deletes a range of elements
  MyVector.erase(MyVector.begin()+1, MyVector.begin()+4);

  cout<<"After erase() operation, MyVector contains: ";
  for(int i = 0; i < MyVector.size(); i++)
    cout<<MyVector[i]<<" ";   

  return 0;
}

The output of the above code will be:

After erase() operation, MyVector contains: 10 50

❮ C++ <vector> Library