C++ - Best practice for overwriting/reconstructing entire std::vector -
if have std::vector want overwrite (not resize). safest way in terms of memory management? example
int main() { std::vector<float> x (5, 5.0); x = std::vector<float> (6, 6.0); x = std::vector<float> (4, 4.0); }
will create vector of 5 floats of value 5.0. overwrite vector of size 6 values 6.0, overwrite vector of size 4 values 4.0. if i'm performing type of operation indefinite number of times, there risks of corrupting or leaking memory approach? should using clear()
before each overwrite? there more efficient way achieve this?
i'm sure question has been asked many times google isn't pulling exact scenario looking for.
thanks!
std::vector
has specific member functions doing this. allocators , copy/move aside, each of vector
's constructors has corresponding overload of assign
same thing. if want reuse vector
's storage, use it:
std::vector<float> x (5, 5.0); x.assign(6, 6.0); x.assign(4, 4.0);
of course, there no guarantee vector
implementations won't reallocate memory. however, stupid implementation.
Comments
Post a Comment