0

This function computes the mode of a Vec<i32> using a HashMap to keep count of the occurrence of each value. I do not understand why this will not compile unless the key is deferenced twice in this last line:

fn mode(vec: &Vec<i32>) -> i32 {
    let mut counts = HashMap::new();

    for n in vec {
        let count = counts.entry(n).or_insert(0);
        *count += 1;
    }

    **counts.iter().max_by_key(|a| a.1).unwrap().0
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
swaltek
  • 143
  • 5

1 Answers1

2

It has to be dereferenced twice because you've created a double reference.

  1. You are iterating over &Vec<T> which produces &T.
  2. You called HashMap::iter on HashMap<K, V> which produces (&K, &V).
fn mode(vec: &[i32]) -> i32 {
    let mut counts = std::collections::HashMap::new();

    for &n in vec {
        *counts.entry(n).or_insert(0) += 1;
    }

    counts.into_iter().max_by_key(|a| a.1).unwrap().0
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366