Sobes.tech
Junior

What operation on a vector in C++ can lead to a significant number of element copies?

sobes.tech AI

Answer from AI

Insertion (or deletion) of an element not at the end of the vector.

When inserting an element at a position before the end of the vector (emplace, insert):

  • Elements to the right of the insertion point are shifted one position "to the right". This requires copying or moving each such element.
  • If the current capacity of the vector is insufficient to accommodate the new element, a reallocation occurs: a new, larger block of memory is allocated, and all existing elements are copied or moved to this new block. Then the old memory block is freed.

When deleting an element from a position before the end of the vector (erase):

  • Elements to the right of the deletion point are shifted one position "to the left". This requires copying or moving each such element.

The greatest number of copies occurs when inserting an element at the beginning of the vector with subsequent reallocation, as all existing elements are copied and then elements are shifted to make space for the inserted element.

Example of inserting at the beginning, which may cause reallocation and subsequent shifts:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec;
    // Assume the current capacity of vec is small
    for (int i = 0; i < 5; ++i) {
        // Insert at the beginning
        vec.insert(vec.begin(), i);
        // Each insertion at the beginning requires shifting all existing elements
        // If reallocation occurs during this process,
        // all elements are first copied to a new buffer,
        // and then shifted in the new buffer.
    }
    return 0;
}