使用move_iterator访问vector

Accessing vector with move_iterator

本文关键字:访问 vector iterator move 使用      更新时间:2023-10-16

我有一个std:vector,其中MyClass不能被复制(复制构造函数和赋值构造函数被删除),但可以移动

我想访问for循环中的元素,我该怎么做呢:

for(MyClass c : my_vector) {
    //c should be moved out of my_vector
} // after c goes out of scope, it get's destructed (and no copies exist anymore)

我找到了move_iterator,但我不知道如何在for循环中正确使用它

按引用迭代并移动:

for (auto & x : v) { foo(std::move(x)); }

使用std::move -算法可能更合适,从<algorithm>开始,类似于std::copy。或者,std::transformmake_move_iterator()可能适合。

类似

for(MyClass &c : my_vector) {
   do_something_with(std::move(c));
}

是我通常会做的