Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a thing is in a vector

Tags:

rust

How do I check if a thing is in a vector?

let n= vec!["-i","mmmm"];
if "-i" in n { 
    println!("yes");
} else {
    println!("no");

I'm guessing that I need to put this in a loop and then do if "-i" in x where x is the iter var. But I was hopping there is a handy method available or I've confused the syntax and there is a similar way to do this.

like image 597
9716278 Avatar asked Oct 14 '19 00:10

9716278


People also ask

How do you find something in a vector?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

How do you check if something is a vector in C++?

We can find the index of an element in a vector using the std::find_if() function. This function finds the first element in a range for which the predicate function returns true.

How do you check if an item is in a vector in R?

%in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false.


2 Answers

There is the contains (https://doc.rust-lang.org/std/vec/struct.Vec.html#method.contains) method on Vec.

Example:

let n = vec!["-i","mmmm"];

if n.contains(&"-i") { 
    println!("yes");
} else {
    println!("no");
}

It is somewhat restrictive, for instance it doesn't allow checking if a Vec<String> contains x if x is of type &str. In that case, you will have to use the .iter().any(...) method described by @harmic

like image 186
8176135 Avatar answered Oct 20 '22 18:10

8176135


While you could construct a loop, an easier way would be to use the any method on an iterator for your vector.

any takes a closure that returns true or false. The closure is called for each of the items in turn until it finds one that returns true. Note that the iterator returns references to the values (thus the & in |&i|).

let n= vec!["-i","mmmm"];

if n.iter().any(|&i| i=="-i") {
    println!("Yes");
}

Since any operates on iterators, it can be used with any type of container. There are a large number of similar methods available on iterators, such as all, find, etc. See the standard library documentation for Iterators.

like image 24
harmic Avatar answered Oct 20 '22 17:10

harmic