'Partition with two predicate
I am looking for a way to partition a Vec with two predicate :
- One for the first partition point. For example x > 3
- One for the last element of the partition. For example x < 7
And so for example this vector :
[1, 2, 3, 4, 5, 6, 7, 8, 9]
having this slice :
[4, 5, 6]
I think I can use partition_point twice like the example on std. But is there another method (or crate) where I can pass directly two predicate and slice between the first match of the first predicate and the first match of the second predicate ?
Solution 1:[1]
This is pretty trivial to implement yourself. It's just a function that takes a slice and two predicates, and returns a subslice:
fn partition<T, P1, P2>(i: &[T], mut p1: P1, mut p2: P2) -> &[T]
where P1: FnMut(&T) -> bool,
P2: FnMut(&T) -> bool
{
let mut start: usize = 0;
while start < i.len() && !p1(&i[start]) {
start += 1;
}
let mut end = start;
while end < i.len() && p2(&i[end]) {
end += 1;
}
&i[start..end]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cdhowie |
