cpp / beginner
Snippet
Lambda Expressions
Lambda expressions create anonymous functions inline. The syntax [] captures variables, () holds parameters, and {} contains the function body. Lambdas are useful for short operations, especially with algorithms like std::for_each and std::count_if. The capture list [threshold] passes a variable from the outer scope into the lambda.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>#include <vector>#include <algorithm>int main() {std::vector<int> nums = {5, 2, 8, 1, 9};auto print = [](int n) { std::cout << n << " "; };std::cout << "Original: ";std::for_each(nums.begin(), nums.end(), print);std::cout << std::endl;int threshold = 5;auto isLarge = [threshold](int n) { return n > threshold; };int count = std::count_if(nums.begin(), nums.end(), isLarge);std::cout << "Numbers > " << threshold << ": " << count << std::endl;return 0;}
Breakdown
1
auto print = [](int n) { ... };
Creates a lambda that takes an int and prints it
2
std::for_each(nums.begin(), nums.end(), print);
Applies the lambda to each element in the range
3
[threshold]
Captures threshold by value from the surrounding scope
4
std::count_if(..., isLarge)
Counts elements that satisfy the lambda condition