C++ <vector> - clear() Function
The C++ vector::clear function is used to clear all elements of the vector. This function makes the vector empty with a size of zero.
Syntax
void clear();
void clear() noexcept;
Parameters
No parameter is required.
Return Value
None.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the vector::clear function is used to clear all elements of the vector called MyVector.
#include <iostream> #include <vector> using namespace std; int main (){ vector<int> MyVector{10, 20, 30, 40, 50}; vector<int>::iterator it; cout<<"Before clear() function: \nMyVector contains:"; for(it = MyVector.begin(); it != MyVector.end(); ++it) cout<<" "<<*it; cout<<"\nMyVector size is: "<<MyVector.size()<<"\n\n"; MyVector.clear(); cout<<"After clear() function: \nMyVector contains:"; for(it = MyVector.begin(); it != MyVector.end(); ++it) cout<<" "<<*it; cout<<"\nMyVector size is: "<<MyVector.size(); return 0; }
The output of the above code will be:
Before clear() function: MyVector contains: 10 20 30 40 50 MyVector size is: 5 After clear() function: MyVector contains: MyVector size is: 0
❮ C++ <vector> Library