Logo

Programming-Idioms

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

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.

import Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
mapM_ print $ sortBy (comparing snd) $ Map.toList mymap

Map.toList gives a list of all (key,value) pairs. Sorts on the values (second item of the pairs) and prints.

$ is apply operator and serves here only to save parentheses.
import Data.Map as Map
import Data.List (sortOn)
mapM_ print . sortOn snd $ Map.toList mymap

Using Map.toList to convert the map to a list of (key, value) pairs, then sort the list based on the second element of the pair with sortOn snd.
for_each(begin(mymap), end(mymap),
    [&s](const auto& kv) { s.insert(kv.second); });

Using a std::multiset<>

New implementation...