【问题标题】:How to move items between two vectors in C++如何在 C++ 中的两个向量之间移动项目
【发布时间】:2020-01-09 02:34:13
【问题描述】:

有什么方法可以在不使用 Copy Constructor 的情况下将多个项目从一个 std::vector 移动到另一个?

考虑下面的测试代码

class CTest
{
public:
    int m_value;
    CTest(int n) : m_value(n) {}
    CTest(CTest&& mv) { m_value = mv.m_value; }
    CTest(const CTest& cp) = delete;
};

    std::vector< CTest> vct1;
    vct1.emplace_back(CTest(1));

    //Now move items from vct1 to vct2 to specified position
    std::vector< CTest> vct2;

    //Error: 'CTest &CTest::operator =(const CTest &)': attempting to reference a deleted function
    vct2.insert(vct2.begin(), std::make_move_iterator(vct1.begin()), std::make_move_iterator(vct1.end()));

    //Error: CTest &CTest::operator =(const CTest &)': attempting to reference a deleted function
    std::move(vct1.begin(), vct1.end(), vct2.begin());
    std::move(vct1.begin(), vct1.end(), std::inserter(vct2, vct2.begin()));

唯一可行的方法是使用可能在内部使用 emplace_back 的 back_inserter:

//This works
std::move(vct1.begin(), vct1.end(), std::back_inserter(vct2));

但我还需要在向量的前面或中间插入新项目。

由于矢量重新分配,我不想一个接一个地添加它。还有其他方法吗?还是我应该手动创建一个新向量,将其预分配到目标大小并手动将其逐一移动?

谢谢

【问题讨论】:

  • 添加移动赋值运算符CTest&amp; operator=(CTest&amp;&amp;),然后所有行都可以正常编译。
  • 顺便说一句:std::vector 可能是错误的容器。为了移动周围的东西,你应该考虑使用一些链表类型。
  • @rafix07:谢谢!我非常关注最小的测试用例和报告的错误,我忘了添加它。它现在正在工作;-)
  • @Klaus:这是一个最小的测试用例。在真正的应用程序中,它使用 boost::stable_vector 是因为访问速度非常快,并且永久迭代器具有非常偶然的数据合并
  • @rafix07 请将其添加为答案,以便我选择它。

标签: c++ vector stl move-semantics


【解决方案1】:

正如@rafix07 所指出的,虽然错误是

'CTest &CTest::operator =(const CTest &)': attempting to reference a deleted function

问题在于缺少移动分配运算符

CTest& operator=(CTest&& mv) { m_value = mv.m_value; return *this; }

之后,所有提到的三个方法都有效:

vct2.insert(vct2.begin(), std::make_move_iterator(vct1.begin()), std::make_move_iterator(vct1.end()));
std::move(vct1.begin(), vct1.end(), std::inserter(vct2, vct2.begin()));
std::move(vct1.begin(), vct1.end(), std::back_inserter(vct2));

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2022-08-17
    • 2023-03-15
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多