Vector 是否可以在Vec中找到元素<;T>;然后移除它?

Vector 是否可以在Vec中找到元素<;T>;然后移除它?,vector,rust,Vector,Rust,在Rust中,是否有一个内置的函数可以同时或作为单独的动作查找和删除向量的元素 例如: for f in factors { if f in list { list.remove(f); } } 目前,rust文档仍然有点混乱,因此虽然我的搜索结果没有显示任何内容,但我觉得很有可能其他人已经找到了它。您可以始终使用into iter()将Vec分解为迭代器、过滤器(…)元素和收集()进入新的Vec: list.into_iter().filter(|e| !fa

在Rust中,是否有一个内置的函数可以同时或作为单独的动作查找和删除向量的元素

例如:

for f in factors {
    if f in list {
        list.remove(f);
    }
}

目前,rust文档仍然有点混乱,因此虽然我的搜索结果没有显示任何内容,但我觉得很有可能其他人已经找到了它。

您可以始终使用
into iter()
将Vec分解为迭代器、
过滤器(…)
元素和
收集()
进入新的Vec:

list.into_iter().filter(|e| !factors.contains(e)).collect();
您可能需要指定collect的类型(应该是Vec,其中T是元素的类型),除非将其绑定到正确类型的变量中

编辑:按照A.B.的建议,你也可以写

list.retain(|e| !factors.contains(e))
请注意,两者都在O(L×F)范围内,其中L是
列表的len,F是
因子的len。对于小L和/或F,这就可以了。否则,最好先将因子转换为哈希集。

据我所知,没有同步的“查找并删除”方法。 Vec有:

  • 是移除一个元素并移动所有后续元素以填充间隙的常规方法
  • 拆下此元件并更换为最后一个(避免所有换档,因此通常更快)
  • 移除最后一个元素(非常高效,如果您想删除VEC中的元素)可能不是您需要的
你可以这样做:

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]

该示例可以写成:

let mut list = (0..10).collect::<Vec<u32>>();
list.retain(|element| element % 2 == 0);
assert_eq!(&list[..], &[0, 2, 4, 6, 8]);
let mut list=(0..10).collect::();
list.retain(|元素|元素%2==0);
断言!(&列表[…],&[0,2,4,6,8]);

相关文档可以在这里找到:

啊,很有趣,它转移了重点,这可能就是为什么很难找到它。太棒了。谢谢你!