简体   繁体   中英

Can a std::vector be ='d to another std::vector?

Say I have the following:

std::vector<int> myints;

and then I have a function that returns an 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 then do:

myints = GiveNumbers();

would doing this safely make it so that myints has the numbers 0 to 49 in it and nothing else? Would doing this clear what could have been in myints previously? If not whats the proper way to do this?

Thanks

Yes. This is safe. You will be copying the results from your GiveNumbers() function into myints . It may not be the most efficient way to do it, but it is safe and correct. For small vectors, the efficiency differences will not be that great.

是的,它将分配它,它将清除之前接收向量中的内容。

Yes, as a matter of fact, your return numbers in GiveNumbers() is copying the vector onto the stack.

When you use the operator= , you'll get the same contents onto your new vector

As has been mentioned, this is perfectly safe to use, albeit not the most efficient method of doing so.

To save on resources, it may be better to pass your vector in by reference, and modify it directly.

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

As was also mentioned, the efficiency may not make a huge difference for very small vectors, but on larger vectors can actually be substantial.

The savings you get by modifying the original vector directly are in two ways:

  1. Memory savings (Not creating a temporary vector)
  2. Speed savings (Only iterating N times to set the vector in one pass, rather than taking one pass to set the temp vector and a second pass to copy them into the original)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM