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.