PrevNext

(Optional) C++ - Lambda Expressions

Authors: Benjamin Qi, Dong Liu

Defining anonymous function objects.

Edit This Page

Introduction

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> decltype(auto) operator()(Args &&...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
}

With function

Instead of auto, use 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