C++ .clear()
Published Aug 25, 2024
Contribute to Docs
The .clear() method is used to remove all elements from a vector.
Syntax
vector.clear();
The vector must be defined using std::vector before the .clear() method can be used.
Example
In the example below, .clear() method is called on the numbers vector:
#include <iostream>#include <vector>int main() {// Declaring a vector with 4 integersstd::vector<int> numbers = {1, 2, 3, 4};// Print out vector size before clear method is calledstd::cout << "Before: " << numbers.size()<<"\n";// Call the clear method on numbers vectornumbers.clear();// Print out the size after clear method is calledstd::cout << "After: " << numbers.size()<<"\n";}
The output of the above code is:
Before: 4After: 0
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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours