Capturing Variables
The lambda [](int score) { return score > 700; } has its limit written right in its body. But often, the limit is in a variable, such as the score a player wants to beat:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> scores = {640, 1250, 380, 980, 720};
int myScore = 700;
int better = std::count_if(scores.begin(), scores.end(), [](int score) { return score > myScore; });
std::cout << "Better than you: " << better << std::endl;
return 0;
}This program doesn't compile:
main.cpp:8:93: error: variable 'myScore' cannot be implicitly captured in a lambda with no capture-default specifiedA lambda is a function, and as you know from the lesson on functions, a function doesn't see the local variables of main. It sees only its parameters and the variables it creates itself. You can't add a second parameter either, because std::count_if calls the lambda with one element. That's what the square brackets are for. A variable whose name you write between them is captured: the lambda gets its own copy of the variable when it's created, and can use it in its body:
int better = std::count_if(scores.begin(), scores.end(), [myScore](int score) { return score > myScore; });Now the program prints Better than you: 3. The compiler even suggests this fix: below the error, you find the note capture 'myScore' by value.
A lambda can capture several variables, separated by commas: [minScore, maxScore]. It's the same with any algorithm that takes a lambda. Whenever a lambda needs a value from main, capture the variable that holds it, rather than writing the number into the lambda: then the lambda keeps working when the value changes.
Instructions
- 1
With one hit, the hero defeats every monster whose health is at most
heroAttack. Count those monsters withstd::count_ifand a lambda that capturesheroAttack, and print the result asOne hit: 2. Keep the line withheroAttackas it is: the exercise also runs your program with other values. - 2
A monster is a real challenge when the hero can't defeat it with one hit, but it has less health than the hero: its health is greater than
heroAttackand less thanheroHealth. Count such monsters with a lambda that captures both variables, and print the result asChallenges: 2. Keep the line withheroHealthas it is too.