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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With