在Rust中,是否有一个内置函数用于查找和删除向量的元素,同时和单独的操作?
例如:
for f in factors {
if f in list {
list.remove(f);
}
}
Run Code Online (Sandbox Code Playgroud)
目前,生锈文档仍然有点令人困惑,所以虽然我的搜索没有显示,但我觉得其他人很可能找到它.
A.B*_*.B. 10
该示例可以写为:
let mut list = (0..10).collect::<Vec<u32>>();
list.retain(|element| element % 2 == 0);
assert_eq!(&list[..], &[0, 2, 4, 6, 8]);
Run Code Online (Sandbox Code Playgroud)
相关文档可在此处找到:https://doc.rust-lang.org/std/vec/struct.Vec.html
您始终可以使用 aninto_iter()将 Vec 解构为迭代器,filter(..)将元素解构collect()为新的 Vec:
list.into_iter().filter(|e| !factors.contains(e)).collect();\nRun Code Online (Sandbox Code Playgroud)\n\n您可能需要指定collect的类型(应该是Vec<T>,其中T是元素的类型),除非您将其绑定到正确类型的变量中。
\n\n编辑:按照AB的建议,你也可以写
\n\nlist.retain(|e| !factors.contains(e))\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,两者都在 O(L \xc3\x97 F) 之内,其中 L 是 的 len list,F 是 的 len factors。对于小 L 和/或 F,这样就可以了。否则,最好先将因子转换为 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4719 次 |
| 最近记录: |