In this C++ tutorial, you will learn about vector::clear() function, its syntax, and how to use this function to remove all the elements in a vector, with example programs.

C++ Vector clear() function

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


The syntax of clear() function is

void clear();


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" };
    cout << "Size of Vector : " << names.size() << endl;


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.


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.