Sobes.tech
Junior — Middle

What is the time complexity of inserting an element into a std::vector container?

sobes.tech AI

Answer from AI

The time complexity of inserting an element into std::vector depends on whether reallocation of memory is necessary:

  • Amortized complexity: inserting at the end on average is O(1). This occurs when the vector has enough allocated memory.
  • In the worst case: when there is not enough allocated memory, reallocation occurs (allocating a new memory block, copying elements), which takes O(n), where n is the current size of the vector.

Thus, inserting into std::vector is usually very fast, but can sometimes be costly due to reallocation.