In C++, lambda expressions provide a convenient way to define anonymous functions (functions without a name) directly in the code. They are particularly useful for short, throwaway functions that you don't need to reuse elsewhere. Lambda expressions enhance code readability and flexibility by allowing you to write inline functions tailored to specific contexts.
Lambda expressions are especially powerful when used with Standard Template Library (STL) algorithms, which often require function objects or callable entities as arguments. Understanding how to use lambda expressions effectively can significantly streamline your C++ programming.
A lambda expression in C++ consists of the following parts:
The basic syntax is:
1[capture](parameters) -> return_type { body }
Example: Basic Lambda
1#include <iostream>23int main() {4auto greet = []() { std::cout << "Hello, World!5"; };6greet();7return 0;8}
Hello, World!
Variables captured by value are copied into the lambda's scope.
Example: Capture by Value
1#include <iostream>23int main() {4int x = 10;5auto func = [x]() { std::cout << "Value of x: " << x << "6"; };7func();8return 0;9}
Value of x: 10
Variables captured by reference are accessible as references, allowing modification.
Example: Capture by Reference
1#include <iostream>23int main() {4int x = 10;5auto func = [&x]() { std::cout << "Value of x before change: " << x << "6";7x = 20;8std::cout << "Value of x after change: " << x << "9"; };10func();11return 0;12}
Value of x before change: 10 Value of x after change: 20
You can capture all variables by value or reference using = and &.
Example: Generalized Capture
1#include <iostream>23int main() {4int x = 10, y = 20;5auto func1 = [=]() { std::cout << "Value of x and y by value: " << x << ", " << y << "6"; };7auto func2 = [&]() { std::cout << "Value of x and y by reference: " << x << ", " << y << "8"; };9func1();10func2();11return 0;12}
Value of x and y by value: 10, 20 Value of x and y by reference: 10, 20
By default, lambda expressions that capture variables by value do not allow modification of those variables. The mutable keyword allows this.
Example: Mutable Lambda
1#include <iostream>23int main() {4int x = 10;5auto func = [x]() mutable { std::cout << "Value of x before change: " << x << "6";7x = 20;8std::cout << "Value of x after change: " << x << "9"; };10func();11return 0;12}
Value of x before change: 10 Value of x after change: 20
C++14 introduced generic lambdas, which can deduce the types of their parameters automatically.
Example: Generic Lambda
1#include <iostream>23int main() {4auto add = [](auto a, auto b) { return a + b; };5std::cout << "Sum of 5 and 3: " << add(5, 3) << "6";7std::cout << "Sum of 2.5 and 1.2: " << add(2.5, 1.2) << "8";9return 0;10}
Sum of 5 and 3: 8 Sum of 2.5 and 1.2: 3.7
Lambda expressions are frequently used with STL algorithms to perform operations on collections.
Example: Using Lambda with std::for_each
1#include <iostream>2#include <vector>3#include <algorithm>45int main() {6std::vector<int> numbers = {1, 2, 3, 4, 5};7std::for_each(numbers.begin(), numbers.end(), [](int& n) { n *= 2; });8for (const auto& num : numbers) {9std::cout << num << " ";10}11return 0;12}
2 4 6 8 10
Let's create a program that sorts a vector of strings by their length using a lambda expression.
Example: Sorting Strings by Length
1#include <iostream>2#include <vector>3#include <algorithm>45int main() {6std::vector<std::string> words = {"apple", "banana", "cherry", "date"};7std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.length() < b.length(); });8for (const auto& word : words) {9std::cout << word << " ";10}11return 0;12}
date apple cherry banana
| Concept | Description |
|---|---|
| Lambda Syntax | [capture](parameters) -> return_type { body } |
| Capture Clauses | By value ([x]), by reference ([&x]), generalized capture ([=], [&]) |
| Mutable Lambdas | Allows modification of captured variables by value |
| Generic Lambdas | Deduces parameter types automatically |
| Use with STL | Enhances flexibility and readability when used with STL algorithms |
Now that you've learned about lambda expressions, the next topic is Arrays (1D and Multidimensional). Arrays are fundamental data structures in C++ that allow you to store multiple elements of the same type in contiguous memory locations. Understanding arrays will help you build more complex data structures and algorithms.
Stay tuned for the next lesson!