Start learning free

LESSON 262 OF 667 · PAIRS, SORTING & BUILT-INS

Custom Sorting in C++

Lesson

TL ; DR:

To sort by your own rule, give sort a lambda. It gets two items and returns true when the first one goes first.


vector<int> nums = {25, 13, 5, 41, 33};

sort(nums.begin(), nums.end(),
     [](int a, int b) {
         if (a % 10 != b % 10) {
             return a % 10 < b % 10;
         }
         return a < b;
     });
// 41 13 33 5 25

vector<int> scores = {70, 95, 82};

sort(scores.begin(), scores.end(), [](int a, int b) { return a > b; });
// 95 82 70


Full lesson:

The sort function puts a vector in order. Give it the vector's begin() and end(). Numbers go from small to large, and text from A to Z.

Sometimes you need another order. The shortest word may have to come first, or the highest score.

Then add a third value, a lambda. A lambda is a small function written right where you need it. It has no name. It starts with []. Then come its parameters and its body.

The lambda gets two items, a and b. It returns true when a must go before b. The sort function calls it again and again, on two items at a time.

  • Shortest first: the body returns a.size() < b.size().
  • High to low: the body returns a > b.

A parameter like const string& a lets the lambda read a string without copying it.

For two rules, check the first rule. Use the second one only on a tie, as the if above does.

Above, the first rule compares the last digits, a % 10 and b % 10. Numbers with the same last digit then go from small to large.

On two strings, < and > compare them from A to Z.

Use < or > in the lambda. Never use <= or >=. Two equal items must give false both ways. Otherwise sort can crash.

The sort function doesn't keep equal items in their old order. Add a second rule when ties matter.

It also changes the vector itself. To keep the original, sort a copy. The line vector<string> copy = words; makes one.


Your task

A pet shop sells toys. Their prices are in prices. Sort prices from high to low.

The shop's pets are in names. Sort names by their last letter, in alphabetical order. Names with the same last letter go from A to Z.

The code already prints both, one item per line.

Expected output:

30
12
8
5
Bella
Luna
Bo
Coco
Max
Rex
STEP 1 OF 4
    Ctrl + Enter to check