capypad
0 day streak
cpp / intermediate
Snippet

Lambda Expressions and Capturing

Lambdas are anonymous functions that can be defined inline. The capture clause '[]' allows the lambda to access variables from the surrounding scope, either by value or by reference.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
int threshold = 10;
auto isAbove = [threshold](int val) {
return val > threshold;
};
std::cout << std::boolalpha << isAbove(15) << std::endl;
return 0;
}
Breakdown
1
[threshold](int val)
Captures the 'threshold' variable by value and defines one integer parameter.
2
auto isAbove =
Stores the lambda in a variable using the 'auto' keyword, as lambdas have unique compiler-generated types.