Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

(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?

like image 776
Zizheng Tai Avatar asked Jun 20 '26 03:06

Zizheng Tai


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.

like image 79
Ayxan Haqverdili Avatar answered Jun 21 '26 18:06

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!