C++

C++ 람다식(Lambda expression) 총정리

김구티2 2024. 4. 25. 21:12

1. 람다식의 개념

이름이 필요 없는 짧은 코드 조각에 사용할 수 있는 인라인 함수를 허용하기 위해 Lambda expression이 도입됐다. 가장 간단한 형태로 람다 식을 다음과 같이 정의할 수 있다.

 

[ capture clause ] (parameters) -> return-type  
{   
   definition of method   

 

일반적으로 람다 식의 리턴 타입은 컴파일러 자체에서 평가하므로 명시적으로 지정할 필요는 없다. 또한 the -> return-type 부분은 무시할 수 있다. 그러나 조건문과 같이 복잡한 경우에는 컴파일러가 리턴 타입을 결정할 수 없으며, 명시적인 지정이 필요하다.


표준 함수를 사용한 람다 식의 다양한 용도는 다음과 같다:

// C++ program to demonstrate lambda expression in C++
#include <bits/stdc++.h>
using namespace std;

// Function to print vector
void printVector(vector<int> v)
{
     // lambda expression to print vector
     for_each(v.begin(), v.end(), [](int i)
     {
          std::cout << i << " ";
     });
     cout << endl;
}

int main()
{
     vector<int> v {4, 1, 3, 5, 2, 3, 1, 7};

     printVector(v);

     // below snippet find first number greater than 4
     // find_if searches for an element for which
     // function(third argument) returns true
     vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i)
     {
          return i > 4;
     });
     cout << "First number greater than 4 is : " << *p << endl;


     // function to sort vector, lambda expression is for sorting in
     // non-increasing order Compiler can make out return type as
     // bool, but shown here just for explanation
     sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool
     {
          return a > b;
     });

     printVector(v);

     // function to count numbers greater than or equal to 5
     int count_5 = count_if(v.begin(), v.end(), [](int a)
     {
          return (a >= 5);
     });
     cout << "The number of elements greater than or equal to 5 is : "
             << count_5 << endl;

     // function for removing duplicate element (after sorting all
     // duplicate comes together)
     p = unique(v.begin(), v.end(), [](int a, int b)
     {
          return a == b;
     });

     // resizing vector to make size equal to total different number
     v.resize(distance(v.begin(), p));
     printVector(v);

     // accumulate function accumulate the container on the basis of
     // function provided as third argument
     int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
     int f = accumulate(arr, arr + 10, 1, [](int i, int j)
     {
          return i * j;
     });

     cout << "Factorial of 10 is : " << f << endl;

     //  We can also access function by storing this into variable
     auto square = [](int i)
     {
          return i * i;
     };

     cout << "Square of 5 is : " << square(5) << endl;
}

 

출력:

4 1 3 5 2 3 1 7 
First number greater than 4 is : 5
7 5 4 3 3 2 1 1 
The number of elements greater than or equal to 5 is : 2
7 5 4 3 2 1 
Factorial of 10 is : 3628800
Square of 5 is : 25

 

람다 식은 바깥쪽 범위에서 변수에 액세스함으로써 일반 함수보다 더 강력한 기능을 가질 수 있다. 우리는 3가지 방법으로 바깥쪽 범위에서 외부 변수를 캡처할 수 있다.

① Capture by reference 

② Capture by value 

③ Capture by both (mixed capture)


변수 캡처에 사용되는 구문:
[&] : reference로 모든 외부 변수 캡처
[=] : value로 모든 외부 변수 캡처
[a, &b] : a는 value로, b는 reference로 캡처
빈 캡처 절 [ ]이 있는 람다는 로컬인 변수에만 액세스할 수 있다.

 

예시:

// C++ program to demonstrate lambda expression in C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
     vector<int> v1 = {3, 1, 7, 9};
     vector<int> v2 = {10, 2, 7, 16, 9};

     // access v1 and v2 by reference
     auto pushinto = [&] (int m)
     {
          v1.push_back(m);
          v2.push_back(m);
     };

     // it pushes 20 in both v1 and v2
     pushinto(20);

     // access v1 by copy
     [v1]()
     {
          for (auto p = v1.begin(); p != v1.end(); p++)
          {
               cout << *p << " ";
          }
     };

     int N = 5;

     // below snippet find first number greater than N
     // [N] denotes, can access only N by value
     vector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i)
     {
          return i > N;
     });

     cout << "First number greater than 5 is : " << *p << endl;

     // function to count numbers greater than or equal to N
     // [=] denotes, can access all variable
     int count_N = count_if(v1.begin(), v1.end(), [=](int a)
     {
          return (a >= N);
     });

     cout << "The number of elements greater than or equal to 5 is : "
             << count_N << endl;
}

 

출력:

First number greater than 5 is : 7
The number of elements greater than or equal to 5 is : 3

728x90

'C++' 카테고리의 다른 글

C++ 포인터(Pointers) 총정리  (0) 2024.04.29
C++ 포인터와 레퍼런스 정리  (0) 2024.04.29
C++사용자 정의 예외  (0) 2024.04.25
C++ 스택 풀기(Stack Unwinding)  (0) 2024.04.24
C++ 클래스를 이용한 예외 처리  (0) 2024.04.24