Junior — Middle
How does the std::vector container behave if you try to add an element when its current size reaches the capacity limit?
sobes.tech AI
Answer from AI
When adding an element to a std::vector using push_back or emplace_back, and the current size equals capacity (meaning there is no free reserved space), the following occurs:
- A new block of memory is allocated with increased capacity (usually 1.5 to 2 times the current).
- Existing elements are copied or moved to the new memory area.
- The old memory block is freed.
- The new element is added to the vector.
This means that the add operation in such cases can be costly in terms of time due to memory reallocation and copying of elements. Therefore, if the approximate size is known in advance, it is recommended to use reserve to allocate the necessary capacity.
Example:
std::vector<int> v;
v.reserve(10); // reserve space for 10 elements
for (int i = 0; i < 10; ++i) {
v.push_back(i); // no reallocation will occur
}
v.push_back(11); // now capacity will be increased, reallocation occurs