Referring to article Gotw 54 by HerbSutter, he explains about
-
The Right Way To “Shrink-To-Fit” a
vector or deque and -
The Right Way to Completely Clear a vector or
deque
Can we just use
container.resize()
andcontainer.clear()for the above task
or am I missing something?
There are two different things that a vector holds:
sizeVscapacity. If you justresizethe vector, there is no guarantee that the capacity(how much memory is reserved) must change.resizeis an operation concerned with how much are you using, not how much the vector capacity is.So for example.
In the end, capacity should not changed on every operation, because that would bring a lot of memory allocation/deallocation overhead. He is saying that if you need to “deallocate” the memory reserved by vector, do that.