What is deque.erase( ) in C++?


In this article we will be discussing the working, syntax and examples of deque::erase() function in C++.

What is a Deque in C++ STL?

Deque is the Double Ended Queues that are the sequence containers which provides the functionality of expansion and contraction on both the ends. A queue data structure allow user to insert data only at the END and delete data from the FRONT. Let’s take the analogy of queues at bus stops where the person can be inserted to a queue from the END only and the person standing in the FRONT is the first to be removed whereas in Double ended queue the insertion and deletion of data is possible at both the ends.

What is deque::erase()?

This function is used to remove the element from the container at specified position and in a range. This function reduces the size of the deque container by the number of elements removed. Deque containers are efficient in removing or inserting the elements at the beginning or at the end of the deque container.

Syntax

dequename.erase(Position)
dequename.erase( beginning position, ending position)

Parameter

It defines the either the position of element to be removed from the deque container or in the form of iterator, it can also define the specified range to be deleted/erased from the container.

Example

Input: 2 3 4 5 6 7 8
Output: 2 4 6 8
Input: 5 6 7 8 9 3 4 6
Output: 5 3 4 6

Approach can be followed

  • First we initialize the deque.

  • Then we print the deque.

  • Then we define the erase( ) function.

  • Then we print the new deque after erasing operation.

By using above approach we can erase the elements from deque. While defining the erase( ) function we specify the position of the element to be deleted Or specify the range of element to be deleted.

Example

// C++ code to demonstrate the working of deque.erase( ) function
#include<iostream.h>
#include<deque.h>
Using namespace std;
int main( ){
   // initializing deque
   deque<int> deque ={ 1 2 3 4 5 6 7 8 9 10 };
   cout<< “ Deque: “;
   for( auto x = deque.begin( ); x != deque.end( ); ++x)
      cout<< *x << “ “;
   // Erase 5th element in deque
   deque.erase(deque.begin( ) + 4)
   // Erase first four element in deque
   deque.erase(deque.begin( ), deque.begin( ) + 4)
   // Printing new deque
   cout<< “ New deque:”;
   for( x = deque.begin( ) ; x >= deque.end( ); ++x)
      cout<< “ “ <<*x;
   return 0;
}

Output

If we run the above code then it will generate the following output

Input – Deque: 1 2 3 4 5 6 7 8 9 10
Output – New Deque: 6 7 8 9 10

Updated on: 05-Mar-2020

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements