I'm trying to iterate a vector as pairs of chunks (in my case it's an image represented as a contiguous bitmap and I'd like to have access to pixels from two rows at once).
The problem is that I can't do .chunks(w).chunks(2)
, but have to create a temporary vector in between.
Is there a way to do it purely with iterators? (I'm OK if the result is an iterator itself)
playground
let input: Vec<_> = (0..12).collect();
let tmp: Vec<_> = input.chunks(3).collect();
let result: Vec<_> = tmp.chunks(2).collect();
println!("{:?}", result);
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
Oh, I've got it! I can split larger chunks:
input.chunks(2*3).map(|dbl| dbl.split_at(3)).collect();
Yes, or you could do this:
let tmp: Vec<_> = input
.chunks(2 * 3)
.map(|x| x.chunks(3).collect::<Vec<_>>())
.collect();
This outputs exactly the same thing as your example, without the mix of tuples and arrays from your solution:
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With