Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector, return vs. parameter [duplicate]

Tags:

c++

stl

vector

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);
}
like image 423
Marc Andreson Avatar asked Sep 13 '10 18:09

Marc Andreson


2 Answers

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.

like image 131
UncleBens Avatar answered Oct 05 '22 16:10

UncleBens


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).

like image 35
Pavel Minaev Avatar answered Oct 05 '22 17:10

Pavel Minaev