Logo

Programming-Idioms

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

Idiom #13 Iterate over map keys and values

Access each key k with its value x from an associative array mymap, and print them.

Traversing each key and each associated object of mymap
#include <iostream>
for (const auto& [k, x]: mymap) {
	std::cout << "Key: " << k << " Value: " << x << '\n';
}

The [key, value] syntax is a structured binding declaration, since C++17.

'\n' doesn't flush stdout.
#include <iostream>
for (auto entry : mymap) {
  auto k = entry.first;
  auto x = entry.second;
  std::cout << k << ": " << x << "\n";
}
#include <iostream>
for (const auto& kx: mymap) {
	std::cout << "Key: " << kx.first << " Value: " << kx.second << std::endl;
}

std::endl flushes stdout.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;

use Ada.Containers;
for C in My_Map.Iterate loop
   Put_Line ("Key = " & Key (C) & ", Value = " & Element (C));
end loop;

New implementation...