tags:

views:

111

answers:

4

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

+1  A: 

Yes, it will assign it and it will clear what was in the receiving vector previously.

AndreyT
+1  A: 

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

Tom
Alright perfect, thanks!
Milo
Anonymous coward care to explain the downvote ?
Tom
i voted u back up for a very good comment. Probably it doesnt invoke op= in real life due to optimizations
pm100
+7  A: 

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.

A. Levy
+1 for warning about efficiency.
Brian
It shouldn't be inefficient if your compiler supports RVO.
jamesdlin
RVO should only reduce it from copying twic4e to copying once.
James Curran
+1  A: 

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)
KevenK
It shouldn't be inefficient if your compiler supports RVO, which does that transformation for you.
jamesdlin
Also, your version that takes a reference argument should be careful that it call `std::vector::clear()` first or check that the incoming argument doesn't start with more than 50 elements.
jamesdlin
@jamesdlin: Please note the use of `nums.resize(50);`.
KevenK
Whoops, you're right. It somehow slipped my mind that `resize` can shrink. Duh. Maybe I was thinking about `reserve`.
jamesdlin
@jamesdlin: I highly doubt that RVO will get you all the benefits that this function gives. It will optimize away some temporaries, but this will still be more efficient.
A. Levy