Skip to content
Exercise · Algorithms and Complexity · lesson 8 of 9

Exercise: sort by key

Write a function void sort_by_age(std::vector<Person>& people) that orders people by age, youngest first. People of the same age must stay in the order they had before the call. The file already defines the Person struct, a group of named fields: p.name is the name and p.age is the age.

  • {{"a", 30}, {"b", 25}, {"c", 40}} → {{"b", 25}, {"a", 30}, {"c", 40}}
  • {{"a", 30}, {"b", 20}, {"c", 30}, {"d", 20}} → {{"b", 20}, {"d", 20}, {"a", 30}, {"c", 30}}

Constraints: the vector may be empty, and different people may have the same age.

sort_by_age.cpp — cpp
cpp · 11 lines
Ctrl+Enter run · Esc leave editor