In the C++ programming language, the deque clear() function is a predefined member function of the deque, i.e., double-ended queue. It can help to remove all the elements from the deque. Once we call the clear() function, the deque becomes empty and size has the value zero, and its capacity may remain unchanged.

In C++, the function certainly destroys all elements properly and frees the memory occupied by them, but the deque may have new elements placed in it without having to reallocate memory at once. It is clearly used whenever we need to reuse the same deque in a program to keep fresh data in it without constructing a new one.
It has the following syntax:
Here, we are going to discuss several examples that demonstrate deque clear() function.
This example demonstrates how to remove all elements from a deque using the clear() function.
Output:
Deque before clear(): 10 20 30 40 50 Deque after clear(): Size of deque: 0
Explanation:
In this example, we have created the deque with five integer values. After that, the elements in the deque are removed using the clear() function. When we execute the clear() function, the deque becomes empty, and the value of size() returns 0 because all the elements have been removed successfully.
This example demonstrates how to reuse a deque after removing all elements using the clear() function.
Output:
Deque before clear(): 10 20 30 40 50 Deque after clear() and inserting new elements: 100 200 Current size of deque: 2
Explanation:
In this example, the push_back() function is used to insert values in the deque. Thereafter, the clear() function wipes all the elements, leaving the deque empty. The deque can still be utilized without any problems because fresh elements are introduced after clearing the elements. The output attests that the deque now contains solely the recently added elements.
This example demonstrates how to remove string elements from a deque using the clear() function.
Output:
Size before clear(): 3 Size after clear(): 0
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India