Jan 2, 2020 in C Plus Plus
Q: Lambda expression in C++

1 Answer

0 votes
Jan 2, 2020
A lambda expression lets you define functions locally, at the place of the call, thereby eliminating much of the tedium and security risks that function objects incur. A lambda expression has the form:

[capture](parameters)->return-type {body}

The [] construct inside a function call's argument list indicates the beginning of a lambda expression. Let's see a lambda example.

Suppose you want to count how many uppercase letters a string contains. Using for_each() to traverses a char array, the following lambda expression determines whether each letter is in uppercase. For every uppercase letter it finds, the lambda expression increments Uppercase, a variable defined outside the lambda expression:

int main()


   char s[]="Hello World!";

   int Uppercase = 0; //modified by the lambda

   for_each(s, s+sizeof(s), [&Uppercase] (char c) {

    if (isupper(c))



 cout<< Uppercase<<" uppercase letters in: "<< s<<endl;


It's as if you defined a function whose body is placed inside another function call. The ampersand in [&Uppercase] means that the lambda body gets a reference to Uppercase so it can modify it. Without the ampersand, Uppercase would be passed by value. C++11 lambdas include constructs for member functions as well.
Click here to read more about Loan/Mortgage
Click here to read more about Insurance

Related questions

+1 vote
+1 vote
+1 vote
+1 vote
+1 vote
Jan 2, 2020 in C Plus Plus
+1 vote