From 54c67dfb38d1bb2a9dc004b3244d2ae3102107f3 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Thu, 29 Oct 2015 22:13:24 +0530 Subject: [c++] Added Lambda Expressions and Range for --- c++.html.markdown | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) (limited to 'c++.html.markdown') diff --git a/c++.html.markdown b/c++.html.markdown index d03092e5..6033ca06 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -801,6 +801,106 @@ void doSomethingWithAFile(const std::string& filename) // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// Example consider sorting a vector of pairs using the second +// value of the pair + +vector > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the header + +sort(tester.begin(), tester.end(), [](const pair &lhs, const pair &rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables. +// For Example: + +vector dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++){ + dog_ids.push_back(i); +} + +int weight[3]; +weight[0] = 30, weight[1] = 50, weight[2] = 10; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +sort(dog_ids.begin(), dog_ids.end(), [weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// Note we captured "weight" in the above example. + +// lambda are really useful for the case of structs +// You can use lambda expressions instead of overloading +// the "<" operator + +struct dog{ + int weight, age; +}dogs[3]; + +dogs[0].weight = 30, dogs[0].age = 4; +dogs[1].weight = 40, dogs[1].age = 10; +dogs[2].weight = 20, dogs[2].age = 9; + +// Say I want to sort the dogs array by the dogs' weights + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.weight < rhs.weight; + }); +// dogs is now sorted according to their weight + +// Do something with the dogs + +// Now I want to sort the dogs by in descending order of their age + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.age > rhs.age; + }); +// dogs is now sorted in descending order of their age + + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout<