Map container in C++

Level 4157 keystrokes

Stores names and ages as key-value pairs in a map and prints them; a map keeps its keys sorted, so they appear in alphabetical order.

C++ code

// A map from string keys to int values, sorted by key
1map<string, int> ages;
// operator[] inserts the key if it is missing, then assigns the value
2ages["Alice"] = 25;
3ages["Bob"] = 30;
4ages["Carol"] = 28;
5
// Iterate over the entries in key order; each p is a key-value pair
6for (const auto& p : ages) {
// first is the key (name), second is the value (age)
7 cout << p.first << ": " << p.second << endl;
8}

Output

Alice: 25
Bob: 30
Carol: 28
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.

  • <× 9
  • "× 8
  • ;× 5
  • [× 3
  • ]× 3
  • =× 3
  • :× 2
  • .× 2
  • ,× 1
  • (× 1

More C++ examples at level 4

← C++ typing practice