c++performancestlvector

What is the most efficient way to append one std::vector to the end of another?


Let v1 be the target vector, v2 needs to be appended to the back of it.

I'm now doing:

v1.reserve(v1.size() + v2.size()); 
copy(v2.begin(), v2.end(), back_inserter(v1));

Is this the most efficient way? Or can it maybe be done just via copying a chunk of memory? Thanks!


Solution

  • After a lot of arguing (and a reasonable comment from Matthieu M. and villintehaspam), I'll change my suggestion to

    v1.insert( v1.end(), v2.begin(), v2.end() );
    

    I'll keep the former suggestion here:

    v1.reserve( v1.size() + v2.size() ); 
    v1.insert( v1.end(), v2.begin(), v2.end() );
    

    There are some reasons to do it the latter way, although none of them enough strong: