Deque Erase Function - C++ Programming Tutorial
C++ Course / STL Queue & Stack / Deque Erase Function

Deque Erase Function

BLUF: Mastering Deque Erase Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Deque Erase Function

C++ is renowned for its efficiency. Learn how Deque Erase Function enables low-level control and high-performance computing in the tutorial below.

C++ Deque erase

The erase function in C++ for Deque eliminates the element at a specified position or within a range, resulting in a reduction of the deque's size by the number of elements that are removed.

Syntax

Example

iterator erase(iterator pos);
iterator erase(iterator first,iterator last);

Parameter

It specifies the index indicating the location from where the element should be deleted from the deque.

It specifies the range within the deque indicating which elements are to be deleted.

Return value

It yields an iterator directing to the element succeeding the final element eliminated by the function.

Example 1

Let's consider a basic scenario where an item is deleted from a specified range.

Example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
    deque<int> d={1,2,3,4};
    deque<int>::iterator itr;
    cout<<"Content of deque:";
    for(itr=d.begin();itr!=d.end();++itr)
    cout<<*itr<<" ";
    cout<<'\n';
    d.erase(d.begin()+1,d.begin()+2);
    cout<<"After erasing second and third element,Content of deque:";
    for(itr=d.begin();itr!=d.end();++itr)
    cout<<*itr<<" ";
    return 0;
}

Output:

Output

Content of deque:1 2 3 4 
After erasing second and third element,Content of deque:1 3 4

Example 2

Let's examine a basic scenario where the item is deleted from the designated location.

Example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
    deque<string> str={"mango","apple","strawberry","kiwi"};
    deque<string>::iterator itr;
    cout<<"Content of deque:";
    for(itr=str.begin();itr!=str.end();++itr)
    cout<<*itr<<" ,";
    str.erase(str.begin()+2);
    cout<<'\n';
      cout<<"Now,Content of deque:";
     for(itr=str.begin();itr!=str.end();++itr)
    cout<<*itr<<" ,";
    return 0;
}

Output:

Output

Content of deque:mango ,apple ,strawberry ,kiwi ,
Now,Content of deque:mango ,apple ,kiwi ,

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience