Lambda expressions in modern C++ (in depth step by step tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone and welcome to my channel in this video i want to talk about an important topic in modern c plus and that is lambda expressions also known as lambdas i am pretty sure that you have heard about lambdas before and in this video i'm going to explain everything that you need to know in order to start writing faster and cleaner code with lambdas in modern c plus plus now in this video i'm going to explain the most important concepts that you need to know but since this is a very broad topic and there is a lot to learn if you want to see some additional examples and practice on your own i am going to link a book in the description that you can use to learn about lambdas in modern c plus and the best thing is that it is completely free so make sure to check it out lambda expressions were introduced in modern c plus plus and they are available with c plus plus version 11 and above and the main purpose of lambda expressions is to allow you to write inline anonymous functions so what are inline anonymous functions well if you're familiar with regular functions you know that the main purpose of a function is to allow you to write the code once put it in a function and then whenever you need that code you would just invoke that function so no need to retype the code again now an inline function on the other hand is a function that has very small definition inline functions are usually very simple and they are very often used for small snippets of code that are very simple and they are not going to be reused like regular functions so they are not even worth to be named so that is why i also said that they are anonymous so as i said a lambda is an unnamed function that is not going to be reused like regular functions are lambdas are often used for short small snippets of code that are so simple that they are not even worth to be named they keep your code clean they are easy to read and they are fast to execute and they keep everything in the same place as you will see when i show you the code and also at the end of this video i'm going to show you a couple of tips and tricks that you can do with lambda so make sure to watch the video until the end so i believe that's enough speaking about lambdas now i'm going to show you the code and for writing the code we are going to use c plus builder which is the best id that you can use in order to build c plus user interface applications um so if you are also interested to learn about c plus user interface applications i'm going to link that in the description and i will leave a link that you can use in order to download c plus builder in the description as well so let's create a console application that we will need in order to write our code click on file new other and then console application okay make sure that c plus plus is selected here click ok and here is our code so if i run this program let's see what is going to happen okay let's add couple things so here i'm going to say system pause greater than no okay and then let's add std c out hello world like this okay and then one more thing that i need to do is i need to include iostream so i will say include stream like this and now our code should work so if i run my application again here we have our hello world console application so how does a lambda look like well let's delete this code and i'm going to start with a simple example so what do you need in order to create a lambda first thing that you need are these angled brackets and then parentheses and then you need curly brackets like this so this here is how you create a lambda now i know that there is a lot of brackets so let me explain what each of these is used for so this first pair these angled brackets are called capture claws and i'm going to explain what they are used for later in this video for now let's just put cc here so capture clause now these parentheses are used in order to pass parameters so here you put parameters p okay and then inside these curly brackets you put the definition of your lambda function so let's call it f d function definition okay so what i want to do now is i want to create an example and then we are going to see how we can solve a problem from that example by using lambdas so the first thing that i need is a vector so let's say here include vector like this and then here let's create a vector let's say std vector and let's say that it's going to be vector of integers and i will call it v and i will initialize it so that it has elements of 2 3 7 14 and 23 for example now an interesting thing that i want to do with this vector here is the following in c plus plus there is a very useful header file called algorithm and it contains a lot of functions that are designed to work with ranges of elements like our vector here and one of those functions is for each so let me show you how that works and how we are going to use lambdas with for each function so as i said it is part of algorithm header file so the first thing that we need to do is say include algorithm okay and one of the functions from this header file is called for each so i will say std for each like this and what this for each function should do is it should iterate through this vector here from the beginning until the end so let's specify that let's say for each v dot begin until v dot end okay what i want to do is i want to do something like this so for each element of this vector here from the beginning until the end please do something and let's put semicolon at the end so now i want to specify what this something is so let me very quickly type some code that i want to show you and i want to show you a problem with that code and then we are going to introduce lambdas in order to solve that problem so this is the code that i added i created a structure and inside it i had to override this operator here that receives one parameter and i just print that parameter in the body of this function and i named that something so the same name as this here so what we expect to happen now is that for each element of this vector here from the beginning until the end we invoke this function here so the result should be that all of these elements should be printed in our console so let's run the program okay and we have an error and the error is this part here so let's just comment this this is not valid code this is just for us to remember how a lambda looks like so let's run the program now okay and as i promised here are all of the elements of our vector now the problem that i have with this code here this code is that it's overkill so to create a structure and then override an operator just to be able to print an element into the console is an overkill too much code so what i want to do now is i want to show you how you can solve this same problem by using a lambda expression so we will write much less code is going to be much cleaner and easier to read and understand so let's create our lambda and here is the formula that we will use let's do it here so the first thing is our capture clause and then parentheses for parameters and then curly brackets for function definition so here we have a lot of brackets so what do we put inside these brackets well for now this capture clause is going to stay empty and then inside these parentheses we put parameters and that is going to be this parameter here so int x that goes here and then inside curly brackets we put function definition and that will be this part here so i'll copy it and paste it here okay now what i can do is i can just replace this something with this line of code with our lambda so i'm going to copy it and then paste it here okay and i will comment this part and i will also comment this part so that we can see how our program will run with this lambda function instead of this part here so if i run the program as you can see the behavior is the same with this one line of code as it was with this structure and then overloaded operator and so on so our program works as expected so what that means is that now i can completely remove this code because from now we will not use this approach but we will use lambdas instead so again why would you use this approach here instead of the one that i just deleted well it's cleaner code it's easier to read and it keeps everything in the same place so everything that you need is here in this line of code and in case that you wanted to write and use this function again you would probably retype it anyways because it's very simple it's a very trivial function and if you wanted to reuse this as a function create a function to be able to reuse it it's much more work than benefit so you would have to create a function and then you would have to put it in a header file and you would have to find a place where you are going to put that header file so that it can be accessed by different parts of your application so that your function can be reused and then if that feather header file is going to consist of functions that are like this one what are you going to name it like my favorite two line functions it doesn't really make sense so that is why in this situation lambdas are much better solution so what happens if you wanted to do something else well let's delete this part because i prefer to write my lambda here and then just copy it and paste it here so let's say for example that for each element of this vector you want to print the information if it is even or odd number let's do that part here so here instead of just printing the element i will create an if else expression so i will say if x modulated by 2 is equal to 0 that means that the number is even so if it is divisible by 2 that means that the number is even so i will say std c out x is oh is even number like this okay and then i will say else x is odd number like this so if i want to use this lambda inside my for each i will just paste it here like this so capture clause parameters and then the definition of my function which is this part here okay so now you need to comment this part out because we will have a compile time error if we don't and then if i run my program let's see what is going to happen and we have the information that 2 is even 3 is odd 7 is odd 14 is even and then 23 is odd number so that is another example of how you can use lambda expressions something that i promised at the beginning of the video is that i will share some useful tips related to lambda expressions and that is the fact that lambda expressions can be much more powerful than ordinary functions and that is because a lambda expression can have access to variables from its enclosing scope so what does that mean well that means that this lambda here can have access to all the variables from its enclosing scope which is this scope here so all the variables from our main function and at the moment we don't have any variables so let's change that let's create a variable i'll do it here delete this part of the code so let's create a variable of type int and i will call it d and let's assign it the value of three so what i want to do with this variable here is i want to pass it into this lambda and for that i will use this capture clause so i want to capture this variable here into this lambda function and how i will do that well you just say here d very simple so now you can use this d variable inside this lambda here so how are we going to use this d so the reason why i named this variable d is because i want to use it in order to divide my x by that variable so i will say if x modulated by number d gives the result of zero that means that x is divisible by number d so let's change this part here as well so if this is true that means that x is divisible by and then here let's put this number d like this and then in this else situation i will say that x is not divisible by d and let's delete this line of code okay so if i run the program again let's see what's going to happen as you can see it says that 2 is not divisible by 3 3 is divisible by 3 7 is not 14 is not and 23 is not okay and what you can do now is you can change this d to be any number that you want so let's say for example number seven and if i run the program again it says that 2 is not 3 is not 7 is divisible by 7 14 is as well divisible by 7 and then 23 is not so that is how you capture a variable and pass it to your lambda by using this capture clause now one thing that you cannot do in this situation is you cannot change the value of this d variable so if i try to do something like this if i try to say for example d is equal to 10 we are going to get an error okay the application has failed and it says cannot assign to a variable captured by copy in a non-mutable lambda so what does that mean it means that if you want to change values of captured variables you need to pass them by a reference and this here should work okay so if you pass it by value like this that means that you cannot change it inside your lambda and then if you want to change it you will need to pass it by a reference like this okay so if i write the value of my d now so if i say std c out and then i say d is equal to and then let's print d and if i run the program as you can see the value of our d variable has been changed okay so what happens if you have multiple variables that you want to capture in your lambda well let's say that you have also a variable called e and then its value is equal to five so if you want to pass this e variable as well well you just put a column sign and you pass that variable as well like this and then again here you will not be able to change the value of this e so if i say e is equal to 10 or 19 this here is going to result as an error if you want to change it again you need to pass it by a reference like this now something that is useful to know is that if you want all your variables to be passed by a reference so that you can change them all in your lambdas what you can do instead is you can just put this ampersand symbol like this and this should work so if i run the program there will be no compile time errors as you can see and then if you want all your variables to be passed by value you use this symbol here and that means that the values of these variables will not change inside this lambda you will not be able to do that so if i run the program we get two errors for these two lines of code okay so let's return this so that we can change the value of both variables like this so those were some tips and tricks that i wanted to share related to lambda expressions and if you want to see some more examples definitely check out the book that i will link in the description it is completely free so you can download it and use it to learn on your own and learn more details and see more examples of lambda expressions and how they are used so thank you very much for watching uh if you enjoyed this video please give it a thumbs up and then also share it with your friends and with other people who would like to learn programming and i will see you in some other video bye
Info
Channel: CodeBeauty
Views: 17,534
Rating: undefined out of 5
Keywords: lambda, lambdas, lambda expressions, lambda expression, c++, lambda expressions in c++, lambda expression in c++, c++ lambdas, what is lambda, c++ lambda expressions, c++ lambda expression, modern c++, codebeauty, code beauty, 2022, inline functions, anonymous functions, functor, lambda expressions in modern c++, modern c++ lambda expressions, tutorial, saldina, example, what is lambda expression, what are lambda expressions, lambda expressions example, lambda expression example
Id: MH8mLFqj-n8
Channel Id: undefined
Length: 18min 35sec (1115 seconds)
Published: Wed Nov 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.