.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 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

Looking to contribute?

Learn C++ on Codecademy