람다식은 익명 함수를 표현하는 문법입니다. 함수 객체(Functor)를 대신해 사용할 수 있으며, 특히 STL 알고리즘과 함께 사용되어 코드의 간결성과 유지보수성을 높여줍니다.
람다식의 기본 구문은 다음과 같습니다.
[capture list](parameters) -> return_type {
// 함수 본문
};
capture list: 외부 변수(지역 변수)를 람다식 내부에서 사용하기 위해 캡처하는 리스트. parameters: 람다 함수의 매개변수. -> return_type: 반환 타입. 생략할 수 있으며, 컴파일러가 자동으로 추론합니다. {}: 함수 본문. #include <iostream>
int main() {
// 간단한 람다식 예시
auto add = [](int a, int b) -> int { return a + b; };
std::cout << add(3, 4) << std::endl; // 출력: 7
// 외부 변수 캡처 예시
int x = 10;
auto func = [&x]() { std::cout << "x: " << x << std::endl; };
func(); // 출력: x: 10
// 매개변수를 사용하지 않는 람다식
auto hello = []() { std::cout << "Hello, Lambda!" << std::endl; };
hello(); // 출력: Hello, Lambda!
return 0;
}
auto add: 두 개의 매개변수를 받아 더하는 람다 함수. 반환 타입 int는 명시적으로 지정했습니다. [&x]를 사용해 변수 x를 참조로 캡처. []()는 매개변수를 받지 않으며, 단순 출력을 수행합니다.람다식에서 외부 변수를 람다 함수 내부로 가져오려면 캡처 리스트를 사용해야 합니다.
[]: 아무 변수도 캡처하지 않습니다. [var]: 특정 변수 var를 값으로 캡처합니다. [&var]: 특정 변수 var를 참조로 캡처합니다. [=]: 모든 변수를 값으로 캡처합니다. [&]: 모든 변수를 참조로 캡처합니다. [var1, &var2]: 특정 변수를 지정해 값 또는 참조로 캡처합니다.#include <iostream>
int main() {
int a = 5;
int b = 10;
// 값으로 캡처 (변경 불가)
auto func1 = [a, &b]() mutable {
a = 100; // 에러: a는 값으로 캡처되어 변경 불가
b = 200; // 유효: b는 참조로 캡처되어 변경 가능
};
// 모든 변수 값으로 캡처, b만 참조로
auto func2 = [=, &b]() mutable {
b = 200; // 유효
};
func1();
std::cout << "a: " << a << ", b: " << b << std::endl; // 출력: a: 5, b: 200
return 0;
}
[a, &b]: a는 값으로, b는 참조로 캡처됩니다. mutable: 람다 내에서 값으로 캡처된 변수를 수정할 수 있도록 허용합니다.mutable:
예제:
int x = 10;
auto func = [x]() mutable {
x = 20;
std::cout << x << std::endl; // 출력: 20
};
func();
std::cout << x << std::endl; // 출력: 10 (외부 변수는 변경되지 않음)
constexpr:
예제:
constexpr auto add = [](int a, int b) { return a + b; };
static_assert(add(3, 4) == 7, "Error");
람다식은 STL 알고리즘에서 조건자로 사용될 때 빛을 발합니다.
std::find_if#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
auto it = std::find_if(v.begin(), v.end(), [](int n) { return n > 3; });
if (it != v.end()) {
std::cout << "찾은 값: " << *it << std::endl; // 출력: 4
}
return 0;
}
std::count_ifint count = std::count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; });
std::cout << "짝수 개수: " << count << std::endl;
std::for_eachstd::for_each(v.begin(), v.end(), [](int& n) { n *= 2; });