std::make_move_iterator vs. std::move for vector concatenation

Viewed 537

(This is about the std::move from <algorithm>: https://en.cppreference.com/w/cpp/algorithm/move)

AFAIK, there are two common ways to move the content of one vector to the end of another.

First:

std::vector<T> dst, src;
...
dst.insert(dst.end(),
           std::make_move_iterator(src.begin()),
           std::make_move_iterator(src.end()));

Second:

std::vector<T> dst, src;
...
std::move(src.begin(),
          src.end(),
          std::back_inserter(dst));

Are these both idiomatic ways to do concatenation? If so, is there any difference in terms of semantics?

1 Answers

Either should get the job done, but there is a subtle difference. When you use insert, the vector has the chance to allocate memory enough to hold all elements in one allocation. When you use back_inserter, that's the equivalent of multiple push_backs which may do multiple allocations and moves.

Related