remove on condtion in vec rust
To remove an element from a Rust vector based on a condition, you can use the retain
method. This method retains only the elements that satisfy a given condition, effectively removing the elements that do not meet the condition.
Here's an example of how you can remove elements from a vector based on a condition:
fn main() {
let mut vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
vec.retain(|&x| x % 2 == 0); // Remove odd numbers from the vector
println!("{:?}", vec); // Output: [2, 4, 6, 8, 10]
}
In this example, the retain
method is called on the vector vec
. The closure |&x| x % 2 == 0
is passed to retain
, which checks if each element of the vector is divisible by 2 (i.e., even). If an element satisfies the condition, it is retained in the vector. Otherwise, it is removed.
After calling retain
, the vector vec
will only contain the even numbers, resulting in the output [2, 4, 6, 8, 10]
.
I hope this helps! Let me know if you have any further questions.