fork download
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. int counter = 0;
  6.  
  7. //-----------------------------------------------
  8. //vvv Lambda vvv
  9.  
  10. auto doSomething = [&counter](const std::string &str)
  11. {
  12. ++counter;
  13.  
  14. std::cout << "Called 'doSomething' " << counter << " times. "
  15. << "Calling with with '" << str << "' as a parameter." << std::endl;
  16. };
  17.  
  18. //'doSomething' is a variable that *holds* an instance of the lambda to call later, like a function pointer.
  19.  
  20. //-----------------------------------------------
  21.  
  22. doSomething("Penguin");
  23. doSomething("Aardvark");
  24.  
  25. for(const std::string &element : {"fire", "water", "earth", "wind"})
  26. {
  27. doSomething(element);
  28. }
  29.  
  30. return 0;
  31. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Called 'doSomething' 1 times. Calling with with 'Penguin' as a parameter.
Called 'doSomething' 2 times. Calling with with 'Aardvark' as a parameter.
Called 'doSomething' 3 times. Calling with with 'fire' as a parameter.
Called 'doSomething' 4 times. Calling with with 'water' as a parameter.
Called 'doSomething' 5 times. Calling with with 'earth' as a parameter.
Called 'doSomething' 6 times. Calling with with 'wind' as a parameter.