10

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

0

3 Answers 3

17
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); 
2
  • 2
    Awesomeness. Did not know about make_move_iterator. Nov 15, 2010 at 17:25
  • 1
    VS2010 does support this. Good. Nov 15, 2010 at 17:25
4

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.

1
  • It would, if there was a unique_ptr pre-C++0x ;) But it's a neat trick anyway. Nov 15, 2010 at 18:21
1

Actually, you can use good old std::swap_ranges(...)

http://www.cplusplus.com/reference/algorithm/swap_ranges/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.