C++ deque clear() Function

Last Updated : 13 May 2026

Deque clear() Function

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.

C++ Deque clear() Function

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.

Syntax

It has the following syntax:

Parameters

  • The clear() function does not take any parameters.
  • It simply removes all the elements present in the deque.

Return type

  • It does not return any value (return type void).
  • After execution, the deque becomes empty. (size becomes 0).

Examples of deque clear() function

Here, we are going to discuss several examples that demonstrate deque clear() function.

Example 1: Remove All Elements from a Deque Using clear()

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.

Example 2: Reuse a Deque After Using clear() Function

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.

Example 3: Clear String Elements from a Deque Using clear()

This example demonstrates how to remove string elements from a deque using the clear() function.

Output:

Size before clear(): 3
Size after clear(): 0

Next TopicC++ Deque