Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

like image 242
jmasterx Avatar asked Aug 16 '10 17:08

jmasterx


2 Answers

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.

like image 122
A. Levy Avatar answered Oct 01 '22 00:10

A. Levy


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

like image 39
AnT Avatar answered Oct 01 '22 00:10

AnT