根据某些条件从 Vec 中删除元素 [英] Removing elements from a Vec based on some condition
问题描述
我的代码如下所示:
struct Bar {
i: i32,
}
struct Foo {
v: Vec<Bar>,
}
impl Foo {
fn foo(&mut self) {
self.v.drain(self.v.iter().filter(|b| b.i < 10));
}
}
注意Bar
是不允许被复制或克隆的.
Note that Bar
is not allowed to be copied or cloned.
我想删除所有不满足该条件的Bar
.最初我以为我可以迭代它们并调用 remove
但我不允许有两个可变借用或一个可变借用,如果有一个完全有意义的不可变借用.
I want to delete all Bar
s that don't satisfy that condition. Initially I thought I could just iterate over them and call remove
but I am not allowed to have two mutable borrows or one mutable borrow if there is an immutable borrow which makes total sense.
我想最简单的方法就是clone
、filter
和collect
,但我不能克隆或复制.
I guess the easiest thing would be to just clone
, filter
and collect
, but I am not allowed to clone or copy.
我该怎么做?
推荐答案
如果你查看 Vec
的接口,你不会发现基于谓词擦除某些元素的方法.相反,您会发现 retain
根据谓词保留元素.
If you look at the interface of Vec
, you will not find a method that erases some elements based on a predicate. Instead you will find retain
which keeps the elements based on a predicate.
当然,两者都是对称的,只是如果您通过remove"或erase"过滤方法名称(它的描述中确实包含remove"),则更难找到retain
.
Of course, both are symmetric, it's just that retain
is harder to find if you filter method names by "remove" or "erase" (it does contain "remove" in its description).
提供的示例不言自明:
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);
这篇关于根据某些条件从 Vec 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!