如何处理丢失的“emplace_range”在 C++0x STL 中?
我有两个容器,假设它们的定义如下:
std::vector<std::unique_ptr<int>> a;
std::vector<std::unique_ptr<int>> b;
假设 a
和 b
均已填充。我想使用 move-semantics 将整个容器 a
插入到 b
中的特定位置,以便将 unique_ptr
移动到 b
。我们假设 i 是指向 b 中某处的有效迭代器。以下不起作用:
b.insert(i, a.begin(), a.end()); // error: tries to copy, not move, unique_ptrs
是否有另一种STL算法可以实现这种“通过移动插入范围”?我想我需要一种 emplace_range
,但 VS2010 的 STL 中没有。我不想编写一个逐个插入的循环,因为每次插入时都会向上移动向量的整个内容,最终会导致令人讨厌的 O(n^2) 。还有其他选择吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在目标中
插入
所需数量的空白元素(一次),然后使用swap_ranges
。无论如何,源元素将毫无用处,因为这是unique_ptr
。这个适用于 C++0x 之前的版本,但另一个答案显然更适合 Visual C++ 10。
You
insert
the required number of blank elements in the target (in one shot) and then useswap_ranges
. The source elements are going to be useless anyway since this isunique_ptr
.This would work for pre-C++0x, but the other answer is clearly better for Visual C++ 10.
实际上,您可以使用旧的
std::swap_ranges(...)
http://www.cplusplus.com/reference/algorithm/swap_ranges/
Actually, you can use good old
std::swap_ranges(...)
http://www.cplusplus.com/reference/algorithm/swap_ranges/