I have two containers, let's say they're defined like this:
std::vector<std::unique_ptr<int>> a;
std::vector<std::unique_ptr<int>> b;
Assume both a
and b
are populated. I want to insert the entire container a
to a particular location in b
, using move-semantics so the unique_ptr
s move to b
. Let's assume i
is a valid iterator to somewhere in b
. The following doesn't work:
b.insert(i, a.begin(), a.end()); // error: tries to copy, not move, unique_ptrs
Is there another STL algorithm that can achieve this 'insert-range-by-moving'? I guess I need a sort of emplace_range
, but there isn't one in VS2010's STL. I don't want to write a loop that inserts one by one, since it would end up a nasty O(n^2) due to shifting up the entire contents of the vector every time it inserts. Any other options?
auto a_begin = std::make_move_iterator(a.begin());
auto a_end = std::make_move_iterator(a.end());
b.insert(i, a_begin, a_end);
You insert
the required number of blank elements in the target (in one shot) and then use swap_ranges
. The source elements are going to be useless anyway since this is unique_ptr
.
This would work for pre-C++0x, but the other answer is clearly better for Visual C++ 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With