Deque Erase Function

C++ Deque erase

C++ Deque erase function removes the element from the specified position or range and this effectively reduces the size of the deque by the number of elements removed.

Syntax

Example

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

Parameter

pos : It defines the position at which the element to be removed from the deque.

(first,last) : It defines the range within deque between which the elements to be removed.

Return value

It returns an iterator pointing to the element that followed the last element removed by the function.

Example 1

Let's see a simple example when element is removed within a 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 see a simple example when the element is removed at the specified position

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: