Referring to article Gotw 54 by HerbSutter, he explains about

  1. The Right Way To "Shrink-To-Fit" a vector or deque and

  2. The Right Way to Completely Clear a vector or deque

Can we just use container.resize() and container.clear() for the above task or am I missing something?

Was it helpful?


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.


Neither resize() nor clear() work. The .capacity() of a vector is guaranteed to be at least as big as the current size() of the vector, and guaranteed to be at least as big as the reserve()d capacity. Also, this .capacity() doesn't shrink, so it is also at least as big as any previous size() or reserve()ation.

Now, the .capacity() of a vector is merely the memory it has reserved. Often not all of that memory cotains objects. Resizing removes objects, but doesn't recycle the memory. A vector can only recycle its memory buffer when allocating a larger buffer.

The swap trick works by copying all ojects to a smaller, more appropriate memory buffer. Afterwards, the original memory buffer can be recycled. This appears to violate the previous statement that the memory buffer of a vector can only grow. However, with the swap trick, you temporarily have 2 vectors.

The vector has size and capacity. It may hold X elements but have uninitialized memory in store for Y elements more. In a typical implementation erase, resize (when resizing to smaller size) and clear don't affect the capacity: the vector keeps the memory around for itself, should you want to add new items to it at a later time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top