Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to return a vector from a function in c++ [duplicate]

Tags:

c++

stl

I have a function that returns an array like this:

vector<string> GetString()
{
   vector<string> s;
   s.push_back("one");
   s.push_back("two");
   s.push_back("three");
   return s;
}

and I'm calling it in this way:

   vector<string> mystrings=GetStrings();

I can implement it as follows too:

void GetString(vector<string> & s)
{
   s.push_back("one");
   s.push_back("two");
   s.push_back("three");
}

and call it in this way:

 vector<string> mystrings;
 GetStrings(mystrings);

Which one is better?

Does version one copy a vector to another? If yes then it is slow if the vector is big.

like image 855
mans Avatar asked Oct 22 '13 13:10

mans


1 Answers

Which one is better?

They do different things. Use the first if you want a vector containing just those strings; use the second if you want to be able to append those strings to an existing vector.

If you want the semantics of the first version, then that's "better" in the sense of being easier to use correctly, and harder to use incorrectly.

Is version one copies a vector to another?

In modern C++, definitely not: returning a local variable and initialising from a temporary are both done by moving, not copying. Even if you're stuck with a pre-C++11 compiler, both copies should be elided. If your compiler doesn't support move semantics or copy elision, then you really should throw it away.

like image 143
Mike Seymour Avatar answered Sep 28 '22 09:09

Mike Seymour