// lambda.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include #include #include #include using namespace std; void print(int i) { cout << i << endl; }; int main() { vector vi; //reminder about the vector vi.push_back(1); vi.push_back(2); vi.push_back(3); vi.push_back(4); vi.push_back(5); vi.push_back(6); for_each(vi.begin(), vi.end(), print); //usual way of printing the vector elements cout << "__________________________________________" << endl; //Lambda example for_each(vi.begin(), vi.end(), [](int k) { cout << k << endl; }); //Square brackets say that it is a lambda function, round brackets say that lambda takes integers as parameter and braces say what we are going to do cout << "__________________________________________" << endl; for_each(vi.begin(), vi.end(), //exactly the same function but written in multiple lines [](int k) { cout << k << endl; } ); cout << "__________________________________________" << endl; for_each(vi.begin(), vi.end(), //lambda funciton with multiple statements [](int k) { if (k % 3 == 0) { cout << k << " is divisible by 3" << endl; } else { cout << k << " is not divisible by 3" << endl; } } ); cout << "__________________________________________" << endl; //Lambdas with return type vector v2; transform(vi.begin(), vi.end(), back_inserter(v2), [](int k) {return k * k; }); //Lambda that returns, transform take one collection and transform to another collection, back_inserted push back the elements to the new vector //This lambda is easy for compiler to figure out the type of the return -> we do not need to specify it explicitly for_each(v2.begin(), v2.end(), [](int k) { cout << k << endl; } ); vector v3; transform(vi.begin(), vi.end(), back_inserter(v3), [](int k)->double { if (k % 2 == 0) { return k * k; } else { return k * k / 2.0; } } ); //Lambda that returnsm where we need to specify the return type for_each(v3.begin(), v3.end(), [](double s) { cout << s << endl; } ); system("pause"); return 0; }