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
- sort: the whole range, smallest first
- sort with greater<int>(): largest first
- Part of a range
- A plain array, with begin() and end() too
- Why not a list: list::sort() instead
- stable_sort: ties keep their order
- partial_sort and nth_element, a preview
- is_sorted and is_sorted_until
- The rule as a named function
- The rule as a function object
- less, greater, and the < that pairs already have
- The lambda, piece by piece
- A lambda written in place
- Captures: by value [t] and by reference [&t]
- [=], [&], counting the questions, and mutable
- The three rules every comparator keepsIntermediate
- Every cost in one table