In Rust, is there an in built function for finding and removing elements of a vector, both simultaneously and as separate actions?
For example:
for f in factors {
if f in list {
list.remove(f);
}
}
Currently, the rust documentation is still a tad confusing, so while my search as shown up nothing, I feel like there is a good chance someone else may have found it.
clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.
To remove all elements from a vector in Rust, use . retain() method to keep all elements the do not match. let mut v = vec![ "A", "warm", "fall", "warm", "day"]; let elem = "warm"; // element to remove v.
The example can be written as:
let mut list = (0..10).collect::<Vec<u32>>();
list.retain(|element| element % 2 == 0);
assert_eq!(&list[..], &[0, 2, 4, 6, 8]);
The relevant documentation can be found here: https://doc.rust-lang.org/std/vec/struct.Vec.html
You could always use an into_iter()
to destructure the Vec into an iterator, filter(..)
that for the element and collect()
into a new Vec:
list.into_iter().filter(|e| !factors.contains(e)).collect();
You may need to specify the type of collect (which should be Vec<T> where T is the type of your element) unless you bind it into a variable of the right type.
Edit: Following A.B.'s advice, you could also write
list.retain(|e| !factors.contains(e))
Note that both would be within O(L × F) where L is the len of list
and F the len of factors
. For small L and/or F, this will be fine. Otherwise it may be better to convert factors into a HashSet first.
There is no simultaneous "find and remove" method, that I know of. Vec has:
you could do something like:
let mut v = vec![1, 2, 3];
// iterate through the vector and return the position for the
// first element == 2. If something is found bind it to the name
// index
if let Some(index) = v.iter().position(|&i| i == 2) {
v.remove(index); // remove the element at the position index (2)
}
println!("{:?}", v); // prints [1, 3]
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