Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   how to reallocate a STL vector (http://www.go4expert.com/forums/reallocate-stl-vector-t14179/)

aortizb 25Sep2008 07:06

how to reallocate a STL vector
 
Hello,

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?

4) any other suggestion

Thanks in advance.

Alejandro

aortizb 26Sep2008 00:23

Re: how to reallocate a STL vector
 
I complete my problem here.

My problem is something like this:

num = 10;
for (i = 0; i < num-1; i++)
{
size = (i +1) * n; // where n is a random number between 1 and 10
vector<double> vec(size, 0.0);
for (j = 0 ; j < size-1; j++)
{
vec[j] = (j + 1) * (i + n);
}

// 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:

double* vec;
num = 10;
for (i = 0; i < num-1; i++)
{
size = (i +1) * n; // where n is a random number between 1 and 10

vec = new double[size]

for (j = 0 ; j < size-1; j++)
{
vec[j] = (j + 1) * (i + n);
}

// now I do something with "vec". After this I don't need it anymore, so
// I delete it.

delete [] vec;

}

oogabooga 26Sep2008 22:21

Re: how to reallocate a STL vector
 
I would just allocate a vector that is the biggest you will need and use that,
only freeing it at the end. If you can't do that for some reason, then use resize.


All times are GMT +5.5. The time now is 20:47.