To count the number of occurrences of a specific item in a vector in Rust, you can use the iter
method combined with the filter
method and the count
method.
In this example,
vec
with a set of numerical values using the vec![]
macro.item
that holds the value we want to count in the vector.iter
method on the vector vec
to create an iterator over the elements of the vector.filter
method on the iterator to retain only the elements that match item
. The closure |&x| x == &item
is used to compare each element x
with item
.count
method on the filtered iterator to count the number of matching elements.println!
macro.fn main() {
let vec = vec![1, 2, 3, 2, 2, 4, 5, 2];
let item = 2;
let count = vec.iter().filter(|&x| x == &item).count();
println!("{}", count);
}
4
In this example,
char_vec
with a set of string values using the vec![]
macro.str_item
that holds the string we want to count in the vector.iter
method on the vector char_vec
to create an iterator over the elements of the vector.filter
method on the iterator to retain only the elements that match str_item
. The closure |&x| x == &str_item
is used to compare each element x
with str_item
.count
method on the filtered iterator to count the number of matching elements.println!
macro.fn main() {
let char_vec = vec!["apple", "banana", "apple", "cherry", "banana", "apple"];
let str_item = "apple";
let count = char_vec.iter().filter(|&x| x == &str_item).count();
println!("{}", count);
}
3
In this example,
bool_vec
with a set of boolean values using the vec![]
macro.bool_item
that holds the boolean value we want to count in the vector.iter
method on the vector bool_vec
to create an iterator over the elements of the vector.filter
method on the iterator to retain only the elements that match bool_item
. The closure |&x| x == &bool_item
is used to compare each element x
with bool_item
.count
method on the filtered iterator to count the number of matching elements.println!
macro.fn main() {
let bool_vec = vec![true, false, true, true, false, true, false];
let bool_item = true;
let count = bool_vec.iter().filter(|&x| x == &bool_item).count();
println!("{}", count);
}
4
In this tutorial, we learned How to count the Number of Occurrences of Specific Item in the Vector in Rust language with well detailed examples.