std::vector resize downward

前端 未结 4 1908
醉话见心
醉话见心 2020-12-01 10:34

The C++ standard seems to make no statement regarding side-effects on capacity by either resize(n), with n < size(), or clear().

4条回答
  •  春和景丽
    2020-12-01 10:53

    Calling resize() with a smaller size has no effect on the capacity of a vector. It will not free memory.

    The standard idiom for freeing memory from a vector is to swap() it with an empty temporary vector: std::vector().swap(vec);. If you want to resize downwards you'd need to copy from your original vector into a new local temporary vector and then swap the resulting vector with your original.

    Updated: C++11 added a member function shrink_to_fit() for this purpose, it's a non-binding request to reduce capacity() to size().

提交回复
热议问题