开发者

Vector capacity and reserve

Consider the following code snippet:

std::vector<int> v;
v.reserve(100);
v.insert(v.end开发者_如何学Python(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?


If the capacity is 100, then the vector has space allocated for 100 elements. reserve(0) is a no-op, because reserve won't shrink the capacity.

reserve(n) will try to grow the allocation to enough space for at least n elements. There's no guarantee that it will succeed, it won't report failure and it may overallocate.

Don't call reserve unless you've measured your code with and without it and found it makes a significant difference. All other use of reserve is premature optimization.


You are looking for the (in)famous swap trick:

vector<T>().swap(myVector);

See here for backgrounder

How to downsize std::vector?


Just as a reminder, C++0x/11 added the shrink_to_fit convenience function to the STL container, which is already available in VS2010, so you're lucky if you're coding on Windows (with VS). :)


Yes, the vector still holds 100 locations. reserve is only used to increase the size and isn't able to shrink it. A reserve(0); call would have no effect at all. In C++1x I believe there will be a shrink_to_fit call that you're interested in.

In the current standard, you have to use the swap trick to release storage allocated by a vector, but before you do, carefully consider if you really want to do that. If you add elements back to the vector later again you'll just reallocate. Unless you're on an embedded system just let vector manage its own memory.

Swap trick: Use vector<T>().swap(myvector); to release the storage of a vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜