Lambdas Intro

A mechanism to set up anonymous functions (without names). Once we have them set up, we can either give them names and call them, or we can even get them to do things directly.

Declaring and using lambda functions

Lambda function signature: [capture list] (parameters) -> return type {
// Function body
};

auto func = []() { std::cout << "hello world!" << std::endl; };
func();

Call lambda function directly after definitiion


  []() { std::cout << "Hello world" << std::endl; }();

Lambda function that takes parameters


  [](double a, double b) {
    std::cout << "a + b : " << (a + b) << std::endl;
  }(12.1, 5.7);

Lambda function that returns something


  auto result = [](double a, double b) { return (a + b); }(12.1, 5.7);

  std::cout << "result: " << result << std::endl;


  std::cout << "result: " <<
      [](double a, double b) { return (a + b); }(12.1, 5.7) << std::endl;

Specify return type explicitly


  auto result = [](double a, double b) -> double {
    return (a + b); 
  }(12.1, 5.7);