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.
Syntax
The syntax of clear() function is
</>
Copy
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
</>
Copy
#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.