简体   繁体   English

使用move_iterator访问向量

[英]Accessing vector with move_iterator

I have a std:vector where MyClass can not be copied (copy constructor and assignment constructor are delete), but can be moved 我有一个std:vector,无法复制MyClass(将复制构造函数和赋值构造函数删除),但可以将其移动

I would like to access the elements in a for loop, how can I do this: 我想在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)

I found the move_iterator but I can't figure out how to use it properly in a for loop. 我找到了move_iterator,但是我不知道如何在for循环中正确使用它。

Iterate by reference and move: 通过引用进行迭代并移动:

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

It may even be more appropriate to use the std::move - algorithm , from <algorithm> , the one that's like std::copy . 甚至更适合使用<algorithm>std::move 算法 ,它类似于std::copy Alternatively maybe something like std::transform together with make_move_iterator() might suit. 另外,也许像std::transformmake_move_iterator()一起适用。

Something like 就像是

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

would be what I'd normally do. 就是我通常会做的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM