std::vector and std::string reallocation strategy

前端 未结 4 1422
南方客
南方客 2021-01-17 23:03

What is the reallocation strategy used for std::string and std::vector in GCC\'s implementations?

I\'m interested in the specific strategy employed: When I append it

4条回答
  •  灰色年华
    2021-01-17 23:59

    Both vector and string guarantee that the complexity of push_back is "amortized constant", meaning that the time it takes to call push_back n times divided by n is bounded by a constant as n gets large. The only way to achieve this is for the reallocation to increase the size geometrically, i.e. make the new capacity some fixed multiple of the old size. That way you will only have very "few" reallocations.

    Typical growth factors in implementations are 2 or 1.5, though any number strictly greater than 1 will do.

    This doesn't interact with reserve, though. If you call reserve(size() + 1) before each pushback, you may get a reallocation each time.

提交回复
热议问题