Could std :: vector be = 'd for another std :: vector?

Say I have the following:

std::vector<int> myints;

and then I have a function that returns int vector:

std::vector<int> GiveNumbers()
{
  std::vector<int> numbers;
for(int i = 0; i < 50; ++i)
{
  numbers.push_back(i);
}

return numbers;
}

could i do the following:

myints = GiveNumbers();

would it be safe to make myints have numbers from 0 to 49 in it and nothing more? Understand what could be in the past? If not, what is the way to do this?

thank

+5
source share
4 answers

Yes. It is safe. You will copy the results from your function GiveNumbers()to myints. This is not the most efficient way to do this, but it is safe and correct. For small vectors, the differences in efficiency will not be so large.

+7
source

, , , .

+1

, , return numbers in GiveNumbers() .

operator=,

+1

, , .

, .

void setNumbers(vector<int> &nums)
{
   nums.resize(50);
   for(int i = 0; i < 50; ++i)
   {
      nums[i] = i;
   }
}

, , .

, , , :

  • ( )
  • Saving speed (only repeating N times to set the vector in one pass, instead of making one pass to set the temporary vector and the second pass to copy them to the original)
+1
source

All Articles