Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Multiple entries may exist for the same value x.

let mut items: Vec<_> = mymap.iter().collect();
items.sort_by_key(|item| item.1);
for (k, x) in items {
    println!("[{},{}]", k, x);
}
use itertools::Itertools;
for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
	println!("[{},{}]", k, x);
}

Requires the itertools crate
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });

Using a std::multiset<>

New implementation...
< >
programming-idioms.org