if-init & Structured Bindings
Completed
Read n lines name score into a map (keeping the highest score per name). Then for each of q queries use if (auto it = m.find(name); it != m.end()) to print the score or missing. Finally print every entry with structured bindings.
Input
n, n lines, q, q names.
Output
q lines, then the entries.
Example
Input
4 ann 50 bob 70 ann 90 cy 10 2 ann zed
Output
90 missing ann=90 bob=70 cy=10
Editor
C++
Hints
insert returns a pair: an iterator and whether a new element was added.
Solution explanation
The if-init statement keeps it scoped to the if/else where it's used.
Show solution
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n, q;
cin >> n;
map<string, int> best;
for (int i = 0; i < n; i++) {
string name;
int score;
cin >> name >> score;
if (auto [it, inserted] = best.insert({name, score}); !inserted) {
it->second = max(it->second, score);
}
}
cin >> q;
for (int i = 0; i < q; i++) {
string name;
cin >> name;
if (auto it = best.find(name); it != best.end()) cout << it->second << "\n";
else cout << "missing\n";
}
for (const auto &[name, score] : best) cout << name << "=" << score << "\n";
return 0;
}