Sobes.tech
Junior — Middle

Is adding an element to the end of a vector performed with high efficiency and constant time complexity?

sobes.tech AI

Answer from AI

In the standard implementation of std::vector, adding an element to the end (push_back) typically has amortized constant time complexity. This means that most of the time, the operation is performed in O(1), but occasionally, when the vector reaches its current capacity, a reallocation of memory occurs, and elements are copied to a new buffer, which takes O(n) time.

Thus, adding an element to the end of the vector does not guarantee strictly constant time complexity, but it is amortized — yes. This ensures high performance during sequential additions.

Example:

std::vector<int> v;
for (int i = 0; i < 1000; ++i) {
    v.push_back(i); // amortized O(1)
}
Is adding an element to the end of a vector performed… - sobes.tech