C++ .clear()

eddiepeters00's avatar
Published Aug 25, 2024
Contribute to Docs

The .clear() method is used to remove all elements from a vector.

  • 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

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 integers
std::vector<int> numbers = {1, 2, 3, 4};
// Print out vector size before clear method is called
std::cout << "Before: " << numbers.size()<<"\n";
// Call the clear method on numbers vector
numbers.clear();
// Print out the size after clear method is called
std::cout << "After: " << numbers.size()<<"\n";
}

The output of the above code is:

Before: 4
After: 0

All contributors

Contribute to 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