/* File: lambda1.cpp Simple example of a lambda expression in C++ Lambda expressions that do not capture any variables can be type cast to function pointers. */ #include using namespace std ; typedef int (* f_type) (int) ; void apply( f_type f, int A[], int n) { for (int i=0 ; i < n ; i++) { A[i] = f( A[i] ) ; } } int main () { auto add3 = [](int n) { return n + 3 ; } ; // a lambda expression in C++ cout << "add3(5) = " << add3(5) << endl ; int B[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} ; printf("Before:\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (add3, B, 10) ; printf("\n\nAfter calling apply(add3, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply ( [](int n){ return n + 5 ;}, B, 10) ; // real intention printf("\n\nAfter calling apply(..., B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } }