deque::clear() and deque::erase() in C++ STL

Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.

deque::clear()

clear() function is used to remove all the elements of the deque container, thus making its size 0.Syntax :

dequename.clear()Parameters :
No parameters are passed.
Result :
All the elements of the deque are
removed ( or destroyed )

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// CPP program to illustrate

// Implementation of clear() function

#include <deque>

#include <iostream>

usingnamespacestd;

intmain()

{

deque<int> mydeque{ 1, 2, 3, 4, 5 };

mydeque.clear();

// Deque becomes empty

// Printing the deque

for(autoit = mydeque.begin(); it != mydeque.end(); ++it)

cout << ' '<< *it;

return0;

}

Output:

No Output

deque::erase()

erase() function is used to remove elements from a container from the specified position or range.

Syntax :

1. dequename.erase(position)
2. dequename.erase(startingposition, endingposition)Parameters :
Position of the element to be removed in the form of iterator.
or the range specified using start and end iterator.
Result :
Elements are removed from the specified
position of the container.

Algorithm
1. Run a loop till the size of the deque.
2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement iterator.
3. Print the final deque.

// CPP program to illustrate

// Application of erase() function

#include <deque>

#include <iostream>

usingnamespacestd;

intmain()

{

deque<int> mydeque{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };

for(autoi = mydeque.begin(); i != mydeque.end(); ++i) {

if(*i % 2 == 0) {

mydeque.erase(i);

i--;

}

}

// Printing the deque

for(autoit = mydeque.begin(); it != mydeque.end(); ++it)

cout << ' '<< *it;

return0;

}

Output:

1 3 5 7 9

clear() VS erase() . When to use what?

clear() removes all the elements from a deque container, thus making its size 0. All the elements of the deque are removed using clear() function.erase() function on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.