Sobes.tech
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:

  1. It checks whether there is enough currently allocated memory to accommodate the new element.
  2. If there is enough space, the element is added to the end of the array.
  3. If there is not enough memory, a new block of memory of larger size (usually 1.5–2 times the current size) is allocated.
  4. Existing elements are copied or moved to the new memory block.
  5. The old memory block is freed.
  6. 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.