什么是在Rust中逐个元素地比较2个向量或字符串的最佳方法,同时能够对每对元素进行处理?例如,如果您想要计算不同元素的数量.这就是我正在使用的:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
if x != y {
diff_count += 1i32;
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方式还是有更规范的东西?
She*_*ter 12
为了得到匹配元素的数量,我可能会使用filter和count.
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).filter(|&(a, b)| a == b).count();
println!("{}", matching);
}
Run Code Online (Sandbox Code Playgroud)
如果您想使用@Shepmaster 的答案作为单元测试中使用的断言的基础,请尝试以下操作:
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()
}
Run Code Online (Sandbox Code Playgroud)
当然,在漂浮物上使用时要小心!那些讨厌的 NaN 不会进行比较,您可能需要使用容差来比较其他值。您可能想通过告诉第一个不匹配值的索引来使其变得更奇特。