I am trying to fix some code that uses vectors a lot and there are some loops that look like this:
for (int t=0;t<T;t++){
std::vector<double> vect;
for (int i=0;i<MAX;i++){
double value;
vect.push_back(value);
}
/*....*/
}
I know more or less how to improve this by reusing the same vector for the outer iterations, but while doing this I found that when calling std::vector::clear
"the vector capacity is not guaranteed to change", while I was actually hoping that the capacity would be guaranteed to not change. Maybe I am just misunderstanding what is written on cplusplus.com. However, my question is:
How can I clear a vector without changing its capacity?
Should I call reserve
after clear
to make sure the capacity will be the same?
PS: just to be clear, I want to rewrite above code to
std::vector<double> vect;
vect.reserve(MAX);
for (int t=0;t<T;t++){
for (int i=0;i<MAX;i++){
double value;
vect.push_back(value);
}
/*....*/
vect.clear();
}
ie. I still want to fill it via push_back
and I am worried about the clear()
changing the capacity of the vector.