Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle missing 'emplace_range' in C++0x STL?

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?

like image 454
AshleysBrain Avatar asked Nov 15 '10 17:11

AshleysBrain


2 Answers

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); 
like image 125
ronag Avatar answered Oct 01 '22 23:10

ronag


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.

like image 26
Steve Townsend Avatar answered Oct 02 '22 00:10

Steve Townsend