pub trait VecExt<T> {
// Required methods
fn drain_filter_swapping<F>(
&mut self,
filter: F,
) -> DrainFilterSwapping<'_, T, F> ⓘ
where F: FnMut(&mut T) -> bool;
fn is_sorted_by<F>(&self, compare: F) -> bool
where F: FnMut(&T, &T) -> bool;
}
Expand description
Extension methods for std::vec::Vec
Required Methods§
sourcefn drain_filter_swapping<F>(
&mut self,
filter: F,
) -> DrainFilterSwapping<'_, T, F> ⓘ
fn drain_filter_swapping<F>( &mut self, filter: F, ) -> DrainFilterSwapping<'_, T, F> ⓘ
Creates an iterator which uses a closure to determine if an element should be removed.
If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the vector and will not be yielded by the iterator.
Using this method and consuming the iterator is equivalent to the following code:
let mut i = 0;
while i < vec.len() {
if some_predicate(&mut vec[i]) {
let val = vec.swap_remove(i);
// your code here
} else {
i += 1;
}
}
But drain_filter_swapping
is easier to use.
Note that drain_filter_swapping
also lets you mutate every element in the filter closure,
regardless of whether you choose to keep or remove it.
§Note
Because the elements are removed using Vec::swap_remove
the order of elements yielded
by the iterator and the order of the remaining elements in the original vector is not
maintained.
§Examples
Splitting an array into evens and odds, reusing the original allocation. Notice how the order is not preserved in either results:
use mz_ore::vec::VecExt;
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
let evens = numbers.drain_filter_swapping(|x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;
assert_eq!(evens, vec![2, 4, 14, 6, 8]);
assert_eq!(odds, vec![1, 15, 3, 13, 5, 11, 9]);