英文:
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:
- search this slice until I find the first
0
; - 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论