Lambda Functions and Use Cases in C++
Learn lambda functions in C++, including capture lists, anonymous functions, and practical modern C++ use cases.
Introduced in C++11, lambda functions allow defining short, inline, anonymous functions directly within the code. They make certain operations more expressive, improve readability, and enable functional-style programming. This article explains the structure, logic, and practical use cases of lambda expressions in C++.
1) What Is a Lambda Function?
A lambda function is an anonymous function that is typically used for short-lived operations. It is ideal for simple logic that does not require a fully defined named function.
Basic syntax:
[capture] (parameters) mutable noexcept -> return_type {
// body
};
Simplified common form:
[](int x) { return x * 2; };
2) Simple Lambda Example
auto hello = []() {
cout << "Hello!" << endl;
};
hello();
3) Lambda with Parameters
auto sum = [](int a, int b) {
return a + b;
};
cout << sum(3, 4);
4) Specifying a Return Type
auto divide = [](double a, double b) -> double {
return a / b;
};
5) Capture (Capturing Variables)
Lambdas can access variables from their surrounding scope. This feature is called capture.
Capture by value:
int x = 10;
auto f = [x]() {
cout << x;
};
Capture by reference:
int x = 10;
auto f = [&x]() {
x += 5;
};
Capture all by value:
auto f = [=]() { /* ... */ };
Capture all by reference:
auto f = [&]() { /* ... */ };
6) Using mutable
By default, lambdas cannot modify captured-by-value variables. The mutable keyword allows local modification of the captured values.
int x = 10;
auto f = [x]() mutable {
x += 5; // allowed
return x;
};
7) Using Lambdas with STL Algorithms
One of the most powerful uses of lambdas is within STL algorithms.
Using with sort:
vector<int> v = {40, 10, 30, 20};
sort(v.begin(), v.end(), [](int a, int b) {
return a > b; // descending
});
Using with count_if:
vector<int> numbers = {1, 2, 3, 4, 5, 6};
int count = count_if(numbers.begin(), numbers.end(), [](int x) {
return x % 2 == 0; // even numbers
});
8) Using Lambdas as Callbacks
Lambdas are often used as callback functions, especially in event-driven programming.
void process(int x, function<void(int)> callback) {
callback(x * 2);
}
int main() {
process(5, [](int result) {
cout << "Result: " << result;
});
}
9) Lambdas as Function Objects
A lambda can be passed as an argument, returned from functions, or stored inside containers.
vector<function<int(int)>> ops;
ops.push_back([](int x) { return x + 1; });
ops.push_back([](int x) { return x * 2; });
10) Advantages of Using Lambdas
- Shorter, more readable code
- Defines small logic locally
- Excellent integration with STL algorithms
- Ability to capture variables by value or reference
- Encourages functional programming patterns
11) TL;DR
- Lambda → anonymous inline function
- Capture → access outer variables
- mutable → allows modifying captured-by-value variables
- Perfect for sort, count_if, and other STL algorithms
- Great for callbacks and small helper functions
- Fully compatible with Visual Studio 2022, GCC, and Clang