PrevNext

(Optional) C++ - Lambda Expressions

Authors: Benjamin Qi, Dong Liu

Defining anonymous function objects.

Edit This Page

Introduction

Anything more beginner-friendly?

This section is not complete.

Any help would be appreciated! Just submit a Pull Request on Github.

Recursive Lambdas

With y_combinator

Resources
open-std
RIP Tutorial

If we add the following from the link above in C++14:

namespace std {
template<class Fun>
class y_combinator_result {
Fun fun_;
public:
template<class T>
explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}
template<class ...Args>

Then we can have code like the following!

int main() {
cout << y_combinator([](auto gcd, int a, int b) -> int {
return b == 0 ? a : gcd(b, a % b);
})(20,30) << "\n"; // outputs 10
}

Looks like ecnerwala uses these a lot.

Another way

Change auto to function<return_type(param)>.

int main() {
function<int(int, int)> gcd = [&](int a, int b) {
return b == 0 ? a : gcd(b, a % b);
};
cout << gcd(20, 30) << '\n'; // outputs 10
}

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext