【问题标题】:How do I move-append one std::vector to another?如何将一个 std::vector 移动附加到另一个?
【发布时间】:2020-08-17 03:26:30
【问题描述】:

假设我有一个std::vector<T> fromstd::vector<T> to,其中T 是不可复制但可移动的类型,to 可能为空,也可能不为空。我希望from 中的所有元素都附加在to 之后。

如果我将 std::vector<T>::insert(const_iterator pos, InputIt first, InputIt last) 重载 (4) 与 pos = to.end() 一起使用,它将尝试复制所有对象。

现在,如果to.empty() 我可以只使用std::move(from),否则我可以先from.reserve(from.size()+to.size()),然后手动to.emplace_back(std::move(from[i]))from 的每个元素,最后是from.clear()

有没有使用std 便利函数或包装器的直接方法?

【问题讨论】:

    标签: c++ c++17 stdvector move-semantics


    【解决方案1】:

    insert 可以与 std::move_iteratorstd::make_move_iterator 辅助函数一起正常工作:

    to.insert(to.end(),std::make_move_iterator(from.begin()),
        std::make_move_iterator(from.end()));
    

    【讨论】:

      【解决方案2】:
      #include<iterator>
      
      std::vector<T> source = {...};
      
      std::vector<T> destination;
      
      std::move(source.begin(), source.end(), std::back_inserter(destination));
      

      【讨论】:

        【解决方案3】:

        您可能需要考虑std::move() 算法——即std::copy() 的移动对应物——而不是std::move() 便利模板函数:

        #include <vector>
        #include <algorithm>
        
        struct OnlyMovable {
           OnlyMovable() = default;
           OnlyMovable(const OnlyMovable&) = delete;
           OnlyMovable(OnlyMovable&&) = default;
        };
        
        auto main() -> int {
           std::vector<OnlyMovable> from(5), to(3);
           std::move(from.begin(), from.end(), std::back_inserter(to)); 
        }
        

        【讨论】:

        • 不知何故我总是忘记&lt;algorithm&gt; std::move。这不涉及完全移动 vector (与其元素相反),但我想我只需要编写一个小包装器。
        猜你喜欢
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        • 2012-06-06
        • 2019-11-07
        • 1970-01-01
        • 2014-12-12
        • 2014-03-04
        相关资源
        最近更新 更多