Logo

Programming-Idioms

  • C#
  • Scala

Idiom #112 Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

import scala.collection.immutable.SortedMap
SortedMap.from(mymap).foreach{ case (k, x) => println(s"$k => $x") }
using System.Collections.Generic;
SortedDictionary<string, string> myMap;
foreach (var item in myMap)
{
  Console.WriteLine($"{item.Key}={item.Value}");
}
	
#include <map>
#include <iostream>
#include <string>
auto print(auto&... args) {
  // c++17 fold expression
  (std::cout << ... << args) << std::endl;
}

auto print_map_contents(auto mymap) {
  // c++17 structured binding
  for (auto [k, x] : mymap) {
    print("mymap[", k, "] = ", x);
  }
}

auto main() -> int {
  // map is ordered map, iteration is ascending by key value
  auto map = std::map<std::string, int> {
    {"first entry", 12},
    {"second entry", 42},
    {"third entry", 3},
  };

  print_map_contents(map);
}

New implementation...