Lambda expression in C++
Previous: C++
Lambda expressions, also known as lambdas or closures, were added in C++11 and refined further in later versions. They allow you to define an unnamed function object which can be nested inside of other functions.
Although lambdas behave a lot like functions, they are not functions themselves. The type of a lambda expression is a unique, unnamed, non-union class type generated by the compiler. Specifically, they define an overloaded function call operator (operator()), which makes them functors (also called function objects).
They are especially useful for short, one-off function objects, such as those passed to standard algorithms.
Some of the primary benefits of lambda expressions are:
- Function nesting: You can define a function inside another function. This helps avoid namespace pollution.
- Cleaner syntax: Avoids the boilerplate of writing a separate named function or functor class.
- Inline behavior: Useful when passing behavior to STL algorithms like
std::sort,std::for_each, etc. - Capture flexibility: Lambdas can capture local variables by value or
reference. This is the difference between using [=] or [this] or something
else. Essentially these functions don’t have innate access to local variables
unless it is explicilty given
- [=] - pass everything in by value
- [&] - pass everything in by reference
- [a] - can pass in individual variables as well
General Syntax:
[ captureClause ] ( parameters ) -> returnType { statements; }
Example: A lambda to square a number
#include <iostream>
int main()
{
auto square = [](int x) -> int { return x * x; };
std::cout << square(5) << std::endl; // Output: 25 return 0; }
}