如何检查事物是否在向量中 [英] How do I check if a thing is in a vector

查看:44
本文介绍了如何检查事物是否在向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查事物是否在向量中?

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");

我猜我需要把它放在一个循环中,然后做 if "-i" in x 其中 x 是 iter var.但是我想有一个方便的方法可用,或者我混淆了语法,并且有类似的方法可以做到这一点.

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.

推荐答案

虽然您可以构建一个循环,但更简单的方法是使用 any 向量迭代器上的方法.

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

any 接受一个返回 true 或 false 的闭包.依次为每个项目调用闭包,直到找到返回 true 的项目为止.请注意,迭代器返回对值的引用(因此是 |&i| 中的 &).

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");
}

由于 any 对迭代器进行操作,因此它可以与任何类型的容器一起使用.迭代器上有大量类似的方法可用,例如allfind等.请参阅迭代器.

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.

这篇关于如何检查事物是否在向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆