Having a class members std::vector<double> v
and int n
, what is the difference between using the following on this vector
, which is not initialized:
v.assign(n, 0.0);
or
v.resize(n, 0.0);
C++ Vector Library - resize() FunctionThe C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
vector::resizeResizes the container to contain count elements. If the current size is greater than count , the container is reduced to its first count elements.
vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.
Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.
assign
sets the size to n
and all element values to 0.0, whereas resize
sets the size to n
and only new element values to 0.0.
If v
is empty beforehand, they're the same, but assign
is probably clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With