Iterating over a map in C++

Level 3121 keystrokes

A range-based for loop over a map gives one key-value pair at a time, with the key in first and the value in second. A map is ordered by key, so it prints a:1 b:2.

C++ code

// Initializes the map with two {key, value} pairs
1map<string, int> m = {{"a", 1}, {"b", 2}};
// p is a reference to each pair<const string, int>, in key order
2for (auto& p : m) {
// first is the key and second is the value: a:1 b:2
3 cout << p.first << ":" << p.second << " ";
4}
// Ends the line after the loop
5cout << endl;

Output

a:1 b:2 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 11
  • "× 8
  • ,× 4
  • {× 4
  • }× 4
  • ;× 3
  • :× 2
  • .× 2
  • (× 1
  • )× 1

More C++ examples at level 3

← C++ typing practice