有没有办法从另一个向量中存在的通用第一个向量中删除条目?
Is there a way to remove entries from a generic first vector that are present in another vector?
调用高阶函数时,我无法理解所有权。如果元素存在于第二个向量中,我应该从第一个向量中删除条目,所以我想出了这个尝试:
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.iter()
.filter(|incoming| !b.contains(incoming))
.collect::<Vec<T>>()
}
我无法更改函数签名。 .collect()
调用不起作用,因为我得到的只是对 a
中元素的引用。虽然这是通用的,但我不知道结果是 copy
-able 还是 clone
-able。我也可能无法取消引用 a
.
中的元素
有没有办法在不从头重写的情况下修复这段代码?
对于这个特定的测试...您可以使用向量而不是依赖引用。签名产生值而不是引用。因此,要通过测试,您只需使用 into_iter
代替:
a.into_iter() // <----------- call into_iter
.filter(|incoming| !b.contains(incoming))
.collect::<Vec<T>>()
这会消耗这些值,然后 returns 再次将它们取出。
销毁传入分配以创建新分配的效率不高。相反,编写更直接符合问题陈述的代码:
fn array_diff<T: PartialEq>(mut a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.retain(|aa| !b.contains(aa));
a
}
在签名中添加 mut
不会更改签名,因为没有人知道您已经添加了它。与以下内容完全相同:
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
let mut a = a;
a.retain(|aa| !b.contains(aa));
a
}
调用高阶函数时,我无法理解所有权。如果元素存在于第二个向量中,我应该从第一个向量中删除条目,所以我想出了这个尝试:
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.iter()
.filter(|incoming| !b.contains(incoming))
.collect::<Vec<T>>()
}
我无法更改函数签名。 .collect()
调用不起作用,因为我得到的只是对 a
中元素的引用。虽然这是通用的,但我不知道结果是 copy
-able 还是 clone
-able。我也可能无法取消引用 a
.
有没有办法在不从头重写的情况下修复这段代码?
对于这个特定的测试...您可以使用向量而不是依赖引用。签名产生值而不是引用。因此,要通过测试,您只需使用 into_iter
代替:
a.into_iter() // <----------- call into_iter
.filter(|incoming| !b.contains(incoming))
.collect::<Vec<T>>()
这会消耗这些值,然后 returns 再次将它们取出。
销毁传入分配以创建新分配的效率不高。相反,编写更直接符合问题陈述的代码:
fn array_diff<T: PartialEq>(mut a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.retain(|aa| !b.contains(aa));
a
}
在签名中添加 mut
不会更改签名,因为没有人知道您已经添加了它。与以下内容完全相同:
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
let mut a = a;
a.retain(|aa| !b.contains(aa));
a
}