CS253: Software Development with C++

Spring 2018

Lambda Functions

See this page as a slide show

CS253 Lambda Functions

Lambda

λ

This is the Greek letter lambda.

In a C++ context, it refers to an anonymous function.

Functions

A function

Here’s a boring ordinary function:

double half(double d) { return d/2.0; }

int main() {
    cout << half(4.2) << '\n';
}
2.1

Pointer to a function

double half(double d) { return d/2.0; }

int main() {
    double (*p)(double) = half;
    cout << (*p)(10.2) << ' ' << p(8.6) << '\n';
}
5.1 4.3

auto is your friend

double half(double d) { return d/2.0; }

int main() {
    auto p = half;
    cout << (*p)(10.2) << ' ' << p(8.6) << '\n';
}
5.1 4.3

auto sure made that declaration easier!

There must be a better way.

λ-expressions

auto p = [](double d) -> double { return d/2.0; };
cout << p(8.6) << '\n';
4.3

λ-expressions

Let’s omit that return-type declaration:

auto p = [](double d) { return d/2.0; };
cout << p(8.6) << '\n';
4.3

Use

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:54

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building