的C ++功能。我希望以下通用代码适用于任何收集类型。如果输入集合类型是
Vec
,我希望输出收集类型也是Vec
。
fn clone_if<'a, List, ItemType, BinaryPredicate>(list: List, binary_predicate: BinaryPredicate) -> List
where
List: Clone + IntoIterator<Item = &'a ItemType> + Copy,
ItemType: 'a,
BinaryPredicate: Fn(&ItemType) -> bool
{
let mut res = list.clone();
for item in res.into_iter() {
if !binary_predicate(&item) {
// res.remove();
}
}
res
}
fn main() {
let first_list = vec![1, 2, 3, 4, 5, 6];
let second_list = clone_if(&first_list, |item| {
(item & 1) == 0
});
assert_eq!(vec![2, 4, 6], *second_list);
}
当前功能'
clone_if
与您想要实现的目标不兼容。因此,我将其稍微重写以匹配您真正想要的东西。
fn clone_if<List, ItemType, BinaryPredicate>(list: &List, binary_predicate: BinaryPredicate) -> List
where
for<'a> &'a List: IntoIterator<Item = &'a ItemType>,
List: FromIterator<ItemType>,
ItemType: Clone,
BinaryPredicate: Fn(&ItemType) -> bool,
{
list.into_iter()
.filter(|val| binary_predicate(*val))
.cloned()
.collect()
}
fn main() {
let first_list = vec![1, 2, 3, 4, 5, 6];
let second_list = clone_if(&first_list, |item| (item & 1) == 0);
assert_eq!(vec![2, 4, 6], *second_list);
}
list: &List
main
for<'a> &'a List: IntoIterator<Item = &'a ItemType>
-您希望
list
参考在迭代时产生对其元素的引用,这与兼容。这样可以防止不必要的复制。
&Vec
-需要用
List: FromIterator<ItemType>
。
collect()
-您想在输出列表中创建输入项目的克隆由于不必要,因此将所有其他
ItemType: Clone
Clone
删除。then算法本身:
Copy
-从输入列表创建一个
.into_iter()
Iterator<Item = &ItemType>
-进行过滤。尚未制作副本。需要关闭和解雇的原因是因为.filter(|val| binary_predicate(*val))
对迭代的项目进行了参考,在这种情况下,这将是filter
&&ItemType
&&ItemType
&ItemType
的需求。
binary_predicate
.cloned()
。请注意,这是完成的。
Iterator<Item = &ItemType>
使用Iterator<Item = ItemType>
将filter()
转换为.collect()
。