An unnamed function object capable of capturing variables in scope
[(capture list)] (int x, int y) -> int {return x*y;}
[] : 아무것도 캡처하지 않음
[&x]: x만 Capture by reference
[x] : x만 Capture by value
[&] : 모든 외부 변수를 Capture by reference
[=] : 모든 외부 변수를 Capture by value (스코프 내의 모든 변수를 Capture by value, 멤버함수에서 람다가 호출된다면 this 포인터도 전달됨)
[x,y] : x,y 를 Capture by value
[&x,y] : x는 Capture by reference , y는 Capture by value
[&x, &y] : x,y 를 Capture by reference
[&, y] : y 를 제외한 모든 값을 Capture by reference
[=, &x] : x 를 제외한 모든 값을 Capture by value
#include <iostream>
int main() {
int a = 5;
int b = 10;
auto lambda = [a, &b]() {
std::cout << "a: " << a << ", b: " << b << '\n';
a++;
b++;
}
lambda();
// a: 5, b: 11
std::cout << "a: " << a << ", b: " << b << '\n';
// a: 5, b: 11
return 0;
람다 표현식에서 Capture list는 statement에서 사용할 외부 변수를 지정하는 방법을 정의함.
Capture list 없이 람다 표현식을 작성하면 람다 statement에서 어떤 외부 변수도 사용할 수 없음.
1. 값에 의한 캡처 Capture by Value
변수를 복사하여 람다 표현식 내부에 저장
2. 참조에 의한 캡처 Capture by Reference
변수를 참조로 캡처하여 람다 표현식 내부에서 사용
3. 모든 변수를 값에 의해 캡처 Capture all by Value
모든 외부 변수를 복사하여 람다 표현식 내부에 저장
4. 모든 외부 변수를 참조에 의해 캡처 Capture all by Reference
모든 외부 변수를 참조로 캡처하여 람다 표현식 내부에서 사용
#include <iostream>
int main() {
int x = 5;
auto valueLambda = [x]() {std::cout << "value: " << x << std::endl; };
valueLambda();
// value: 5
x = 6;
auto referenceLambda = [&x]() {std::cout << "reference: " << x << std::endl; };
referenceLambda();
// reference: 6
int y = 7;
auto allValueLambda = [=]() {std::cout << "All value: " << x << ", " << y << std::endl; };
allValueLambda();
// All value: 6, 7
auto allReferenceLambda = [&]() {std::cout << "All reference: " << x << ", " << y << std::endl; };
allReferenceLambda();
// All value: 6, 7
return 0;
}
컴파일러가 생성하는 런타임 객체
람다 표현식에 대한 런타임 결과는 오브젝트 생성. 생성된 오브젝트를 Closure.
Closure와 Lambda와의 관계는 Class와 object 사이의 관계와 동일
Any object for which the function call operator is defined
#include <iostream>
#include <functional>
using namespace std;
int evaluate(function<int(int, int)> f, int x, int y) {
return f(x, y);
}
int main() {
int a;
cout << "Enter an integer: ";
cin >> a;
cout << evaluate([a](int x, int y) {
if (x == a)
x = 0;
else y++;
return x + y;
}, 2, 3);
}
// 입력값: 5
// 출력값: 6
_
#include <iostream>
#include <functional>
using namespace std;
function<int(int)> make_adder() {
int loc_val = 2;
return [loc_val](int x) {return x + loc_val; };
}
int main() {
auto f = make_adder();
cout << f(10) << '\n';
cout << f(2) << '\n';
}
// 12
// 4
Applies the given function object f to the result of dereferencing every iterator in the range [first, last), in order.
std::for_each(std::begin(seq), std::end(seq), [](int x) {std::cout << '\n';});
Copies all element in the range _[first, last)_, in order.
std::copy(std::begin(seq) + 1, std::end(seq) - 1, std::begin(seq2));
std::transform(std::begin(name), std::end(name), std::begin(name), std::toupper);