Rust 迭代器迭代,直到第一个不满足条件的元素

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

给定一个

Vec<i32>
,我想创建一个
Vec<i32>
,其中包含所有第一个
i32
,并且谓词返回 true,一旦遇到不满足谓词的第一个元素,就会删除所有元素。简单的过滤器实现为

fn first_predicate<F>(vec: Vec<i32>, f: F) -> Vec<i32>
where
    F: FnMut(&i32) -> bool,
{
    vec.into_iter().filter(f).collect() //return all elements satisfying the predicate, not the first group
}

因为它返回满足谓词的所有元素。

有没有办法一旦遇到不满足谓词的元素就停止迭代?

rust iterator vec
1个回答
0
投票

是的,您可以使用

take_while
代替
filter

© www.soinside.com 2019 - 2024. All rights reserved.