开发者

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?


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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜