是否可以在Vec <T>中找到一个元素并将其删除?

Nec*_*hno 11 vector rust

在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


llo*_*giq 6

您始终可以使用 aninto_iter()将 Vec 解构为迭代器,filter(..)将元素解构collect()为新的 Vec:

\n\n
list.into_iter().filter(|e| !factors.contains(e)).collect();\n
Run Code Online (Sandbox Code Playgroud)\n\n

您可能需要指定collect的类型(应该是Vec<T>,其中T元素的类型),除非您将其绑定到正确类型的变量中。

\n\n

编辑:按照AB的建议,你也可以写

\n\n
list.retain(|e| !factors.contains(e))\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,两者都在 O(L \xc3\x97 F) 之内,其中 L 是 的 len list,F 是 的 len factors。对于小 L 和/或 F,这样就可以了。否则,最好先将因子转换为 HashSet。

\n


Pao*_*lla 5

据我所知,没有同时“查找和删除”的方法。向量有:

  • 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]
Run Code Online (Sandbox Code Playgroud)