Presenting the Problem
Containers that remain alive for long periods can degrade performance since they are quick to grow but reluctant to shrink. Take, for instance, a mail server that stores incoming messages in a vector before dispatching them to the clients. At peak time, the vector is filled with thousands of messages, causing its capacity to grow accordingly. After the short peak, the vector contains only a few messages at any given time. However, its
capacity remains high.
| Author's Note: The member function capacity() reports the number of elements that the container can hold without requiring reallocation. size() returns the number of elements currently stored in the container. capacity() - size() is therefore the number of available "free slots" that can be filled with additional elements without reallocation. Notice that these member function count elements, not bytes. |
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;
}
The output is:
capacity of vi is: 100
size of vi is: 1
capacity of vi2 is: 1
size of vi2 is: 1
This behavior is more than a hint: to trim a container
c1, simply copy it to another container
c2 and then copy
c2 to
c1:
vi2=vi; //vi2 is a trimmed copy of vi
vi=vi2; //trims vi