Junior — Middle
Can you explain how memory redistribution works inside a std::vector container when adding new elements?
sobes.tech AI
Answer from AI
In std::vector, when adding new elements, if the current capacity of the vector is insufficient, memory reallocation occurs:
- A new block of larger size (usually twice the current capacity) is allocated to store the elements.
- Existing elements are copied or moved to the new memory block.
- The old memory block is freed.
This allows the vector to dynamically expand, maintaining elements in a contiguous memory block for efficient access. However, reallocation is an expensive operation, so it is recommended to reserve the necessary capacity in advance using reserve(), if the expected size is known.
Example:
std::vector<int> v;
v.reserve(10); // reserve memory for 10 elements
for (int i = 0; i < 10; ++i) {
v.push_back(i); // no reallocation will occur
}