kentwait
kentwait

Reputation: 2071

Check if length of all vectors is the same in Rust

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.

Upvotes: 4

Views: 2911

Answers (2)

Stargateur
Stargateur

Reputation: 26757

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

Upvotes: 3

Mike Cluck
Mike Cluck

Reputation: 32511

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");
    }
}

Upvotes: 7

Related Questions