Embercode
✕
SortingQuick quiz

Comparator contracts

8 questions. Covers Bad comparator bugs.

Questions 1 to 5 of 8

  1. 1. A student sorts people by age, oldest first, with this comparator. What is the problem? ``cpp std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.age >= b.age; }); ``
  2. 2. A comparator returns the result of a subtraction, as in this code. What is wrong with it? ``cpp std::sort(v.begin(), v.end(), [](int a, int b) { return a - b; }); ``
  3. 3. This comparator is meant to sort by length, then by text. What does g++ report? ``cpp return std::tie(a.size(), a) < std::tie(b.size(), b); ``
  4. 4. The comparator b - a > 0.1 is used on the values 0.0, 0.08 and 0.16 to treat close values as tied. Is it a valid comparator for these three values?
  5. 5. The comparator [](int a, int b) { return a > b; } is used to sort in descending order. Is it a valid comparator?

5 question(s) left on this page.