如何处理丢失的“emplace_range”在 C++0x STL 中?

发布于 2024-10-03 02:57:53 字数 602 浏览 0 评论 0原文

我有两个容器,假设它们的定义如下:

std::vector<std::unique_ptr<int>> a;
std::vector<std::unique_ptr<int>> b;

假设 ab 均已填充。我想使用 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_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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

茶底世界 2024-10-10 02:57:53
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); 
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); 
财迷小姐 2024-10-10 02:57:53

您在目标中插入所需数量的空白元素(一次),然后使用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 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.

淡忘如思 2024-10-10 02:57:53

实际上,您可以使用旧的 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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文