Clear on vector | Sololearn: Learn to code for FREE!


Clear on vector

Refer below code: Once I clear vector, values are wiped off. Does this mean that allocated memory is also released? If so, why capacity is also 4 yet after clear ? Is there a way to make it zero again ?

7/24/2021 3:47:38 PM

Ketan Lalcheta

2 Answers

New Answer


After clear the capacity is not changed which means that the allocated memory is not released. To make it zero again you can try using the shrink_to_fit() member function after you call clear()


Agree with Hape, Also, as I understand it, there is overhead in resizing the internal buffer for bigger size (cmiiw). So perhaps that is the consideration why `capacity` does not follow `size` after `clear()` was invoked. In anticipation of possible buffer resizing necessity in future, it might be better to still reserve the `capacity`, so there would be less resizing work needed (relatively more efficient).