逐个元素比较两个向量或字符串的最佳方法是什么?

问题描述 投票:3回答:2

在Rust中能够逐个元素地比较两个向量或字符串的最佳方法是什么?例如,如果您想保留不同元素的数量。这就是我正在使用的:

let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
    if x != y {
        diff_count += 1i32;
    }
}

这是正确的方法还是还有更多规范的方法?

rust
2个回答
12
投票
fn main() { let a = "Hello"; let b = "World"; let matching = a.chars().zip(b.chars()).filter(|&(a, b)| a == b).count(); println!("{}", matching); let a = [1,2,3,4,5]; let b = [1,1,3,3,5]; let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count(); println!("{}", matching); }

0
投票
fn do_vecs_match<T : PartialEq>(a : &Vec<T>, b : &Vec<T>) -> bool { let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count(); matching == a.len() && matching == b.len() }

当然,在浮子上使用时要小心!那些讨厌的NaN不会比较,您可能需要使用公差来比较其他值。您可能想通过告诉第一个不匹配值的索引来使其花哨。

© www.soinside.com 2019 - 2024. All rights reserved.