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 ? https://code.sololearn.com/cC5QjbKXtawq/?ref=app
7/24/2021 3:47:38 PMKetan Lalcheta
2 AnswersNew 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).