Alex Rivera | Logout

How to downsize std::vector?

Asked 2008-10-31T11:00:51.627
35

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

Edit
Report

1 Answer

9

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

answered 2008-10-31T11:09:58.317

Your Answer