C++ bootcamp · Lab 41

Map lookup

mediumMaps12 minLesson: Maps

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n. Then n lines of a name and a score. Then one query name.

Print that person's score, or missing if the name is not in the map.

Input. n, then n lines of name and integer, then one query name.

Output. The score, or the word missing.

Examples

Example 1
Input
3
alice 90
bob 80
carol 70
bob
Output
80
Example 2
Input
2
a 1
b 2
z
Output
missing
Hint
  1. std::map<std::string, int> m; then m[name] = score;
  2. m.find(query) == m.end() means missing.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <map>
#include <string>

int main() {
  int n;
  std::cin >> n;
  std::map<std::string, int> m;
  for (int i = 0; i < n; i++) {
    std::string name;
    int score;
    std::cin >> name >> score;
    m[name] = score;
  }
  std::string query;
  std::cin >> query;
  auto it = m.find(query);
  if (it == m.end()) std::cout << "missing\n";
  else std::cout << it->second << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.