If you are concerned about freeing allocated memory (and therefore locked for use elsewhere) in a (large) vector , you should
make sure that the region / lifetime of the corresponding vector is limited to the region / time of its direct use, so that its destruction automatically frees up memory.
Otherwise (for some reason) you can
vec.clear();
Note that vector::clear() cancels the allocation of memory in vector (only memory, if any, is dynamically allocated by vector elements). vector::shrink_to_fit() suggests reducing the size of the vector memory to the actual size, but an implementation may prefer to ignore this request.
Finally, the alternative to clear() , followed by shrink_to_fit() , is the swap idiom (which also works before C ++ 11):
vector<Tp>().swap(vec); assert(vec.capacity()==0);
What happens here is that a new empty vector (of the same type) is created and then immediately replaced with vec , so vec becomes empty (with zero size and capacity). Finally, since the new vector is a temporary (unnamed) object, it is destroyed, as a result of which the memory allocation is initially saved using vec .
source share