Unordered Map in C++

Level 5312 keystrokes

unordered_map stores key-value pairs in a hash table. It assigns with [], checks for a missing key with find() == end(), and loops over all entries; the iteration order is not specified, so it may differ from the output shown.

C++ code

// Hash map from a name to a score
1unordered_map<string, int> scores;
// [] inserts the key if missing, then assigns the value
2scores["Alice"] = 95;
3scores["Bob"] = 87;
4scores["Carol"] = 92;
5
// Prints "Alice: 95"
6cout << "Alice: " << scores["Alice"] << endl;
7
// find returns end() when the key is absent (unlike [], it adds nothing)
8if (scores.find("David") == scores.end()) {
// Prints "David not found"
9 cout << "David not found" << endl;
10}
11
// Structured binding splits each entry into key and value
12for (const auto& [name, score] : scores) {
// Prints all three entries; the order is unspecified and may differ
13 cout << name << ": " << score << endl;
14}

Output

Alice: 95
David not found
Carol: 92
Bob: 87
Alice: 95
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.

  • <× 19
  • "× 16
  • ;× 7
  • [× 5
  • ]× 5
  • =× 5
  • (× 4
  • )× 4
  • :× 3
  • ,× 2

More C++ examples at level 5

← C++ typing practice