Possible Duplicate:
how to “return an object” in C++
I am wondering if there is a difference between the three following approaches:
void FillVector_1(vector<int>& v) {
v.push_back(1); // lots of push_backs!
}
vector<int> FillVector_2() {
vector<int> v;
v.push_back(1); // lots of push_backs!
return v;
}
vector<int> FillVector_3() {
int tab[SZ] = { 1, 2, 3, /*...*/ };
return vector<int>(tab, tab + SZ);
}
The biggest difference is that the first way appends to existing contents, whereas the other two fill an empty vector. :)
I think the keyword you are looking for is return value optimization, which should be rather common (with G++ you'll have to turn it off specifically to prevent it from being applied). That is, if the usage is like:
vector<int> vec = fill_vector();
then there might quite easily be no copies made (and the function is just easier to use).
If you are working with an existing vector
vector<int> vec;
while (something)
{
vec = fill_vector();
//do things
}
then using an out parameter would avoid creation of vectors in a loop and copying data around.
The idiomatic C++ approach would be to abstract over the container type by using an output iterator:
template<typename OutputIterator>
void FillContainer(OutputIterator it) {
*it++ = 1;
...
}
Then it can be used with vector as:
std::vector<int> v;
FillContainer(std::back_inserter(v));
The performance (and other advantages, such as being able to fill a non-empty container) are the same as for your option #1. Another good thing is that this can be used to output in a streaming mode, where results are immediately processed and discarded without being stored, if the appropriate kind of iterator is used (e.g. ostream_iterator
).
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