C++ Standard Library C++ STL Library

C++ <deque> - clear() Function



The C++ deque::clear function is used to clear all elements of the deque. This function makes the deque empty with a size of zero.

Syntax

void clear();
void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

In the example below, the deque::clear function is used to clear all elements of the deque called MyDeque.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<int> MyDeque{10, 20, 30, 40, 50};
  deque<int>::iterator it;

  cout<<"Before clear() function: \nThe deque contains:";
  for(it = MyDeque.begin(); it != MyDeque.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nDeque size is: "<<MyDeque.size()<<"\n\n";

  MyDeque.clear();

  cout<<"After clear() function: \nThe deque contains:";
  for(it = MyDeque.begin(); it != MyDeque.end(); ++it)
    cout<<" "<<*it;

  cout<<"\nDeque size is: "<<MyDeque.size();
  return 0;
}

The output of the above code will be:

Before clear() function: 
The deque contains: 10 20 30 40 50
Deque size is: 5

After clear() function: 
The deque contains:
Deque size is: 0

❮ C++ <deque> Library