如何检查一个元素是否存在于向量中?
let n= vec!["-i","mmmm"];
if "-i" in n {
println!("yes");
} else {
println!("no");
我猜想需要将这个放入循环中,然后执行if "-i" in x
,其中x
是迭代变量。但我希望有一个方便的方法可用,或者我弄错了语法,有一种类似的方法可以实现。
如何检查一个元素是否存在于向量中?
let n= vec!["-i","mmmm"];
if "-i" in n {
println!("yes");
} else {
println!("no");
我猜想需要将这个放入循环中,然后执行if "-i" in x
,其中x
是迭代变量。但我希望有一个方便的方法可用,或者我弄错了语法,有一种类似的方法可以实现。
在 Vec
上有 contains
方法 (https://doc.rust-lang.org/std/vec/struct.Vec.html#method.contains)。
示例:
let n = vec!["-i","mmmm"];
if n.contains(&"-i") {
println!("yes");
} else {
println!("no");
}
这有点限制性,例如,如果x
的类型是&str
,则不允许检查Vec<String>
是否包含x
。在这种情况下,您将需要使用@harmic描述的.iter().any(...)
方法。
O(n)
。我看不出有任何改进的方法。而对于某些数据结构来说,contains
可以实现为O(log n)
。 - ctrl-alt-delor