Learn C++ STL

Lesson 2 of 9 · sort, Comparators and Lambdas: Tell the Algorithm What You Mean

Module 12 · sort, Comparators and Lambdas: Tell the Algorithm What You Mean

Every Sorting Call and Every Way to Write the Rule, With Its Cost

Free with an accountReading

Bob wants his shop's prices from high to low. He sorts them low to high, then prints them backwards with for (int i = n; i >= 0; i--). The first number on his screen is one no customer ever typed: v[n] is one place past the end, and reading it is undefined behaviour. His loop needed i = n - 1. But he needed no backwards loop at all. There is a way to say "high to low" to sort itself, and any other order too.

Checking what this lesson needs for you…

What is inside Every Sorting Call and Every Way to Write the Rule, With Its Cost

  1. sort: the whole range, smallest first
  2. sort with greater<int>(): largest first
  3. Part of a range
  4. A plain array, with begin() and end() too
  5. Why not a list: list::sort() instead
  6. stable_sort: ties keep their order
  7. partial_sort and nth_element, a preview
  8. is_sorted and is_sorted_until
  9. The rule as a named function
  10. The rule as a function object
  11. less, greater, and the < that pairs already have
  12. The lambda, piece by piece
  13. A lambda written in place
  14. Captures: by value [t] and by reference [&t]
  15. [=], [&], counting the questions, and mutable
  16. The three rules every comparator keepsIntermediate
  17. Every cost in one table