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: size
Vs capacity
. If you just resize
the vector, there is no guarantee that the capacity(how much memory is reserved) must change. resize
is an operation concerned with how much are you using, not how much the vector capacity is.
So for example.
size == how much you are using
capacity == how much memory is reserved
vector<int> v(10);
v.resize(5); // size == 5 but capacity (may or may) not be changed
v.clear() // size == 0 but capacity (may or may) not be changed
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.