C++ Vector clear() function

clear() function removes all the elements from a vector.

Syntax

The syntax of clear() function is

void clear();

Example

In the following C++ program, we initialise a vector names with three elements, and then erase all the elements from this vector using clear() function.

C++ Program

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> names{ "apple", "banana", "cherry" };
    names.clear();
    cout << "Size of Vector : " << names.size() << endl;
}

Output

Size of Vector : 0
Program ended with exit code: 0

After clear(), all the elements are removed, and hence the size of the resulting vector is 0.

Conclusion

In this C++ Tutorial, we learned the syntax of clear() function, and how to use this clear() function to remove all the elements from given vector.