.clear()

abereFejiro9953409650's avatar
Published Nov 8, 2024
Contribute to Docs

In C++, the .clear() method removes all elements from a given deque container, leaving the container with a size of 0.

Syntax

dequeName.clear();
  • dequeName: The name of the deque container from which all elements will be removed.

Example

The example below showcases the use of the .clear() method:

#include <iostream>
#include <deque>
int main() {
// Create a deque of integers
std::deque<int> numbers;
// Add elements to the deque
numbers.push_back(50);
numbers.push_back(100);
numbers.push_back(150);
numbers.push_back(200);
// Display the elements of the deque before clearing
std::cout << "My deque contains: ";
for (int num : numbers) {
std::cout << num << " ";
}
// Clear all elements from the deque
numbers.clear();
std::cout << std::endl;
numbers.push_back(200);
// Display the elements of the deque after clearing and adding a new element
std::cout << "My deque contains: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}

The above code generates the following output:

My deque contains: 50 100 150 200
My deque contains: 200

Codebyte Example

The following codebyte demonstrates the use of the .clear() method, which removes all elements from the deque before adding a new element:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy