To check if a vector contains all the items of another vector in Rust, you can use the iter
method combined with the all
method.
In this example,
vec1
with a set of numerical values.vec2
with a different set of numerical values.iter
method on vec2
to get an iterator over the elements of vec2
.all
method on the iterator to check if all elements of vec2
are present in vec1
. The all
method takes a closure that checks if each element of vec2
is contained in vec1
using the contains
method.all
method returns true
if all elements of vec2
are in vec1
; otherwise, it returns false
.println!
macro.fn main() {
let vec1 = vec![1, 2, 3, 4, 5];
let vec2 = vec![2, 3, 4];
let result = vec2.iter().all(|&item| vec1.contains(&item));
println!("{}", result);
}
true
In this example,
main_vec
with a series of character strings.sub_vec
with a subset of character strings.iter
method on sub_vec
to get an iterator over the elements of sub_vec
.all
method on the iterator to check if all elements of sub_vec
are present in main_vec
. The all
method takes a closure that checks if each element of sub_vec
is contained in main_vec
using the contains
method.all
method returns true
if all elements of sub_vec
are in main_vec
; otherwise, it returns false
.println!
macro.fn main() {
let main_vec = vec!["apple", "banana", "cherry", "date", "fig"];
let sub_vec = vec!["banana", "cherry", "date"];
let result = sub_vec.iter().all(|&item| main_vec.contains(&item));
println!("{}", result);
}
true
In this example,
primary_vec
with a list of mixed data types including numbers and strings.secondary_vec
with some elements that are not present in primary_vec
.iter
method on secondary_vec
to get an iterator over the elements of secondary_vec
.all
method on the iterator to check if all elements of secondary_vec
are present in primary_vec
. The all
method takes a closure that checks if each element of secondary_vec
is contained in primary_vec
using the contains
method.secondary_vec
are in primary_vec
, the all
method returns false
.println!
macro.fn main() {
let primary_vec = vec![10, 20, 30, "apple", "banana"];
let secondary_vec = vec![20, "banana", "cherry"];
let result = secondary_vec.iter().all(|&item| primary_vec.contains(&item));
println!("{}", result);
}
false
In this tutorial, we learned How to check if a Vector contains all the items of Another Vector in Rust language with well detailed examples.