gpt4 book ai didi

c++ - 使用 move_iterator 访问 vector

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:44 25 4
gpt4 key购买 nike

我有一个 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::transform连同 make_move_iterator()可能适合。

关于c++ - 使用 move_iterator 访问 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17053377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com