Lambdas
A comparison function like stronger is often needed in one place only, in one call of std::sort. Yet it has a name and sits above main, far from where it's used. C++ lets you write such a function right where you need it, as a lambda (a lambda function): a function without a name, written inside another statement.
std::sort(monsters.begin(), monsters.end(), [](const Monster& a, const Monster& b) {
return a.attack > b.attack;
});This sorts exactly like std::sort(monsters.begin(), monsters.end(), stronger). Compare the lambda with the function:
bool stronger(const Monster& a, const Monster& b) {
return a.attack > b.attack;
}The parameters and the body are the same. Only the return type and the name, bool stronger, have been replaced with []:
[]starts the lambda. Later in this lesson, you will see what goes between the square brackets. For now, they stay empty.(const Monster& a, const Monster& b)are the parameters, as in any function.{ return a.attack > b.attack; }is the body. You don't write a return type: the compiler works it out fromreturn, and a comparison gives abool.
Look at the end of the call, });. The curly brace ends the body of the lambda, the parenthesis ends the call of std::sort, and the semicolon ends the statement. It's easy to lose one of them, so check them first when the compiler complains about this line.
A short lambda fits on one line. This one sorts numbers from the largest, so you don't need std::reverse:
std::vector<int> scores = {640, 1250, 380, 980, 720};
std::sort(scores.begin(), scores.end(), [](int a, int b) { return a > b; });Now scores holds 1250 980 720 640 380. The parameters have the type of the elements: int for a vector of ints, const Monster& for monsters. For structs and strings, the parameters are const references, so that the sort doesn't copy them every time it compares two of them.
When should you write a function, and when a lambda? A lambda when the comparison is short and you need it in one place. A function with a name when you need the same comparison in several places.
Instructions
- 1
Replace the function
higherAttackwith a lambda: write the comparison right into the call ofstd::sort, and delete the function. The program prints the same list as before. - 2
At the end of
main(beforereturn 0;), printBy health:, sortmonsterswith a lambda so that the monster with the most health comes first, and print them withprintMonsters. The new list starts withTroll: health 80, attack 7and ends withBat: health 8, attack 2. Keep the monsters in the vector as they are. - 3
Below that, sort
scoresfrom the highest with a lambda, as in the example, and print them on one line after the textScores:. The program printsScores: 1250 980 720 640 380. Keep the line with the scores as it is.