I have a vector member and want to reallocate memory. Say I have 10 elements in a vector "vec" and I don't need them any more, so they can be erased or whatever. In the next stage I need memory just for 5 elements. In order to reallocate the vector:

1) Should I call to vec.~vector<T>() and then declare again vector<double> vec(5) ?

2) Should I use vec.resize(5)? In this case what does happen with the other 5 elements that were before? are they still allocated in memory or were they deallocated?

3) Should I use vec.reserve(5)? In this case what does happen with the other 5 elements that were before? are they still allocated in memory or were they deallocated?

// now I do something with "vec". Once I have it done I don't
// need the previously calculated "vec" anymore. I always want to use
// exactly the total capacity, so I would like to deallocate the previously
// calculated "vec" because I am going to declare again the "vec" with
// the new capacity in the next i-loop

}

I pressume that I should do something in order to not cause a failure when the declaration "vector<double> vec(size, 0.0) " for i = 1 comes into the picture.

so, any thought?

aortizb

26Sep2008 01:20

Re: how to reallocate a STL vector

so, what should I do? I was thinking that I can use resize or clear or erase function. But these functions will not free the memory. Maybe I don't need to free them and just work with them, though... But anyway, when I was working with C-arrays I simply did the following which is what I would like to emule with the vector class: