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

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:

  • there is no guarantee on to what size will the vector be reallocated — e.g. if the sum size is 1025, it may get reallocated to 2048 — dependant on implementation. There is no such guarantee for reserve either, but for a specific implementation it might be true. If hunting for a bottleneck it might be rasonable to check that.
  • reserve states our intentions clear — optimization may be more efficient in this case (reserve could prepare the cache in some top-notch implementation).
  • also, with reserve we have a C++ Standard guarantee that there will be only a single reallocation, while insert might be implemented inefficiently and do several reallocations (also something to test with a particular implementation).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)