CS253: Software Development with C++

Fall 2018

Lambda Functions

See this page as a slide show

CS253 Lambda Functions

Lambda

λ

This is the Greek letter lambda.

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

Functions

A function

Here’s a boring ordinary function:

bool odd(int n) { return n & 01; }

int main() {
    cout << odd(42) << ' ' << odd(43) << '\n';
}
0 1

Boolean values are displayed as 0 and 1 by default, unless you use cout << boolalpha.

Pointer to a function

bool odd(int n) { return n & 01; }

int main() {
    bool (*p)(int) = odd;
    cout << (*p)(42) << ' ' << p(43) << '\n';
}
0 1

auto is your friend

bool odd(int n) { return n & 01; }

int main() {
    auto p = odd;
    cout << (*p)(42) << ' ' << p(43) << '\n';
}
0 1

auto sure made that declaration easier!

There must be a better way.

λ-expressions

auto p = [](int n) -> bool { return n & 01; };
cout << p(42) << ' ' << p(43) << '\n';
0 1

λ-expressions

Let’s omit that return-type declaration:

auto p = [](int n) { return n & 01; };
cout << p(42) << ' ' << p(43) << '\n';
0 1

Use

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-11-04T15:43

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