:克隆通过根据标准选择元素来克隆任何集合

问题描述 投票:0回答:1
STD::copy_if

的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
与您想要实现的目标不兼容。因此,我将其稍微重写以匹配您真正想要的东西。
rust
1个回答
0
投票

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()
        
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.