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.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
To remove duplicates using for-loop , first you create a new empty list. Then, you iterate over the elements in the list containing duplicates and append only the first occurrence of each element in the new list.
The best way to remove items from a list while iterating over it is to use RemoveAll() .
It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With