在Vec<T>中查找并删除一个元素是否可能?

17
在 Rust 中,是否有一种内置函数可以同时或者分别实现在向量中查找和删除元素的功能?
例如:
for f in factors {
    if f in list {
        list.remove(f);
    }
}

目前,Rust文档仍然有些令人困惑,所以虽然我的搜索没有找到任何内容,但我觉得其他人可能已经找到了。

3个回答

13

啊,有趣!它转移了重点,这也许是为什么找到它可能会很困难的原因。 - Matthieu M.
太棒了。谢谢你! - NecroTechno

6

您可以始终使用 into_iter() 将 Vec 解构为迭代器,filter(..) 函数用于元素过滤,然后 collect() 函数将其收集到新的 Vec 中:

list.into_iter().filter(|e| !factors.contains(e)).collect();

你可能需要指定集合的类型(应该是Vec<T>,其中T是你元素的类型),除非你将其绑定到正确类型的变量中。
编辑:按照A.B.的建议,你也可以写成:
list.retain(|e| !factors.contains(e))

请注意,两者都在O(L × F)范围内,其中L是list的长度,F是factors的长度。对于较小的L和/或F,这样做没问题。否则最好先将factors转换为HashSet。

5
我所知道的没有同时“查找和移除”的方法。Vec有以下几种方法:
- remove 是一般的删除元素的方法,会将后续所有元素向前移动以填补空隙。 - swap_remove 移除指定元素并用最后一个元素来替换它(避免了所有的移动操作,因此通常更快)。 - pop 移除最后一个元素(非常高效,但如果你想要移除 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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接