Search code examples
c++vectorresizecapacity

Amortizing in std::vector::resize and std::vector::push_back


We know that the reallocation mechanism takes care of allocating more memory that we actually need when calling std::vector::push_back(). Usually the capacity grows with the multiplier 2x or with a golden ratio number ~1.618...

Assume, we add elements as follows:

std::vector<int> v;
for(unsigned i = 0; i < 100000; ++i)
{
    v.resize(v.size() + 1);
}

Is it guaranteed that the capacity of the vector is "doubled" if the reallocation takes place? In other words: would the "+1 resize" allocate the memory the same way as it is done for push_back.

Or it is a pure implementation-depended thing?


Solution

  • Is it guaranteed that the capacity of the vector is "doubled" if the reallocation takes place?

    No. The complexity of memory reallocation is amortized constant. Whether the capacity of the object is doubled when needed or increased by another factor is implementation dependent.

    would the "+1 resize" allocate the memory the same way as it is done for push_back

    Yes.

    std::vector::resize(size_type sz) appends sz - size() value-initialized elements to the sequence when sz is greater than size(). That is equivalent to:

     insert(end(), sz-size(), <value initialized object>);
    

    std::vector::insert, std::vector::emplace, and std::vector::push_back have the same complexity for memory allocation - amortized constant.