Lambdas
Contents
File: lambdas13.cpp
#include <algorithm> #include <array> #include <string> #include <functional> #include <iostream> using namespace std ; int main() { //using the mutable keyword //we can change the value in the lambda function //but that change is not refected in the code calling //the lambda function int a1 = 1; int b1 = 1; cout << "In main():" << endl; cout << "a1 = " << a1 << ", "; cout << "b1 = " << b1 << endl; cout << endl; auto add_one = [a1, &b1] () mutable { // modify both a1 & b1 a1++; b1++; cout << "In add_one():" << endl; cout << "a1 = " << a1 << ", "; cout << "b1 = " << b1 << endl; }; add_one(); add_one(); cout << endl; cout << "In main() After calling the lambda function:" << endl; cout << "a1 = " << a1 << ", "; cout << "b1 = " << b1 << endl; }
Output: $./a.exe $ g++ lambdas13.cpp ; ./a.exe In main(): a1 = 1, b1 = 1 In add_one(): a1 = 2, b1 = 2 In add_one(): a1 = 3, b1 = 3 In main() After calling the lambda function: a1 = 1, b1 = 3We are passing 2 variables in the parameters clause. The "a1" is passed by value and the "b1" is passed by reference. We are able to change the value of "a1" because of the mutable keyword. That change is kept local to the lambda
Exercise
File: mutable_ex1.cpp
1) What does the below program print ?
#include <iostream> using namespace std ; int main() { int counter = 0; // Lambda capturing 'counter' by value and declared mutable auto increment = [counter]() mutable { // 'counter' can be modified inside the lambda because of 'mutable' counter++; cout << "Inside lambda: counter = " << counter << endl; }; increment(); // Call the lambda increment(); // Call the lambda again increment(); // Call the lambda a third time cout << counter << endl; return 0; }
Solutions
File: lambdas_ex_1s.cpp