I would like to 'shrink-to-fit' an std::vector
, to reduce its capacity to its exact size, so that additional memory is freed. The standard trick seems to be the one described here:
template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}
The whole point of shrink-to-fit is to save memory, but doesn't this method first create a deep copy and then swaps the instances? So at some point -- when the copy is constructed -- the memory usage is doubled?
If that is the case, is there a more memory-friendly method of shrink-to-fit? (In my case the vector is really big and I cannot afford to have both the original plus a copy of it in memory at any time.)