I did not expect it!
I am storing my data (e.g. double) in std::vector<double> vAnts
Before doing so I reserve some memory space using std::vector::reserve(). So far so good.
The data volume is not const. For one run it is 10000, for other it is 1000, etc.
To save memory I wanted to change reserved vector data memory, like this:
volatile int cap = vAnts.capacity();
cap = vAnts.capacity();
The cap value does not change after the second call of reserve(100), it is 1000, and it is the behavior compliant with C++ standard.
Capacity never decreases.
So the question is: how to free reserved memory without destroying the vector?
I am using VS2008 Standard with VC++ Extensions and VS2008 C++ Express under Window XP Home SP3
Last edited by geoyar; 11-30-2009 at 05:16 PM.
I found a solution on www.CodeProject.com in the article "A Presentation of the STL Vector Container" By Nitron.
It suggests to use what amounts to:
If v had size 0, v.capacity returns 0. Feel free to resize after that as you please.
Last edited by geoyar; 11-30-2009 at 05:52 PM.
> how to free reserved memory without destroying the vector?
> It suggests to use what amounts to:
> If v had size 0, v.capacity returns 0. Feel free to resize after that as you please.
Yes this does reset the capacity to a smaller value >= v.size().
A convenient device, however it does not solve your problem if it was one of performance.
std::vector<MyClass>(v) copy constructs a new anonymous vector which is a copy of v. This anonymous vector has a size of v.size() and a capacity >= v.size(). The anonymous vector is then swapped with the original, and finally the anonymous vector is destroyed.
It you want to reset capacity to zero, it is cheaper to just destroy the vector and then construct it once again - at least the copy overhead is avoided.
Last edited by vijayan; 12-02-2009 at 02:12 AM.
reserve doesn't change the capacity of vector if the capacity isn't smaller than the valued passed to reserve. If you want to force the vector to release the occupied memory you have to use the self-swapping idiom which I discuss here in detail: http://www.devx.com/cplus/10%20Minut...lution/29484/0
Tags for this Thread
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center