如何使用迭代器搜索并返回切片的范围?

huangapple go评论56阅读模式
英文:

How to search and return a range of a slice using iterators?

问题

let src = &[7, 4, 5, 0, 3, 6, 0, 2, 5];

// Step 1: Search for the first `0`
let index_of_zero = src.iter().position(|&x| x == 0).unwrap_or(src.len());

// Step 2: Return all elements up to the found element
let res = &src[..=index_of_zero];
英文:

Suppose I have the following slice:

let src = &[7, 4, 5, 0, 3, 6, 0, 2, 5];

I need to perform two steps:

  1. search this slice until I find the first 0;
  2. return all elements up to the found element.

For the slice above, the returned value would be:

let res = &[7, 4, 5, 0];

Then the search would start again, at the first element after the found 0, returning:

let res = &[3, 6, 0];

And so on...

How to write this with Rust iterators?

答案1

得分: 2

你可以使用 split_inclusive 来获得你想要的结果的迭代器,例如:

    let src = &[7, 4, 5, 0, 3, 6, 0, 2, 5];

    let mut calc = src.split_inclusive(|n| *n == 0);

    let res1 = &[7, 4, 5, 0];
    let res2 = &[3, 6, 0];

    assert_eq!(calc.next().unwrap(), res1);
    assert_eq!(calc.next().unwrap(), res2);
英文:

You can use split_inclusive to get you an iterator over the results you want, e.g.

    let src = &[7, 4, 5, 0, 3, 6, 0, 2, 5];

    let mut calc = src.split_inclusive(|n| *n == 0);

    let res1 = &[7, 4, 5, 0];
    let res2 = &[3, 6, 0];

    assert_eq!(calc.next().unwrap(), res1);
    assert_eq!(calc.next().unwrap(), res2);

huangapple
  • 本文由 发表于 2023年3月15日 21:06:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定