What is Lambda Function in C++: Simple Explanation and Example
lambda function in C++ is a small, unnamed function defined directly in the code where it is used. It allows you to write quick, inline functions without needing to create a separate named function.How It Works
A lambda function in C++ is like a mini-function you write right where you need it, without giving it a name. Imagine you want to quickly sort a list of numbers but with a special rule. Instead of writing a full function somewhere else, you write this small function directly inside your sorting code.
It works by using a special syntax with square brackets [] to capture variables from the surrounding code, parentheses () for parameters, and curly braces {} for the function body. This makes your code cleaner and easier to read, especially when the function is simple and used only once.
Example
This example shows a lambda function that adds two numbers and prints the result.
#include <iostream> int main() { // Define a lambda that takes two ints and returns their sum auto add = [](int a, int b) { return a + b; }; int result = add(5, 3); std::cout << "Sum is: " << result << std::endl; return 0; }
When to Use
Use lambda functions when you need a quick, simple function for a short task, especially if you don't want to create a separate named function. They are great for passing small functions as arguments to other functions, like sorting or filtering data.
For example, if you want to sort a list of names by length or filter numbers that are even, lambda functions let you write that logic right where you use it, making your code shorter and easier to understand.
Key Points
- Lambda functions are unnamed, inline functions defined with
[]()syntax. - They can capture variables from the surrounding scope to use inside.
- They make code cleaner by avoiding separate function declarations for small tasks.
- Commonly used with algorithms like
sort,for_each, andtransform.