【问题标题】:How to combine two vectors containing std::unique_ptr?如何组合两个包含 std::unique_ptr 的向量?
【发布时间】:2014-12-06 16:54:32
【问题描述】:

如果我有两个包含 std::unique_ptr 的向量,有没有办法将向量 b 添加到向量 a 的末尾,从而删除向量 b?

例如:

std::unique_ptr<std::vector<int>> a(&someintvector);

std::unique_ptr<std::vector<int>> b(&someotherintvector);

如何将向量 b 移动到向量 a 的末尾?

【问题讨论】:

  • 也许this 可以帮助您,但我不确定unique_ptr 在您的代码中的作用。

标签: c++ pointers c++11 vector stl


【解决方案1】:

你将b的内容移动到a

std::move(std::begin(*b), std::end(*b), std::back_inserter(*a));

【讨论】:

  • 如果向量也包含一个类,这是否有效?因为我收到以下错误:没有重载函数“std::begin”的实例与参数列表参数类型匹配:(std::unique_ptr<:vector std::allocator>>, std::default_delete<:vector std::allocator>>>>)
【解决方案2】:

将元素移动到a的另一种方式:

a->insert(a->end(), std::make_move_iterator(b->begin()), std::make_move_iterator(b->end()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 2019-04-07
    • 2021-09-25
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多