Saturday, September 27, 2008

Little Sugar:Decreasing capacity in C++

When you use vector,string class in C++, the problem that happens is that the capacity just increases and does not decrease, causing the data structure to hog lot of memory.
For example, say in the vector 10 elements were added , then to the same vector 1000000 elements were added. Then 900000 were deleted. This will not cause the capacity to decrease. This might result in the vector still holding on to a lot of memory.

One way to fix this is the sap trick.

vector < int > elements; // the original vector

vector < int > (elements.begin(), elements.end() ).swap(elements)