检查 Rust 中所有向量的长度是否相同 [英] Check if length of all vectors is the same in Rust

查看:42
本文介绍了检查 Rust 中所有向量的长度是否相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定某个值 T 的向量,即.Vec>.

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)

也就是说,如果所有内部向量的长度都相同,则为 true,否则为 false.

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

推荐答案

您可以使用 all 方法来检查迭代器的所有元素是否与谓词匹配.然后只与列表中的第一个元素进行比较.

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

这篇关于检查 Rust 中所有向量的长度是否相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆