问题
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