在迭代时删除一个元素 [英] Remove an element while iterationg over it

查看:36
本文介绍了在迭代时删除一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在迭代时删除元素?这是一个代码示例:

Is there a way to remove an element while iterationg over it? Here is a code example:

for particle in &mut particles {

    let mut delete = false;
    // Do stuff...

    if delete {
        // Remove element from particles vector <-- THIS
    }

}

我认为这种(肮脏的)设计是不可能的.假设我需要迭代以知道我需要删除哪些元素,删除向量中某些元素的常见(优雅?)模式是什么?如果重复,请随时关闭.

I think it's not possible with this (dirty) design. What's the common (elegant?) pattern to remove some elements in a vector assuming I need to iterate in order to know what element I need to remove? Feel free to close if duplicate.

推荐答案

你可能想要使用 Vec::retain().它允许您为每个元素决定是否保留它.所以在你的情况下,它看起来像这样:

You probably want to use Vec::retain(). It allows you to decide for each element whether or not to keep it. So in your case that would look like this:

particles.retain(|particle| {
    let delete = {
        // Do stuff ...
    };
    !delete
})

你必须从闭包中返回一个 bool.如果返回true,则不会删除该元素;如果返回 false,则将其删除.

You have to return a bool from the closure. If you return true, the element is not removed; if you return false, it is removed.

如果您需要以某种方式将一个元素与向量中的所有其他元素进行比较,那么 retain() 就不再足够了.对于这种情况,您可以找到一个很棒的答案 这里.

If you need to somehow compare one element to all other elements in the vector, then retain() is not sufficient anymore. For this case, you can find an awesome answer here.

这篇关于在迭代时删除一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆