text: In an environment where peak times are very frequent, retaining a high capacity value makes sense. However, if peak times are relatively rare or short, you may need to "trim" the container, ensuring that its capacity matches its size. Unfortunately, STL containers don't define a trim() member function. However, it's relatively easy to achieve this goal with a few steps.
  Trimming a Container
  When you copy a container, the target's capacity is the same as its size. For example, if you have a vector of integers whose capacity and size are 100 and 1, respectively, a copy of this vector will have the same size as the source, but its capacity will be identical to its size. The following program demonstrates this behavior:
  #include <vector>
  #include <iostream>
  using namespace std;
  int main()
  {
  vector <int> vi;
  vi.reserve(100); //enforce a capacity of 100
  vi.push_back(5); //size is 1
  cout<<"capacity of vi is: "<<vi.capacity()<<endl;
  cout<<"size of vi is: "<<vi.size()<<'\n'<<endl;
  vector <int> vi2=vi;
  cout<<"capacity of vi2 is: "<<vi2.capacity()<<endl;
  cout<<"size of vi2 is: "<<vi2.size()<<endl;
  }
  capacity of vi is: 100
  size of vi is: 1
  capacity of vi2 is: 1
  size of vi2 is: 1
  vi2=vi; //vi2 is a trimmed copy of vi
  vi=vi2; //trims vi
  Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
  Your name/nickname
  Your email
  WebSite
  Subject
  (Maximum characters: 1200). You have 1200 characters left.