rustiterator

Check if all elements in vector fall within specified range


I have x_min and x_max, both i16 and x_coordinates, which is a Vec<i16>. Now, I want to check whether every x_coordinate lies between x_min and x_max.

I came up with the following solution, which does indeed work, I think.

!x_coordinates.iter().map(|x| (x_min..=x_max).contains(&x)).collect::<Vec<bool>>().contains(&false)

But this does O(n) passes thrice before giving an answer. Is there a way to short-circuit the Iterator as soon as it finds something that returns a falsey condition?


Solution

  • Thanks to Chayim in the comments, I have now a better solution:

    x_coordinates.iter().all(|x| (x_min..=x_max).contains(&x))