.clear()
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 integersstd::deque<int> numbers;// Add elements to the dequenumbers.push_back(50);numbers.push_back(100);numbers.push_back(150);numbers.push_back(200);// Display the elements of the deque before clearingstd::cout << "My deque contains: ";for (int num : numbers) {std::cout << num << " ";}// Clear all elements from the dequenumbers.clear();std::cout << std::endl;numbers.push_back(200);// Display the elements of the deque after clearing and adding a new elementstd::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 200My 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours