How to shrink-to-fit an std::vector in a memory-efficient way?

Posted by dehmann on Stack Overflow See other posts from Stack Overflow or by dehmann
Published on 2010-04-23T01:05:23Z Indexed on 2010/04/23 1:13 UTC
Read the original article Hit count: 311

Filed under:
|
|
|

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.)

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl