CS253

CS253: Software Development with C++

Spring 2017

Lambda Functions

See this page as a slide show

Lambda Functions

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) << '\n';
    cout << 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) << '\n';
    cout << p(8.6) << '\n';
}
5.1
4.3

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

Modified: 2017-04-13T11:32

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building