unordered_map Lookups
Completed
Read n lines username id into an unordered_map, then q usernames; print each id or unknown. (Only lookups - never print an unordered map's iteration order.)
Input
n, n lines, q, q names.
Output
q lines.
Example
Input
3 ann 7 bob 12 cy 3 3 bob zed ann
Output
12 unknown 7
Editor
C++
Hints
find returns end() when the key is missing - it doesn't insert like [].
Solution explanation
Hash maps average O(1) lookups, but their iteration order is unspecified.
Show solution
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
int n, q;
cin >> n;
unordered_map<string, int> ids;
for (int i = 0; i < n; i++) {
string name;
int id;
cin >> name >> id;
ids[name] = id;
}
cin >> q;
for (int i = 0; i < q; i++) {
string name;
cin >> name;
auto it = ids.find(name);
if (it == ids.end()) cout << "unknown\n";
else cout << it->second << "\n";
}
return 0;
}