lambda function c++

Dongsung Kim·2023년 5월 22일
0

CPP from C

목록 보기
1/1

lambda function 에서 [&] 는 어떻게 쓰는 건가?

ChatGPT 가 도와준거

#include <iostream>

int main() {
    int x = 5;

    auto lambda = [&](){
        std::cout << "Inside the lambda function: x = " << x << std::endl;
        x += 10;
    };

    lambda();

    std::cout << "after calling lambda function: x = " << x << std::endl;
    return 0;
}

함수 안에 x 안적어줘도 안에서 다 꺼내 쓸 수 있음. Surrounding scope 이라고..

Access to surrounding variables: By capturing variables by reference, the lambda function gains access to variables from the surrounding scope. This allows the lambda function to read, modify, or use those variables within its body. It provides a convenient way to work with variables without explicitly passing them as function arguments.

-> class 에서 쓸때, 함수에서 쓸때, global 에서 쓸 때 모두 차이 약간 있음

Convenience and conciseness: Lambda functions, especially when capturing variables by reference, offer a concise and inline way to define small, self-contained functions within a specific context. This avoids the need for defining separate named functions or function objects.

Flexible and adaptable: The use of the [&] capture list allows the lambda function to adapt to changes in the surrounding scope. If variables in the surrounding scope change, the lambda function will automatically reflect those changes since it operates on the captured references.

Enhanced readability and maintainability: Lambdas with capture lists can help improve code readability by keeping related functionality together. It reduces the need for scattering variable references across multiple function calls or having explicit argument passing. This can make the code easier to understand and maintain.

profile
Pick one

0개의 댓글