Using iterators to compare consecutive elements in vector

Suppose I have a vector vec<u64> and I want to compare consecutive elements by the "greater then" relation >... Can I do this without explicit loops, just using iterators, maps, closures ect?

I can usually write these things but here I struggle, due to edge cases...

One way is to (1) generate two iterators, (2) call skip(1) on line of them, (3) combine them via zip.

But I'm not sure about memory access pattern this generates.

Sure, you can do something like

v.iter().zip(v.iter().skip(1)).map(|(&x, &y)| x.max(y)).collect()

(playground)

Another way is to use the windows() combinator. It'll give you a sliding window of the size you're looking for, my_collection.windows(2).all(|w| w[0] < w[1]).

4 Likes