#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
size_t capacity = myVector.capacity();
std::cout << "Initial capacity: " << capacity << std::endl;
// Add elements to the vector and monitor reallocation
for (int i = 0; i < 20; ++i) {
myVector.push_back(i);
// Check if the capacity has changed
if (myVector.capacity() != capacity) {
capacity = myVector.capacity();
std::cout << "Reallocation occurred. New capacity: " << capacity << std::endl;
}
}
return 0;
}
/*
Why Reallocation Happens
Dynamic Size Management: Vectors are designed to grow and shrink dynamically.
When you add more elements than the current capacity, the vector needs more memory to store these additional elements.
Efficiency: To avoid frequent reallocations (which are expensive in terms of time),
vectors typically increase their capacity by a larger factor (often doubling the current capacity). This way,
reallocations occur less frequently as the vector grows.
How Reallocation Happens
Insufficient Capacity: When a new element is added using methods like push_back() and the current capacity
is insufficient to hold the new element, the vector needs to allocate more memory.
Allocate New Memory: The vector allocates a new block of memory with larger capacity. The new capacity is typically
greater than the current one to minimize the number of reallocations.
Copy Elements: The existing elements are copied from the old memory block to the new one.
Free Old Memory: The old memory block is deallocated.
Update Internal Pointers: The vector updates its internal pointers to point to the new memory block.
*/
To embed this project on your website, copy the following code and paste it into your website's HTML: