Map basics in C++

Level 3155 keystrokes

map stores key-value pairs with unique keys. Assigning with [] adds entries; the code reads Alice's value (25), the number of entries (2) and whether "Bob" exists (1).

C++ code

// An empty map from string keys to int values
1map<string, int> ages;
// [] creates the entry if the key is missing, then assigns the value
2ages["Alice"] = 25;
3ages["Bob"] = 30;
// Looks up the value for "Alice": 25
4cout << ages["Alice"] << endl;
// Two entries: prints 2
5cout << ages.size() << endl;
// count returns 1 if the key exists and 0 otherwise, without adding an entry
6cout << ages.count("Bob") << endl;

Output

25
2
1
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.

  • <× 13
  • "× 8
  • ;× 6
  • [× 3
  • ]× 3
  • .× 2
  • (× 2
  • )× 2
  • =× 2
  • ,× 1

More C++ examples at level 3

← C++ typing practice