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
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.
#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:
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.
#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:
Content of deque:mango ,apple ,strawberry ,kiwi ,
Now,Content of deque:mango ,apple ,kiwi ,