Sort Records
Completed
Read people name age. Sort by age ascending, then name, using sort with a lambda, and print them.
Input
n, then n lines.
Output
n lines.
Example
Input
4 zoe 25 adam 30 bob 25 cy 19
Output
cy 19 bob 25 zoe 25 adam 30
Editor
C++
Hints
The lambda returns true when a should come before b.
Solution explanation
A comparator lambda can encode any multi-level ordering.
Show solution
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Person {
string name;
int age;
};
int main() {
int n;
cin >> n;
vector<Person> people(n);
for (auto &p : people) cin >> p.name >> p.age;
sort(people.begin(), people.end(), [](const Person &a, const Person &b) {
if (a.age != b.age) return a.age < b.age;
return a.name < b.name;
});
for (const auto &p : people) cout << p.name << " " << p.age << "\n";
return 0;
}