Wednesday, December 27, 2017

C++11: std::vector::shrink_to_fit()

C++11 added the vector function shrink_to_fit() to suggest to the system to reduce the capacity to size. Here is an example:

#include <iostream>
#include <vector>

int main()
{
  std::vector myVector;

  std::cout << myVector.capacity() << " "; // 15

  myVector.resize(1000);
  std::cout << myVector.capacity() << " "; // 1007

  myVector.clear();
  myVector.shrink_to_fit();
  std::cout << myVector.capacity() << " "; // 15

  std::cout << std::endl;
  return 0;
}
// Output: 0 1000 0
Reference: http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit

No comments:

Post a Comment