Challenge: Scoreboard
Completed
Read n lines of the form name score into a list, then print each one back as name: score, followed by the highest score as Top: name (the first one if several tie).
Input
n, then n lines.
Output
ana: 40 ben: 75 Top: ben
Example
Input
2 ana 40 ben 75
Output
ana: 40 ben: 75 Top: ben
Editor
C++
Hints
Store each name and score in a vector<pair<string, int>> as you read them.
Scan the vector once, printing each entry and remembering the highest score; keep the first name when scores tie.
Solution explanation
Reading everything into a vector first keeps the data so you can print it and scan it again for the top score.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<string, int>> entries;
for (int i = 0; i < n; i++) {
string name;
int score;
cin >> name >> score;
entries.push_back({name, score});
}
string best;
int bestScore = 0;
bool first = true;
for (const auto& e : entries) {
cout << e.first << ": " << e.second << "\n";
if (first || e.second > bestScore) {
best = e.first;
bestScore = e.second;
first = false;
}
}
cout << "Top: " << best << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module