【问题标题】:Moving objects from one Boost ptr_container to another将对象从一个 Boost ptr_container 移动到另一个
【发布时间】:2010-03-02 06:28:17
【问题描述】:

我想将某个元素从 a 移动到 b:

boost::ptr_vector<Foo> a, b;
// ...
b.push_back(a.release(a.begin() + i)));

上面的代码没有编译,因为release函数返回boost::ptr_container_detail::static_move_ptr&lt;...&gt;,不适合推回。

我应该如何进行?

编辑:我发现返回的对象有 .get() .release(),它提供了一个原始指针(这也可能导致一些异常安全问题)。但是,我宁愿不依赖未记录的内部功能,因此请随时分享任何更好的解决方案...

【问题讨论】:

    标签: c++ boost ptr-vector


    【解决方案1】:
    boost::ptr_vector<Foo> a, b;
    
    // transfer one element a[i] to the end of b
    b.transfer( b.end(), a.begin() + i, a ); 
    // transfer N elements a[i]..a[i+N] to the end of b
    b.transfer( b.end(), a.begin() + i, a.begin() + i + N, a );
    

    【讨论】:

      【解决方案2】:

      就个人而言,我更喜欢使用 boost::shared_ptr 的 std::vector(即 std::vector> a, b)。

      然后你就可以使用标准的向量函数了。

      【讨论】:

      • 这种方法更简单,可以说更健壮,但如果您需要处理数十万个对象,指针容器的效率要高得多。
      猜你喜欢
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多