Check if length of all vectors is the same in Rust

妖精的绣舞 提交于 2020-03-16 05:58:06

问题


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()


来源:https://stackoverflow.com/questions/54774837/check-if-length-of-all-vectors-is-the-same-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!