C++ Standard Library C++ STL Library

C++ <list> - erase() Function



The C++ list::erase function is used to delete either a single element or a range of elements from the list. It reduces the size of the list 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 list.
first Iterator specifying position of the first element of the range in the list. Elements in [first, last) position range will be deleted.
last Iterator specifying position of the last element of the range in the list. 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 list::erase function is used to delete a single element from the list called MyList.

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

  cout<<"After erase() operation, MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";   

  return 0;
}

The output of the above code will be:

After erase() operation, MyList contains: Coding Skills

Example:

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

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50};
  list<int>::iterator it, start, end;
  
  start = end = MyList.begin();
  start++;
  advance(end, 4);
  //deletes a range of elements
  MyList.erase(start, end);

  cout<<"After erase() operation, MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++) {
    cout<<*it<<" ";   
  }
  return 0;
}

The output of the above code will be:

After erase() operation, MyList contains: 10 50

❮ C++ <list> Library