Clear on vector | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

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 ?

24th Jul 2021, 3:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Réponses
+ 3
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()
24th Jul 2021, 4:11 PM
Hape - avatar
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).
24th Jul 2021, 4:24 PM