Condsider we have a std::vector and want to compose it, make its size == capacity.
vector<int> V;
for(int i=0; i<10; ++i)
{
V.push_back(i);
}
std::cout<<V.size()<<" "<<V.capacity()<<endl;
So the output for this is 10 13 (tho its implementation defined, I used VS2017).
How to reallocate vector the way, in which size == capacity?
Here is a trick described in Scott Meyers's Effective STL book.
The trick is called shrink-to-fit, or how the author calls it, The swap trick.
std::vector<int>(V).swap(V);
The idea is very simple, we create a temporary copy of V for which size==capacity and swat it with actual V. That easy and simple.
vector<int> V;
for(int i=0; i<10; ++i)
{
V.push_back(i);
}
std::cout<<V.size()<<" "<<V.capacity()<<endl;
std::vector<int>(V).swap(V);
std::cout<<V.size()<<" "<<V.capacity()<<endl;
Now the output for this code is:
10 13
10 10
Note: This trick applies also for
std::string and std::deque
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With