34

std::vector以前に予約したスペースが不要になったときに、容量を小さくする方法はありますか?

4

5 に答える 5

60

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.

于 2008-10-31T11:09:37.600 に答える
19

C++11 を使用している場合は、vec.shrink_to_fit(). 少なくとも VS2010 では、これでスワップ トリックが実行されます。

于 2012-03-01T23:32:38.960 に答える
8

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

于 2008-10-31T11:09:58.317 に答える
-1

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.

于 2008-10-31T11:12:37.907 に答える