tags:

views:

903

answers:

3

Is there a way to resize a std::vector to lower capacity when I no longer need previously reserved space?

+25  A: 

Effective STL, by Scott Meyers, Item 17: Use the swap trick to trim excess capacity.

vector<Person>(persons).swap(persons);

After that, persons is "shrunk to fit".

This relies on the fact that vector's copy constructor allocates only as much as memory as needed for the elements being copied.

Sébastien RoccaSerra
Suggest a fix to the grammar: 'shrunk', not 'shrinked'
James Hopkin
Nice. Do you maybe know why they didn't implement this as a method, as it looks as a common use case for the container?
bombardier
Once the vector has allocated a buffer, it's hard to delete[] the end of that buffer. And doing so simply guarantees that future insertions are going to require allocating a new buffer and copying averything to it (invalidating iterators).
Max Lybbert
+4  A: 

Create a new, temporary, vector from the existing one then call the swap method on the existing one, passing the temporary one in. Let the temporary (now with the old, oversized, buffer) go out of scope.

Hey presto, your vector has exactly the right size for its contents.

If this sounds like a lot of copying and allocation - bear in mind that this is what vector does every time it has to realloc past its current reserved limit anyway.

[Edit] Yes, I just said the same as Sebastien in more words. Another case of stackoverflow race-condition ;-)

Phil Nash
Well, I upvoted you Phil because your answer is still helpful even if you weren't the first one to post it! :-)
Onorio Catenacci
Heh, thanks Onorio
Phil Nash
A: 

You're looking for an equivalent of QVector::squeeze and I'm afraid it doesn't exist explicitely in the STL. Go for Sébastien's answer if it is correct for your STL implementation.

poulejapon