Vector Capacity, Reallocation & Reserve
🟡 Intermediate
📖 Definition
A vector's .size() is the number of stored elements, while .capacity() is the size of currently allocated heap storage. When size exceeds capacity, the vector allocates a larger buffer and moves elements, invalidating existing iterators.
💡 Code Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(100); // Pre-allocate heap capacity to avoid reallocations
std::cout << "Size: " << v.size() << ", Capacity: " << v.capacity() << "\n";
return 0;
}