Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element while iterationg over it [duplicate]

Tags:

rust

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.

like image 250
rap-2-h Avatar asked Sep 04 '17 08:09

rap-2-h


People also ask

How do you remove an element while iterating?

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.

How do you remove duplicates in a for loop?

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.

How do you remove an element from a generic list while iterating over it?

The best way to remove items from a list while iterating over it is to use RemoveAll() .

Can we modify Collection while iterating?

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.


1 Answers

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.

like image 169
Lukas Kalbertodt Avatar answered Sep 21 '22 10:09

Lukas Kalbertodt