32

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);

3 Answers 3

35

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.

26

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.

6

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;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.