逐个元素比较 2 个向量或字符串的最佳方法是什么?
What's the best way to compare 2 vectors or strings element by element?
在 Rust 中逐个元素比较 2 个向量或字符串,同时能够对每对元素进行处理的最佳方法是什么?例如,如果您想计算不同元素的数量。这就是我正在使用的:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
if x != y {
diff_count += 1i32;
}
}
这是正确的方法还是有更规范的方法?
要获取匹配元素的数量,我可能会使用 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);
}
如果您想使用 作为单元测试中使用的断言的基础,试试这个:
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 不会进行比较,您可能希望使用容差来比较其他值。你可能想通过告诉索引第一个不匹配的值来让它变得花哨。
在 Rust 中逐个元素比较 2 个向量或字符串,同时能够对每对元素进行处理的最佳方法是什么?例如,如果您想计算不同元素的数量。这就是我正在使用的:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
if x != y {
diff_count += 1i32;
}
}
这是正确的方法还是有更规范的方法?
要获取匹配元素的数量,我可能会使用 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);
}
如果您想使用
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 不会进行比较,您可能希望使用容差来比较其他值。你可能想通过告诉索引第一个不匹配的值来让它变得花哨。