Sorting with a lambda in C++

Level 3128 keystrokes

The third argument of sort is a comparison that returns true when a should come before b. Returning a > b sorts in descending order: 5 4 3 1 1.

C++ code

1vector<int> v = {3, 1, 4, 1, 5};
// The lambda says a comes first when a > b, so larger numbers move to the front
2sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
// A one-line loop body needs no braces: prints 5 4 3 1 1
3for (int n : v) cout << n << " ";

Output

5 4 3 1 1 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ,× 7
  • (× 5
  • )× 5
  • <× 5
  • ;× 4
  • .× 2
  • "× 2
  • {× 2
  • }× 2
  • >× 2

More C++ examples at level 3

← C++ typing practice