Sobes.tech
Junior — Middle

Explain what the term 'lambda' means in the context of programming and why it is used.

sobes.tech AI

Answer from AI

In programming, a lambda is an anonymous function, meaning a function without a name that can be defined directly at the point of use. Lambdas allow writing more compact and expressive code, especially when working with higher-order functions (for example, passing functions as arguments).

In C++, a lambda looks like this:

auto add = [](int a, int b) { return a + b; };
int result = add(3, 4); // result == 7

Lambdas are useful for concise writing of functions that are used only once, for example, in STL algorithms:

std::vector<int> v = {1, 2, 3, 4};
std::for_each(v.begin(), v.end(), [](int x) { std::cout << x << " "; });

Thus, lambdas enhance the convenience and readability of code.