CLEAR()
This method removes all elements from the vector, effectively making it empty. When clear()
is called, the size of the vector is set to 0, but the memory allocated for its capacity is not released, allowing the vector to be reused efficiently without reallocating memory. This makes clear()
particularly useful when you want to reset a vector’s contents while preserving its allocated storage for future use, avoiding the overhead of creating a new vector. It does not destroy the vector object itself; only its elements are removed.
vectorName.clear();
* Removes all elements from the vector
- After calling clear(), vectorName.empty() will return true
- The vector is still valid and can be reused
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Step 1: Initialize a vector of numbers
vector<int> numbers = {10, 20, 30, 40};
// Step 2: Print the original size
cout << "Original size: " << numbers.size() << endl;
// Step 3: Clear the vector
numbers.clear();
// Step 4: Print size after clearing
cout << "Size after clear: " << numbers.size() << endl;
// Step 5: Check if vector is empty
if (numbers.empty()) {
cout << "The vector is now empty." << endl;
}
return 0;
}
OUTPUT:
Original size: 4
Size after clear: 0
The vector is now empty.
Last updated