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);
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.
I guess by not initialized, you mean it's default initialized, i.e, an empty vector, then
v.assign(n, 0.0);
and
v.resize(n, 0.0);
both changes the size of the vector to n
and all the elements to 0.0
. Note that for non-empty vectors, they are usually not the same, resize()
only sets the new elements to 0.0
.
Assign means replacing a vector with new properties (size and elements). Resize means holding old data and expanding the new vector with new elements, this in case the new size is greater than the old one, otherwise shrink the size and eliminate the extra.
Run the following code twice. One for assign the second one for resize (just uncomment the first one).
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> vec1;
vec1.assign(7,100);
// vec1.resize(7, 100);
std::cout << "Size: " << vec1.size() << std::endl;
for (unsigned int i(0); i < vec1.size(); ++i)
{
std::cout << vec1[i] << std::endl;
}
vec1.resize(4,5);
// vec1.assign(4,5);
std::cout << "\nSize: " << vec1.size() << std::endl;
for (unsigned int i(0); i < vec1.size(); ++i)
{
std::cout << vec1[i] << std::endl;
}
vec1.resize(10,5);
// vec1.assign(10,5);
std::cout << "\nSize: " << vec1.size() << std::endl;
for (unsigned int i(0); i < vec1.size(); ++i)
{
std::cout << vec1[i] << std::endl;
}
std::cin.get();
return 0;
}