Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The swap trick, stl

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?

like image 377
Eduard Rostomyan Avatar asked Dec 20 '25 12:12

Eduard Rostomyan


1 Answers

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

like image 174
Eduard Rostomyan Avatar answered Dec 22 '25 01:12

Eduard Rostomyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!