【问题标题】:How to handle missing 'emplace_range' in C++0x STL?如何处理 C++0x STL 中缺少的“emplace_range”?
【发布时间】:2010-11-15 17:05:44
【问题描述】:

我有两个容器,假设它们是这样定义的:

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

假设ab 都已填充。我想使用移动语义将整个容器a 插入到b 中的特定位置,以便unique_ptrs 移动到b。假设ib 某处的有效迭代器。以下不起作用:

b.insert(i, a.begin(), a.end()); // error: tries to copy, not move, unique_ptrs

是否有另一种 STL 算法可以实现这种“移动插入范围”?我想我需要一种emplace_range,但在 VS2010 的 STL 中没有。我不想编写一个一个一个插入的循环,因为每次插入时都会向上移动向量的全部内容,因此最终会导致令人讨厌的 O(n^2) 。还有其他选择吗?

【问题讨论】:

    标签: c++ algorithm c++11 move-semantics


    【解决方案1】:
    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); 
    

    【讨论】:

    • 太棒了。不知道make_move_iterator
    • VS2010 确实支持这一点。很好。
    【解决方案2】:

    insert 目标中所需的空白元素数量(一次拍摄),然后使用swap_ranges。无论如何,源元素将毫无用处,因为这是unique_ptr

    适用于 pre-C++0x,但另一个答案显然更适合 Visual C++ 10。

    【讨论】:

    • 如果有 unique_ptr pre-C++0x 的话会这样 ;) 但无论如何,这是一个巧妙的技巧。
    【解决方案3】:

    其实你可以用好老的std::swap_ranges(...)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2018-02-19
      • 2023-03-26
      • 2011-12-28
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多