Return multiple max values

Hi again,

Something else that I thought would be interesting, and I can't find much info on (my Rust still needs improvement!) is returning multiple values if there are multiple maxima. For example:

use std::collections::HashMap;

let map: HashMap<Vec<&str>, Vec<(usize, usize)>> = HashMap::new();
// add some
map.insert(["1", "2", "3", "4", "5", "6", "7"], [(5, 4), (3, 3), (1, 1), (6, 5), (2, 2)]);
map.insert(["1", "8"], [(8, 5), (5, 2), (7, 4), (9, 6), (6, 3)]);
map.insert(["1", "8", "2"], [(1, 4), (9, 6), (6, 3)]);

// I want to compare the lengths of the vec of tuples.
let max = map
            .iter()
            .max_by(|a, b| a.1.len().cmp(&b.1.len()))
            .map(|(k, v)| (k, v));

// this will return a random max each time

Is there any way to return all the max entries? Or would I have to sort, get the lengths and then grab the last n elements of the longest length?

Thanks,
M

There's nothing for it in the standard iterator trait. You'll need to write your own loop that finds it. Or you can iterate twice - once to find the maximum, second to get all elements equal to it.

1 Like