English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Deque erase() Usage and Example

C++ Deque (Double-ended Queue)

C ++ The Deque delete() function deletes elements from a specified position or range, effectively reducing the size of the deque by the number of deleted elements.

Syntax

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

Parameter

posIt defines the position from which elements are to be deleted from the deque.

(first, last)It defines the range of the deque where elements to be deleted are located.

Return Value

It returns an iterator pointing to the element immediately following the last element deleted by the function.

Example1

Let's look at a simple example that demonstrates deleting elements within a specified range.

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

Output:

The content of the deque:1 2 3 4 
After deleting the second and third elements, the content of the deque:1 3 4

Example2

Let's look at a simple example where elements are removed at specified positions

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

Output:

The content of the deque: mango, apple, strawberry, kiwi, ,
Now, the content of the deque: mango, apple, kiwi, ,

C++ Deque (Double-ended Queue)