vector::clear()
The clear() function is used to remove all the elements of the vector container, thus making it size 0.
Syntax:
vector_name.clear()
Parameters: No parameters are passed.
Result: All the elements of the vector are removed (or destroyed).
Example:
Input: myvector= {1, 2, 3, 4, 5}; myvector.clear(); Output: myvector= {}
C++
// C++ program to demonstrate // Implementation of clear() function #include <iostream> #include <vector> using namespace std; int main() { vector< int > myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); // Vector becomes 1, 2, 3, 4, 5 myvector.clear(); // vector becomes empty // Printing the vector for ( auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0; } |
Output
No Output
Time Complexity: O(N)
Auxiliary Space: O(1)
All elements are destroyed one by one.
Errors and Exceptions
- It has a no exception throw guarantee.
- It shows an error when a parameter is passed.
vector erase() and clear() in C++
Prerequisite: Vector in C++
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.