【问题标题】:How do I move a unique pointer from one vector to another vector of unique pointers? [closed]如何将唯一指针从一个向量移动到另一个唯一指针向量? [关闭]
【发布时间】:2018-12-25 12:30:28
【问题描述】:

如何在 C++11 中将 unique_ptr 从一个向量移动到 unique_ptrs 的另一个向量?第一个向量中的唯一指针应该被完全删除并添加到第二个向量中。

【问题讨论】:

标签: c++ c++11 vector unique-ptr


【解决方案1】:

好吧,在这种情况下,您有两个概念上独立的操作:

  1. 将元素插入容器。由于您想删除源(这实际上是必要的,因为 std::unique_ptr 是仅移动类型),请使用 std::move 启用移动语义。

    destination.emplace(destination.begin() + m, std::move(source[n])); // or .insert()
    
  2. 从容器中移除掠夺的元素。

    source.erase(source.begin() + n);
    

【讨论】:

    【解决方案2】:

    <algorithm> 包含std::move 的实现。

    std::vector<std::unique_ptr<int>> v1;
    v1.emplace_back(std::make_unique<int>(1));
    std::vector<std::unique_ptr<int>> v2;
    v2.emplace_back(std::make_unique<int>(2));
    
    std::move(v1.begin(), v1.end(), std::back_inserter(v2));
    
    for (auto &&e : v2)
        std::cout << *e;
     // Prints 21
    

    执行后,v1 将包含 1 个具有 nullptr 值的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 2014-04-02
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多