代码之家  ›  专栏  ›  技术社区  ›  AshleysBrain

如何处理C++ 0xSTL中缺少的“EngestixLead”?

  •  10
  • AshleysBrain  · 技术社区  · 14 年前

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

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

    假设两者 a b 已填充。我想插入整个容器 到特定位置 ,使用移动语义 unique_ptr 搬到 . 让我们假设 i 是到中某个位置的有效迭代器 . 以下内容不起作用:

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

    有没有其他STL算法可以通过移动来实现这个“插入范围”?我想我需要一种 emplace_range 但是在VS2010的STL中没有。我不想写一个循环,一个接一个地插入,因为每次插入向量时,它都会移动整个向量的内容,从而导致一个讨厌的o(n^2)。还有其他选择吗?

    3 回复  |  直到 14 年前
        1
  •  17
  •   ronag    14 年前
    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); 
    
        2
  •  4
  •   Steve Townsend    14 年前

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

    这个 为C++0X工作,但是对于Visual C++ 10来说,其他答案显然更好。

        3
  •  1
  •   Viktor Sehr    14 年前

    实际上,你可以用老的 std::swap_ranges(...)

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