Module 4Arrays & VecLesson 3 of 2320 min
Slices, windows & iteration patterns
Subarrays as slices, windows for pairs, enumerate for indices.
Slices are views
rust
let v = vec![10, 20, 30, 40, 50];
let mid = &v[1..4]; // [20,30,40]enumerate
rust
fn main() {
let v = vec![10, 20, 30, 40, 50];
for (i, x) in v.iter().enumerate() {
println!("{i}: {x}");
}
}Output
0: 10
1: 20
2: 30
3: 40
4: 50windows / chunks
rust
for w in v.windows(2) { /* w[0], w[1] adjacent */ }
for c in v.chunks(3) { /* non-overlapping */ }Classic: max subarray of fixed size k (sliding)
Sum first window, then slide by subtracting left and adding right.
Challenge
Return the starting index of the best window as well.
Tips
- windows are O(1) views per step
- Careful with empty/k too large
- enumerate gives indices
Try it live
Slices, windows & iteration patternsRust 2021
Loading editor…
Output
Press Run to compile and execute.