The thing that used to confuse me the most about lamdas was that I didn't understand why there was such a thing as a capture bracket for passing arguments when lambdas also provide the standard way of passing arguments just like ordinary functions do. Then I read somewhere that by using the capture bracket, the variables in the surrounding scope get treated as if they were member variables of the object created by using the lambda. I think this ties in to example you made in the video - when you tried to pass the lambda as an argument to a function that accepted a function pointer as a parameter , it only worked as long as capture bracket wasn't being used. It only passed the functionality defined by the lambda. However, if you want to pass the entire object that gets created by the lambda, together with the variables captured in the brackets, you need to pass it as a function object instead, not just a function pointer. So, in conclusion - arguments passed as parameters get treated just like they would if you were passing them to any function. Variables captured by the brackets become a part of the lambda object.
Thanks a lot for this. That part of the video left me confused so I came to the comments looking for some explanation... Yours made everything clear! Cheers.
This code helped me understand lambdas when I was first learning about them. std::string str{ "this is a string!" }; auto lambda = [&](int num) { std::cout
This is a basic and implicit functionality of lambdas in other languages (ie. C#, JavaScript) but here in C++ you have to explicitly state that you want the given variables to be part of the lambdas scope. It is a weird choice imho and I have no idea why didn't they just made it so that these variables are implicitly already part of the lambda's scope just like in the languages the I mentioned before.
Well as you described very well, just adding some more light to it it looks like this. int main() { int a; int b; auto lamb = [a,&b](int value){ b = value; return a+b; };
lamb(10); return 0; } it looks like this. int main() { int a; int b;
class __lambda_7_17 // random name generated for lambda class { int a; int & b; public: inline /*constexpr */ int operator()(int value) const { b = value; return a + b; }
great video very helpful C++ is a powerful programming language but it has so much syntax. for example there are 4 ways to define a lambda function. this is just confusing and makes code unreadable I'm starting to understand why old school programmers prefer plane C. you have structs functions and pointers. with that they can abstract anything they want.
So glad you are still doing this mane! Keep up the good work! Document everything you know about C++ its so great to have this playlist at my disposal :-) Thanks as always!
Would be interesting if you highlighted more about why they're preferred to function pointers. They've become almost a standard in many different languages.
I think the previous video did that. Function pointer syntax is daunting and you’d have to define your functions at a larger scope than ideal to use them.
@@puppergump4117 I think what they meant to say is that having a micro celebrity of C++ space as an employee would make the company walk on eggshell and give him special treatment because he can use his internet clout to destroy the company's reputation. Nobody wants to screw over their workers but sometimes harsh decisions are made and some people dont take to them lightly but those people also doesn't have a decent following so they are not a risk. I mean just imagine having someone like Joshua Fluke as your employee.
7:00 "Sure thing now it's not gonna work. we need to convert it and add blah blah one billion obvious other things... aand... here we go!" .___. how you do this man
void(*func)(int) is specifically a pointer to a function that takes an int and returns void. It can only point to functions (not lambdas, functors, etc.). std::function can hold any callable object that matches the signature void(int), including functions, lambdas, and functors.
"its pretty simple" every lambda can take inputs within the callback parent function's scope, or take inputs in the declaration scope, using the [] part. and the pointer syntax changes with usage. WHAT
actually i just encountered these in the wild, in an example for a library. and im by no means a highly experienced programmer. It was used in a specialised "for each" function just like in this video
Your lambda example made me think of a dating game concept, where people's prerequisites vary and are stored as lambda variables or something, so that according to an individuals perception, their metrics change.
I'm reminded of the noun-verb system used on the apollo guidance computer. A lambda variable would sort of be an adverb, then? The best example for when and how to use this that I saw was an example quicksort that took, as a parameter, a comparison function. This allowed the same sort function to be used for any type of data you could think of, so long as you could code a function that told the quicksort which data element was larger, which is slick as hell.
The mutable keyword for lambdas its if you invoke the lambda several times. If you modify lambda copy of parameter - it would affect the next invokation. Thats why you have to explicitly say that its the behavior you want.
I'd like a video about constexpr too. I mean, conceptually it isn't hard to understand but it would be great to see it in action with some examples of different situations where you would need to use it
I would to point out that this subject was very hard for me before using map () in javascript. Basically it is that same thing. And that is way learning new language may help you understand the other
Why not just only use function pointers? This notation is more confusing and verbose. Could anyone give an example where it would be best using lambdas than function pointers? It seems to me that lamdas are only useful when you want something really simple and only once. Is this the use case?
Missing link to cppreference for lambdas: en.cppreference.com/w/cpp/language/lambda (it was missing in the video description at the moment this comment was posted).
What's the lifetime of the closure though? If you capture something in there you lock yourself in a way because if you free the reference the lambda function can't get to it. If you pass something by value I assume the value is taken from the point the Lambda is generated not when it's called, since otherwise the surrounding code and thus the variable could be deallocated from the stack. But since the lambda can be called after the place it's created, it must be heap so when does it get destroyed? Is that up to us? How do we know if whatever we pass it to is done with it? Lambdas in C++ feel like a memory leak landmine to me with the understanding I have at this moment. - Love them in Swift where I feel I understand the ARC system very well to use them in a neatly handled way memory wise, but here I feel like I could very easily leak memory
you just added "function" and did some magic to make your code work. but forgot to explain what you did. as your "lambda" was having some syntax issue. can you please explain that.
Do you think lambda's can be substitute for a function which huge function body? I mean..what if the call back function has a huge body and not just a one or two lines of code?
I don't get it. A lambda just seems like extra unnecessary steps. If you're trying to do a cout, why not just type that and be done. Why encapsulate the cout in a bunch of brackets (lambda) for it to achieve the same result?
It looks dumb with simple examples like here, but I'm sure there are some valid reasons to use this. I think it might serve as an inline adapter for function. Like, you want to see which value in array is bigger than 1024. You wrap a comparison function into a lambda, passing it 1024 as one of parameters, and pass lambda to the foreach, for example. Also it just saves you from having one liners like void ____internal____Function(int a) { return a + (int)Pi; } somewhere in your file that will inevitably get lost among normal functions that are much longer than that. Also it can just be inlined and limited to only capture what you need. In that sense it's equivalent to int b = 42; int c = 9; /*Do something*/ { int a = b; ... } But you can't "accidentally" insert c = a*a; in the body and break everything, if I understand correctly.
Could you explain why find_if is any better than writing your own for loop. I know this is a simple example but some of the STL seems a bit superfluous
What problems this cpp feature solves ?? ...can we have a real life example for average programmer (some feature video) … I understand the concept, but what is the benefit for complicating the code (my not educated perspective)
A common place for this is when you are creating APIs projects, or something that should be used by others. I always picture functions that have functions's args as wrappers to focus on their core behaviour. Cherno used good examples of it. For example, when you call a ForEach funcion, what do you really want to do? you want to anything with each element of a list. The function wraps the loop part and leaves to you only the part that matters, do something with each element. Find_if function does the same. What do you want? for each element, you want to check if a certain condition is true (that's why bool return) and get the count of elements. Both examples abstracts the repetitive stuff and leaves you with what really matters, a function (your lambda) with a specific behaviour that doesn't have to deal with anything else than the core functionality. It may be too much because these examples wraps less code, but in real life, you can wraps a lot of things
I don't know why, but that sofa and the tree swaying in the backyard , bright sunny day, it just all feels awesome and nostalgic..
The best cpp video tutorials I've ever seen, thank you!
The thing that used to confuse me the most about lamdas was that I didn't understand why there was such a thing as a capture bracket for passing arguments when lambdas also provide the standard way of passing arguments just like ordinary functions do.
Then I read somewhere that by using the capture bracket, the variables in the surrounding scope get treated as if they were member variables of the object created by using the lambda. I think this ties in to example you made in the video - when you tried to pass the lambda as an argument to a function that accepted a function pointer as a parameter , it only worked as long as capture bracket wasn't being used. It only passed the functionality defined by the lambda. However, if you want to pass the entire object that gets created by the lambda, together with the variables captured in the brackets, you need to pass it as a function object instead, not just a function pointer. So, in conclusion - arguments passed as parameters get treated just like they would if you were passing them to any function. Variables captured by the brackets become a part of the lambda object.
Thanks a lot for this. That part of the video left me confused so I came to the comments looking for some explanation... Yours made everything clear! Cheers.
This code helped me understand lambdas when I was first learning about them.
std::string str{ "this is a string!" };
auto lambda = [&](int num) { std::cout
This thread has been incredibly helpful. Thank you to both of you guys that offered an explanation.
This is a basic and implicit functionality of lambdas in other languages (ie. C#, JavaScript) but here in C++ you have to explicitly state that you want the given variables to be part of the lambdas scope. It is a weird choice imho and I have no idea why didn't they just made it so that these variables are implicitly already part of the lambda's scope just like in the languages the I mentioned before.
Well as you described very well, just adding some more light to it
it looks like this.
int main()
{
int a;
int b;
auto lamb = [a,&b](int value){
b = value;
return a+b;
};
lamb(10);
return 0;
}
it looks like this.
int main()
{
int a;
int b;
class __lambda_7_17 // random name generated for lambda class
{
int a;
int & b;
public: inline /*constexpr */ int operator()(int value) const
{
b = value;
return a + b;
}
public: __lambda_7_17(int _a, int & _b)
: a{_a}
, b{_b}
{}
};
__lambda_7_17 lamb = __lambda_7_17{a, b};
lamb.operator()(10);
return 0;
}
I can’t thank you more. This had puzzled me for more than 6 months. I just felt so relieved and rejuvenated today. Thanks Cherno.
THANK YOU SO MUCH for this video!! You made everything clear
honestly a great series for programmer who have past exp , did whole thing (till lambdas)in like 3-4 hrs and understood almost everything .
Thanks for this, the learncpp section on this nearly cooked my headmeat.
great video very helpful
C++ is a powerful programming language but it has so much syntax. for example there are 4 ways to define a lambda function. this is just confusing and makes code unreadable
I'm starting to understand why old school programmers prefer plane C. you have structs functions and pointers. with that they can abstract anything they want.
finally clearing up a topic I tried to avoid as it confused and overwhelmed me when I first saw it.. thanks!
Hey, I didn't understand that what was the use of ForEach function in this video it would be great if you could help me :)
Sakshi Gupta bruh
2:24 This is almost the exact case I was wanting to use this for, funny enough
So glad you are still doing this mane! Keep up the good work! Document everything you know about C++ its so great to have this playlist at my disposal :-) Thanks as always!
best cpp and one of best programming channel ever
Would be interesting if you highlighted more about why they're preferred to function pointers. They've become almost a standard in many different languages.
I think the previous video did that. Function pointer syntax is daunting and you’d have to define your functions at a larger scope than ideal to use them.
You should make a video on C++ iterators, dude.
please!
@@gvcallen he did today ;)
ok dude
NOOOOOOO
Thank you so much.. I was not clear abot Lambas ever after reading so much.. You made it look so simple.
Damn this guy is so good, must feel pretty good knowing that if you interviewed anywhere you can get the job.
@Lance Adan this is a scam, don't touch, report those comments as spam instead.
@Over Yonder What kind of idiot would put their business at risk just to screw over their workers?
@@puppergump4117 I think what they meant to say is that having a micro celebrity of C++ space as an employee would make the company walk on eggshell and give him special treatment because he can use his internet clout to destroy the company's reputation.
Nobody wants to screw over their workers but sometimes harsh decisions are made and some people dont take to them lightly but those people also doesn't have a decent following so they are not a risk.
I mean just imagine having someone like Joshua Fluke as your employee.
Thank you for explaining that complex topic in a very simple way. A big thanks from India.😊
Wow, this video in combination with the previous one about function pointers was an enlightenment to me! 😄🙏👏 Thank you!
7:00
"Sure thing now it's not gonna work. we need to convert it and add blah blah one billion obvious other things... aand... here we go!"
.___. how you do this man
void(*func)(int) is specifically a pointer to a function that takes an int and returns void. It can only point to functions (not lambdas, functors, etc.).
std::function can hold any callable object that matches the signature void(int), including functions, lambdas, and functors.
Thanks for the clarity of video! Especially for the second part that includes the functional thing!
This is super awesome. And thank you for inadvertently showing me how to put in a breakpoint in my IDE. Never knew I could do that. :)
"its pretty simple"
every lambda can take inputs within the callback parent function's scope, or take inputs in the declaration scope, using the [] part. and the pointer syntax changes with usage.
WHAT
The level of programming you have to possess to encounter situation in which such mechanics must be used is unfathomable.
actually i just encountered these in the wild, in an example for a library. and im by no means a highly experienced programmer. It was used in a specialised "for each" function just like in this video
Dude your channel is awesome! Your videos are super informative and useful. Keep up the good work :)
Start the game engine series soooon please. I'm excited af!
Thank you Cherno! Finally understand it
Your lambda example made me think of a dating game concept, where people's prerequisites vary and are stored as lambda variables or something, so that according to an individuals perception, their metrics change.
I'm reminded of the noun-verb system used on the apollo guidance computer. A lambda variable would sort of be an adverb, then? The best example for when and how to use this that I saw was an example quicksort that took, as a parameter, a comparison function. This allowed the same sort function to be used for any type of data you could think of, so long as you could code a function that told the quicksort which data element was larger, which is slick as hell.
you know the way you teach me is exactly the way i want to be tought
One can never have too many function pointer, functor, and lambda videos.
Thank you for making the video!
The mutable keyword for lambdas its if you invoke the lambda several times. If you modify lambda copy of parameter - it would affect the next invokation. Thats why you have to explicitly say that its the behavior you want.
Man, you saved my day.
Thank you, this was so helpful!!
make video about constexpr and std::optional
I'd like a video about constexpr too. I mean, conceptually it isn't hard to understand but it would be great to see it in action with some examples of different situations where you would need to use it
@@fishyperil2153 totally agree
thank you
I would to point out that this subject was very hard for me before using map () in javascript. Basically it is that same thing. And that is way learning new language may help you understand the other
Thanks for uploading :D nice!
at this point, I can only hear daughter instead of data. tbh. brilliant stuff
Australian accent vs whatever your accent is.
Thanks
got to capture them all! [pokemon].
Lol
Thank you!
This content ► Amazing explanations
These are so fun to watch man
Thanks lot. Wonderful Video.
u are my favorite, Amazing, u kept it very clear...
Top quality tutorial, Thank you.
Why not just only use function pointers? This notation is more confusing and verbose.
Could anyone give an example where it would be best using lambdas than function pointers?
It seems to me that lamdas are only useful when you want something really simple and only once. Is this the use case?
You are the best for c++.
THANKS
Soooooo a callback function
so helpful thanks
Your the sh** mr cherno, rock on brother
Hey great playlist on c++. Can you make a video on iterators in c++?
awesome , Thank you
bless yo intelligent, puzzle solving soul
Thanks man
nice couch you got there.
Missing link to cppreference for lambdas: en.cppreference.com/w/cpp/language/lambda
(it was missing in the video description at the moment this comment was posted).
Added, thank you! :)
The best tutorial on the internet!
You're amazing!
Function objects. You said in the last video you were going to make a video on function objects.
You really know what you're doing. You're so good. Do you have a video about ECS?
do more c++ videos on functional programming
5:00 When I need that I use it ALL THE TIME.
A lambda is an anonymous function. A way for us to make a function without having to physically make one.
A God amongst men.
What's the lifetime of the closure though? If you capture something in there you lock yourself in a way because if you free the reference the lambda function can't get to it. If you pass something by value I assume the value is taken from the point the Lambda is generated not when it's called, since otherwise the surrounding code and thus the variable could be deallocated from the stack. But since the lambda can be called after the place it's created, it must be heap so when does it get destroyed? Is that up to us? How do we know if whatever we pass it to is done with it?
Lambdas in C++ feel like a memory leak landmine to me with the understanding I have at this moment. - Love them in Swift where I feel I understand the ARC system very well to use them in a neatly handled way memory wise, but here I feel like I could very easily leak memory
great, helps a lot!
Amazing
Apart from Asthetics what is the main advantage of using a lambda over a normal function.
I have learned C++ in Stroustrup's book, but it is so old it does not use any lambdas. Instead it uses classes to to enter a function into sort. lol
which book? Hes got a newer one...
Hey, good man what about you ?
Welcome to you.
Great video. The couch made me laugh.
Wow....... thanks a lot ,from egypt .
mnen ya zmala?
you just added "function" and did some magic to make your code work. but forgot to explain what you did. as your "lambda" was having some syntax issue. can you please explain that.
How to pass by const reference in lambdas ? Which might be useful when you pass large objects in lambdas
hey.. thanks for all these videos on C++.. Could u also make a video on Functors in C++?
First of your videos that blew my mind off to another planet. Sorry really you show new syntax there that you haven't told us before... :(
What about defining a lambda within a custom class and you want to use the members of that class in you lambda?
You can capture the "this" pointer
Do you think lambda's can be substitute for a function which huge function body? I mean..what if the call back function has a huge body and not just a one or two lines of code?
What's the difference between capturing by reference and using "mutable" when capturing by copy?
Please make a sophisticated course with some sort of company talking about algorithms/data structures, and sell it to us that would be amazing.
U r love
0:00 Chris? is that you?
*googles lambda c++*
*presses video*
*finds out it is THE CHERNO 🥰😘😘😘🥰🥰🥰🥰🥰🥰🥰🥰🥰🥰*
The same reaction when you realise that I’m commenting on your comment
Can you please make video explaining the basic differences between function pointer and lamdas?
Thank you ! By the way "Cherno" in bulgarian means "Black" :) (the same pronanciation)
Lambdas in C++ ~ Event Listeners in Java
So [] in c++ lambdas are somewhat like closures in JavaScript
Idea for next video:
Advanced templates
how did you got into EA?
by playing Fifa -_-
Here its explained: th-cam.com/video/ykjtuSkt9g8/w-d-xo.htmlm53s
That type of English can't get you into EA m8. just saying.
Luftwafte I what's wrong with my English?
got instead get. Don't mind him though, your english is fine.
hardest video so far
I don't get it. A lambda just seems like extra unnecessary steps. If you're trying to do a cout, why not just type that and be done. Why encapsulate the cout in a bunch of brackets (lambda) for it to achieve the same result?
It looks dumb with simple examples like here, but I'm sure there are some valid reasons to use this.
I think it might serve as an inline adapter for function. Like, you want to see which value in array is bigger than 1024. You wrap a comparison function into a lambda, passing it 1024 as one of parameters, and pass lambda to the foreach, for example.
Also it just saves you from having one liners like void ____internal____Function(int a) { return a + (int)Pi; } somewhere in your file that will inevitably get lost among normal functions that are much longer than that.
Also it can just be inlined and limited to only capture what you need.
In that sense it's equivalent to
int b = 42;
int c = 9;
/*Do something*/
{
int a = b;
...
}
But you can't "accidentally" insert c = a*a; in the body and break everything, if I understand correctly.
auto lambda = [=](int) {std::cout
OK,Thanks!@Peterolen
I want help cherno...I want classes I mean live face to face..guide me how I can get that from you
Join his discord: thecherno.com/discord
Cherno is born for C and C++
Wait, as i look at the handle of the window behind Cherno, it seems that window opens to outside.
Could you explain why find_if is any better than writing your own for loop. I know this is a simple example but some of the STL seems a bit superfluous
What problems this cpp feature solves ?? ...can we have a real life example for average programmer (some feature video) … I understand the concept, but what is the benefit for complicating the code (my not educated perspective)
A common place for this is when you are creating APIs projects, or something that should be used by others. I always picture functions that have functions's args as wrappers to focus on their core behaviour. Cherno used good examples of it.
For example, when you call a ForEach funcion, what do you really want to do? you want to anything with each element of a list. The function wraps the loop part and leaves to you only the part that matters, do something with each element.
Find_if function does the same. What do you want? for each element, you want to check if a certain condition is true (that's why bool return) and get the count of elements.
Both examples abstracts the repetitive stuff and leaves you with what really matters, a function (your lambda) with a specific behaviour that doesn't have to deal with anything else than the core functionality. It may be too much because these examples wraps less code, but in real life, you can wraps a lot of things