Applied Intermediate

12  Iterators

Iterator chains replace most hand-written loops. Build a value by chaining adaptors and finishing with a consumer like sum or collect.

Step 3 / 3

In argmax, return the index of the largest element -- enumerate plus max_by_key, no loop.

Hints
  • .enumerate() turns items into (index, item) pairs.
  • max_by_key picks the pair by its value; a final .map(|(i, _)| i) keeps just the index.
12_iterators.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
fn argmax(v: &[i32]) -> Option<usize> {
    v.iter().enumerate().max_by_key(|&(_, val)| val).map(|(i, _)| i)
}