Logo

Programming-Idioms

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

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.

mymap 
|> Map.to_list 
|> Enum.sort(fn ({_k1, val1}, {_k2, val2}) -> val1 <= val2 end)
|> Enum.each(fn ({k, v}) -> IO.puts("#{k}: #{v}") end)

We need to convert our map to a list to sort it. When converted, the list is a set of two element tuples which we can sort based on the last value. Finally we just want to iterate over those sorted tuples.
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });

Using a std::multiset<>

New implementation...