C++ Standard Library C++ STL Library

C++ <deque> - erase() Function



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

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

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

  return 0;
}

The output of the above code will be:

After erase() operation, MyDeque contains: Coding Skills

Example:

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

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

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

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

The output of the above code will be:

After erase() operation, MyDeque contains: 10 50

❮ C++ <deque> Library