Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 specified

A 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. 1

    With one hit, the hero defeats every monster whose health is at most heroAttack. Count those monsters with std::count_if and a lambda that captures heroAttack, and print the result as One hit: 2. Keep the line with heroAttack as it is: the exercise also runs your program with other values.

  2. 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 heroAttack and less than heroHealth. Count such monsters with a lambda that captures both variables, and print the result as Challenges: 2. Keep the line with heroHealth as it is too.

Back

7/13

  1. 1. Sorting: std::sort
  2. 2. Reversing: std::reverse
  3. 3. A Comparison Function
  4. 4. Lambdas
  5. 5. Quiz: Sort Order
  6. 6. Counting: std::count_if
  7. 7. Capturing Variables
  8. 8. Searching: std::find
  9. 9. Searching with a Lambda: std::find_if
  10. 10. Quiz: Searching
  11. 11. The Largest Element: std::max_element
  12. 12. Yes or No: std::any_of and std::all_of
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.