在 Rust 中,是否有一种内置函数可以同时或者分别实现在向量中查找和删除元素的功能?
例如:
例如:
for f in factors {
if f in list {
list.remove(f);
}
}
目前,Rust文档仍然有些令人困惑,所以虽然我的搜索没有找到任何内容,但我觉得其他人可能已经找到了。
这个例子可以写成:
let mut list = (0..10).collect::<Vec<u32>>();
list.retain(|element| element % 2 == 0);
assert_eq!(&list[..], &[0, 2, 4, 6, 8]);
相关文档可以在这里找到:https://doc.rust-lang.org/std/vec/struct.Vec.html
您可以始终使用 into_iter()
将 Vec 解构为迭代器,filter(..)
函数用于元素过滤,然后 collect()
函数将其收集到新的 Vec 中:
list.into_iter().filter(|e| !factors.contains(e)).collect();
list.retain(|e| !factors.contains(e))
list
的长度,F是factors
的长度。对于较小的L和/或F,这样做没问题。否则最好先将factors转换为HashSet。let mut v = vec![1, 2, 3];
// iterate through the vector and return the position for the
// first element == 2. If something is found bind it to the name
// index
if let Some(index) = v.iter().position(|&i| i == 2) {
v.remove(index); // remove the element at the position index (2)
}
println!("{:?}", v); // prints [1, 3]