How to count elements in a vector with some value without loop?
How can I count the elements in a vector (for example [91, 55, 77, 91]
) with a specific value (for example 91
) without using a loop (as shown below)?
fn count_eq(vec: &Vec<i64>, num: i64) -> i64 {
let mut counter = 0;
for i in vec {
if *i == num {
counter += 1;
}
}
return counter;
}
fn main() {
let v = vec![91, 55, 77, 91];
println!("count 91: {}", count_eq(&v, 91));
}
+3
source to share
1 answer
You can use Iterator::filter
and then count
it:
fn main() {
let v = vec![91, 55, 77, 91];
println!("count 91: {}", v.iter().filter(|&n| *n == 91).count());
}
+9
source to share