mz_ore::vec

Trait VecExt

Source
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§

Source

fn drain_filter_swapping<F>( &mut self, filter: F, ) -> DrainFilterSwapping<'_, T, F>
where F: FnMut(&mut T) -> bool,

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]);
Source

fn is_sorted_by<F>(&self, compare: F) -> bool
where F: FnMut(&T, &T) -> bool,

Returns whether the vector is sorted using the given comparator function.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> VecExt<T> for Vec<T>

Source§

fn drain_filter_swapping<F>( &mut self, filter: F, ) -> DrainFilterSwapping<'_, T, F>
where F: FnMut(&mut T) -> bool,

Source§

fn is_sorted_by<F>(&self, compare: F) -> bool
where F: FnMut(&T, &T) -> bool,

Implementors§