Check if length of all vectors is the same in Rust

2020-04-08 11:18发布

问题:

Given a vector of vectors of some value T, ie. Vec<Vec<T>>.

What's the idiomatic way to check if the inner vectors have the same length? (without external dependencies)

That is, true if all the inner vectors have the same length, and false otherwise.

回答1:

You can use the all method to check if all elements of an iterator match a predicate. Then just compare against the first element in the list.

fn main() {
    let vec_of_vecs = vec![
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3, 4], // remove this to prove that it works for both cases
    ];
    let all_same_length = vec_of_vecs
        .iter()
        .all(|ref v| v.len() == vec_of_vecs[0].len());

    if all_same_length {
        println!("They're all the same");
    } else {
        println!("They are not the same");
    }
}


回答2:

An other solution more generic and idiomatic in my opinion:

fn all_eq_len<'a, T, E: 'a>(collection: T) -> bool
where
    T: IntoIterator<Item = &'a Vec<E>>,
{
    let mut iter = collection.into_iter();
    if let Some(first) = iter.next() {
        let len = first.len();
        iter.all(|v| v.len() == len)
    } else {
        true
    }
}

And of course using itertools:

use itertools::Itertools;

vec_of_vecs.iter().map(|v| v.len()).all_equal()


标签: rust