Logo

Programming-Idioms

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

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.

for k, x in pairs(mymap) do
  print(k, x)
end

The order is arbitrary. If you need a consistent order use an array and ipairs(array) instead.
#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...