Remove an element while iterationg over it [duplicate]

三世轮回 提交于 2020-07-08 11:53:09

问题


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.


回答1:


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
})

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.

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.



来源:https://stackoverflow.com/questions/46033562/remove-an-element-while-iterationg-over-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!