C++ : Reduce reserved space with std::vector::reserve

Possible Duplicate:
How to downsize std::vector?

According to cppreference, in std::vector::reserve(size_t n), n is "Minimum amount desired as capacity of allocated storage.". My question is : how to avoid any reallocation knowing only a maximum ?

As an example, let's say that I have a list of integers, but I don't know the size of this list (for example this list come from the reading of a file). But I know that the maximum size of this list is 1000. Let's say that the real size of the list is 800.

Currently, I use a std::reserve(1000), and then a loop of push_back(). Using reserve I prevent any reallocation. But how to free the extra space at the end of the push_backs ? (in the case of the example, how to release the 1000-800=200 extra space ?)

Thank you very much.


你可以使用std::vector::shrink_to_fit()

std::vector<int> v;
v.reserve(1000);
for(int i=0;i<800;++i)
    v.push_back(10);

v.shrink_to_fit();

You essentially need to create a new vector at the correct size and swap the two vectors' contents. Fortunately, in STL that's a one-liner Here's examples: How to downsize std::vector?

链接地址: http://www.djcxy.com/p/91710.html

上一篇: 向量复制/移动分配时底层存储会发生什么?

下一篇: C ++:使用std :: vector :: reserve减少保留空间