Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL vector: resize() and assign()

Tags:

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); 
like image 907
Oleg Shirokikh Avatar asked Oct 30 '13 03:10

Oleg Shirokikh


People also ask

How do you resize vector vectors?

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.

What does std::vector resize do?

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.

What does vector assign do?

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.

Does resize change capacity?

Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.


1 Answers

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.

like image 173
Potatoswatter Avatar answered Oct 20 '22 04:10

Potatoswatter