Custom Comparator in C++

Level 5286 keystrokes

Sorts a vector of Person structs by age with sort and a lambda comparator, then prints them from youngest to oldest.

C++ code

// Struct with a name and an age
1struct Person {
2 string name;
3 int age;
4};
5
// Initializes three people with brace initialization
6vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Carol", 35}};
7
// The third argument decides the order: should a come before b?
8sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
// Smaller age first: ascending order by age
9 return a.age < b.age;
10});
11
// const auto& reads each element without copying it
12for (const auto& p : people) {
// Prints Bob: 25, Alice: 30, Carol: 35
13 cout << p.name << ": " << p.age << endl;
14}

Output

Bob: 25
Alice: 30
Carol: 35
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 10
  • ,× 8
  • "× 8
  • ;× 7
  • {× 7
  • }× 7
  • .× 6
  • (× 5
  • )× 5
  • &× 3

More C++ examples at level 5

← C++ typing practice