Junior — Middle
What actions are performed when adding a new element to a dynamic array of type vector?
sobes.tech AI
Answer from AI
When adding a new element to a dynamic array of type std::vector, the following actions occur:
- It checks whether there is enough currently allocated memory to accommodate the new element.
- If there is enough space, the element is added to the end of the array.
- If there is not enough memory, a new block of memory of larger size (usually 1.5–2 times the current size) is allocated.
- Existing elements are copied or moved to the new memory block.
- The old memory block is freed.
- The new element is added to the end.
Example:
std::vector<int> v = {1, 2, 3};
v.push_back(4); // adds element 4
This mechanism provides amortized constant time complexity for adding elements, despite possible memory reallocations.