Open In App

How to Clear All Elements from a Deque in C++?

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, deque also known as double-ended queue is a container provided by the Standard Template Library (STL) that allows efficient insertion and deletion at both ends. In this article, we will learn how to clear all elements from a deque in C++.

Example:

Input: 
myDeque = {10, 20, 30, 40};

Output: 
After clearing, the deque is empty

Remove All Elements from a Deque in C++

To clear all elements from a std::deque in C++, we can use the std::deque::clear() function that is used to remove all the elements from the deque container, thus making the deque empty.

Syntax

deque_Name.clear();

C++ Program to Clear All Elements from a Deque

The below program demonstrates how we can use clear() function to remove all elements from a deque in C++.

C++
// C++ program to demonstrate how we can use clear()
// function to remove all elements from a deque
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Creating a deque
    deque<int> dq = { 10, 20, 30, 40 };

    // Printing the elements of the deque
    cout << "Deque Elements:";
    for (int ele : dq) {
        cout << ele << " ";
    }
    cout << endl;
    // Printing the size of the deque before clearing it
    cout << "Before clearing, the deque has " << dq.size()
         << " elements" << endl;

    // Clearing the deque
    dq.clear();

    // Printing the size of the deque after  clearing it
    cout << "After clearing, the deque has " << dq.size()
         << " elements" << endl;

    return 0;
}

Output
Deque Elements:10 20 30 40 
Before clearing, the deque has 4 elements
After clearing, the deque has 0 elements

Time Complexity: O(1), where N is the size of the deque.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads