Lambdas in C++

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 พ.ย. 2024

ความคิดเห็น • 239

  • @satyamraj2779
    @satyamraj2779 8 หลายเดือนก่อน +26

    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..

  • @dsedchenko
    @dsedchenko 5 ปีที่แล้ว +18

    The best cpp video tutorials I've ever seen, thank you!

  • @fishyperil2153
    @fishyperil2153 6 ปีที่แล้ว +322

    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.

    • @obabamaiu
      @obabamaiu 6 ปีที่แล้ว +18

      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.

    • @rj00a
      @rj00a 6 ปีที่แล้ว +67

      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

    • @goku14139268520
      @goku14139268520 6 ปีที่แล้ว +13

      This thread has been incredibly helpful. Thank you to both of you guys that offered an explanation.

    • @groberti
      @groberti 6 ปีที่แล้ว

      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.

    • @sachinnale1076
      @sachinnale1076 5 ปีที่แล้ว +14

      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;
      }

  • @chetannaik5199
    @chetannaik5199 3 ปีที่แล้ว +17

    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.

  • @jinyoungpark3277
    @jinyoungpark3277 6 ปีที่แล้ว +12

    THANK YOU SO MUCH for this video!! You made everything clear

  • @Rahulsingh-theraha
    @Rahulsingh-theraha ปีที่แล้ว

    honestly a great series for programmer who have past exp , did whole thing (till lambdas)in like 3-4 hrs and understood almost everything .

  • @jinshiro
    @jinshiro 4 ปีที่แล้ว +4

    Thanks for this, the learncpp section on this nearly cooked my headmeat.

  • @shadyganem5448
    @shadyganem5448 3 ปีที่แล้ว +18

    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.

  • @rcookie5128
    @rcookie5128 6 ปีที่แล้ว +6

    finally clearing up a topic I tried to avoid as it confused and overwhelmed me when I first saw it.. thanks!

    • @sakshigupta7616
      @sakshigupta7616 4 ปีที่แล้ว

      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 :)

    • @TravelingMooseMedia
      @TravelingMooseMedia 4 ปีที่แล้ว +2

      Sakshi Gupta bruh

  • @austinbryan6759
    @austinbryan6759 6 ปีที่แล้ว +15

    2:24 This is almost the exact case I was wanting to use this for, funny enough

  • @ToxicityGameDev
    @ToxicityGameDev 6 ปีที่แล้ว +8

    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!

  • @mrmrigank7154
    @mrmrigank7154 9 หลายเดือนก่อน

    best cpp and one of best programming channel ever

  • @aurinator
    @aurinator ปีที่แล้ว +8

    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.

    • @UsernameUsername0000
      @UsernameUsername0000 ปีที่แล้ว +3

      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.

  • @EezySeven
    @EezySeven 6 ปีที่แล้ว +270

    You should make a video on C++ iterators, dude.

    • @gvcallen
      @gvcallen 4 ปีที่แล้ว +1

      please!

    • @PflanzenChirurg
      @PflanzenChirurg 4 ปีที่แล้ว +16

      @@gvcallen he did today ;)

    • @nikos4677
      @nikos4677 4 หลายเดือนก่อน +1

      ok dude

    • @vk8a8
      @vk8a8 7 วันที่ผ่านมา

      NOOOOOOO

  • @svddwd
    @svddwd 5 ปีที่แล้ว +2

    Thank you so much.. I was not clear abot Lambas ever after reading so much.. You made it look so simple.

  • @shat104
    @shat104 5 ปีที่แล้ว +98

    Damn this guy is so good, must feel pretty good knowing that if you interviewed anywhere you can get the job.

    • @phagesuffersatgaming.3797
      @phagesuffersatgaming.3797 3 ปีที่แล้ว +4

      @Lance Adan this is a scam, don't touch, report those comments as spam instead.

    • @puppergump4117
      @puppergump4117 2 ปีที่แล้ว +4

      @Over Yonder What kind of idiot would put their business at risk just to screw over their workers?

    • @nakon7niket
      @nakon7niket 2 ปีที่แล้ว +2

      @@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.

  • @madhvishrivastava3646
    @madhvishrivastava3646 7 หลายเดือนก่อน

    Thank you for explaining that complex topic in a very simple way. A big thanks from India.😊

  • @Kazetomosuki
    @Kazetomosuki 3 ปีที่แล้ว +2

    Wow, this video in combination with the previous one about function pointers was an enlightenment to me! 😄🙏👏 Thank you!

  • @YoutubeFrogOfHell
    @YoutubeFrogOfHell 5 ปีที่แล้ว +21

    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

    • @levondarbinyan3934
      @levondarbinyan3934 21 วันที่ผ่านมา

      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.

  • @dimasveliz6745
    @dimasveliz6745 4 ปีที่แล้ว

    Thanks for the clarity of video! Especially for the second part that includes the functional thing!

  • @vegansynths7757
    @vegansynths7757 4 ปีที่แล้ว +2

    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. :)

  • @Arthur-xr5qf
    @Arthur-xr5qf 11 หลายเดือนก่อน +1

    "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

  • @clementboutaric3952
    @clementboutaric3952 6 ปีที่แล้ว +2

    The level of programming you have to possess to encounter situation in which such mechanics must be used is unfathomable.

    • @nutritionalyeast7978
      @nutritionalyeast7978 4 ปีที่แล้ว

      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

  • @GeekyMino
    @GeekyMino 6 ปีที่แล้ว +2

    Dude your channel is awesome! Your videos are super informative and useful. Keep up the good work :)

  • @shanielsamadhan979
    @shanielsamadhan979 6 ปีที่แล้ว +2

    Start the game engine series soooon please. I'm excited af!

  • @kelvin31272
    @kelvin31272 ปีที่แล้ว

    Thank you Cherno! Finally understand it

  • @WildGrowthJ
    @WildGrowthJ 3 หลายเดือนก่อน

    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.

  • @Inglonias
    @Inglonias 4 ปีที่แล้ว +1

    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.

  • @DawitBeza-nr1tn
    @DawitBeza-nr1tn 8 หลายเดือนก่อน +1

    you know the way you teach me is exactly the way i want to be tought

  • @vertigo6982
    @vertigo6982 5 ปีที่แล้ว

    One can never have too many function pointer, functor, and lambda videos.

  • @jianiliao7140
    @jianiliao7140 6 ปีที่แล้ว

    Thank you for making the video!

  • @pavliv
    @pavliv 9 หลายเดือนก่อน

    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.

  • @christianm4906
    @christianm4906 5 ปีที่แล้ว +2

    Man, you saved my day.

  • @samitkapoor53
    @samitkapoor53 4 ปีที่แล้ว

    Thank you, this was so helpful!!

  •  6 ปีที่แล้ว +36

    make video about constexpr and std::optional

    • @fishyperil2153
      @fishyperil2153 6 ปีที่แล้ว +4

      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

    • @peterarbeitsloser7819
      @peterarbeitsloser7819 3 ปีที่แล้ว

      @@fishyperil2153 totally agree

  • @tomdapchai
    @tomdapchai ปีที่แล้ว

    thank you

  • @murhafal-msri5479
    @murhafal-msri5479 2 ปีที่แล้ว +1

    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

  • @susiana5
    @susiana5 6 ปีที่แล้ว +1

    Thanks for uploading :D nice!

  • @ycombinator765
    @ycombinator765 2 ปีที่แล้ว +1

    at this point, I can only hear daughter instead of data. tbh. brilliant stuff

    • @toby9999
      @toby9999 ปีที่แล้ว

      Australian accent vs whatever your accent is.

  • @Muhammad_Abdullah_Sultan
    @Muhammad_Abdullah_Sultan 2 ปีที่แล้ว

    Thanks

  • @GamerSaga
    @GamerSaga 4 ปีที่แล้ว +4

    got to capture them all! [pokemon].

  • @alexsece
    @alexsece 5 ปีที่แล้ว

    Thank you!

  • @mryup6100
    @mryup6100 2 ปีที่แล้ว

    This content ► Amazing explanations

  • @oatmealduck7937
    @oatmealduck7937 4 ปีที่แล้ว

    These are so fun to watch man

  • @sankar9483
    @sankar9483 6 ปีที่แล้ว

    Thanks lot. Wonderful Video.

  • @Kapil_Thakar
    @Kapil_Thakar 2 ปีที่แล้ว

    u are my favorite, Amazing, u kept it very clear...

  • @joushuahung4996
    @joushuahung4996 4 ปีที่แล้ว

    Top quality tutorial, Thank you.

  • @m4l490n
    @m4l490n 4 ปีที่แล้ว +2

    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?

  • @joeporsche1767
    @joeporsche1767 3 ปีที่แล้ว

    You are the best for c++.

  • @ashutoshaswal
    @ashutoshaswal 4 ปีที่แล้ว

    THANKS

  • @toopkarcher
    @toopkarcher ปีที่แล้ว +1

    Soooooo a callback function

  • @achrafbahloul192
    @achrafbahloul192 3 ปีที่แล้ว

    so helpful thanks

  • @Gojam12
    @Gojam12 3 ปีที่แล้ว

    Your the sh** mr cherno, rock on brother

  • @DUFLEBIN
    @DUFLEBIN 6 ปีที่แล้ว +5

    Hey great playlist on c++. Can you make a video on iterators in c++?

  • @boody7665
    @boody7665 5 ปีที่แล้ว

    awesome , Thank you

  • @anthonyduran2627
    @anthonyduran2627 3 ปีที่แล้ว

    bless yo intelligent, puzzle solving soul

  • @ahmedanwar976
    @ahmedanwar976 5 ปีที่แล้ว

    Thanks man

  • @dani-z3n1th
    @dani-z3n1th 2 ปีที่แล้ว

    nice couch you got there.

  • @ashutosh108
    @ashutosh108 6 ปีที่แล้ว +6

    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).

    • @TheCherno
      @TheCherno  6 ปีที่แล้ว +2

      Added, thank you! :)

  • @AbhishekKr1902
    @AbhishekKr1902 6 ปีที่แล้ว

    The best tutorial on the internet!

  • @asajjad4542
    @asajjad4542 4 ปีที่แล้ว

    You're amazing!

  • @reubenfrench6288
    @reubenfrench6288 6 ปีที่แล้ว +1

    Function objects. You said in the last video you were going to make a video on function objects.

  • @mangrubengaming4300
    @mangrubengaming4300 4 ปีที่แล้ว

    You really know what you're doing. You're so good. Do you have a video about ECS?

  • @chyldstudios
    @chyldstudios 6 ปีที่แล้ว +1

    do more c++ videos on functional programming

  • @michaelwplde
    @michaelwplde 4 ปีที่แล้ว

    5:00 When I need that I use it ALL THE TIME.

  • @GenericPhantom1
    @GenericPhantom1 ปีที่แล้ว

    A lambda is an anonymous function. A way for us to make a function without having to physically make one.

  • @ben-nh9sn
    @ben-nh9sn 5 หลายเดือนก่อน

    A God amongst men.

  • @casperes0912
    @casperes0912 3 ปีที่แล้ว +2

    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

  • @LeSaboteur3981
    @LeSaboteur3981 4 ปีที่แล้ว

    great, helps a lot!

  • @abhishekchavhan3768
    @abhishekchavhan3768 ปีที่แล้ว

    Amazing

  • @SuperSaiyan-tr7fz
    @SuperSaiyan-tr7fz 2 ปีที่แล้ว

    Apart from Asthetics what is the main advantage of using a lambda over a normal function.

  • @TiramisuCorleone
    @TiramisuCorleone 4 ปีที่แล้ว

    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

    • @jonf6509
      @jonf6509 4 ปีที่แล้ว

      which book? Hes got a newer one...

  • @HousseinAlDroubi
    @HousseinAlDroubi 3 หลายเดือนก่อน

    Hey, good man what about you ?
    Welcome to you.

  • @Codeaholic1
    @Codeaholic1 5 ปีที่แล้ว

    Great video. The couch made me laugh.

  • @omarahmedwassel5203
    @omarahmedwassel5203 5 ปีที่แล้ว

    Wow....... thanks a lot ,from egypt .

  • @usman8872
    @usman8872 ปีที่แล้ว

    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.

  • @nitinbindal6617
    @nitinbindal6617 3 ปีที่แล้ว

    How to pass by const reference in lambdas ? Which might be useful when you pass large objects in lambdas

  • @priyadarshini.d4980
    @priyadarshini.d4980 2 ปีที่แล้ว

    hey.. thanks for all these videos on C++.. Could u also make a video on Functors in C++?

  • @jannesopanen8032
    @jannesopanen8032 3 ปีที่แล้ว

    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... :(

  • @hidemat5141
    @hidemat5141 2 ปีที่แล้ว +1

    What about defining a lambda within a custom class and you want to use the members of that class in you lambda?

    • @juliangomez4631
      @juliangomez4631 2 ปีที่แล้ว +1

      You can capture the "this" pointer

  • @jeevanreddy7989
    @jeevanreddy7989 5 ปีที่แล้ว +1

    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?

  • @chriswhisker
    @chriswhisker 5 หลายเดือนก่อน

    What's the difference between capturing by reference and using "mutable" when capturing by copy?

  • @alexandergonzalez5975
    @alexandergonzalez5975 6 ปีที่แล้ว +2

    Please make a sophisticated course with some sort of company talking about algorithms/data structures, and sell it to us that would be amazing.

  • @informativecontent4778
    @informativecontent4778 6 ปีที่แล้ว

    U r love

  • @jayayson8549
    @jayayson8549 5 ปีที่แล้ว +1

    0:00 Chris? is that you?

  • @novictim
    @novictim 3 ปีที่แล้ว

    *googles lambda c++*
    *presses video*
    *finds out it is THE CHERNO 🥰😘😘😘🥰🥰🥰🥰🥰🥰🥰🥰🥰🥰*

    • @computerprogrammer7942
      @computerprogrammer7942 3 ปีที่แล้ว

      The same reaction when you realise that I’m commenting on your comment

  • @KNT_19
    @KNT_19 3 ปีที่แล้ว

    Can you please make video explaining the basic differences between function pointer and lamdas?

  • @peterkolarov2890
    @peterkolarov2890 3 ปีที่แล้ว

    Thank you ! By the way "Cherno" in bulgarian means "Black" :) (the same pronanciation)

  • @weirongwu4964
    @weirongwu4964 4 ปีที่แล้ว

    Lambdas in C++ ~ Event Listeners in Java

  • @alwinshoots
    @alwinshoots 3 ปีที่แล้ว

    So [] in c++ lambdas are somewhat like closures in JavaScript

  • @MichaelYoussry
    @MichaelYoussry 6 ปีที่แล้ว

    Idea for next video:
    Advanced templates

  • @devashish0312
    @devashish0312 6 ปีที่แล้ว +17

    how did you got into EA?

    • @bellajbadr
      @bellajbadr 6 ปีที่แล้ว +18

      by playing Fifa -_-

    • @Pajutzo
      @Pajutzo 6 ปีที่แล้ว +5

      Here its explained: th-cam.com/video/ykjtuSkt9g8/w-d-xo.htmlm53s

    • @victornnah3920
      @victornnah3920 6 ปีที่แล้ว +7

      That type of English can't get you into EA m8. just saying.

    • @devashish0312
      @devashish0312 6 ปีที่แล้ว

      Luftwafte I what's wrong with my English?

    • @finnelhumano6096
      @finnelhumano6096 6 ปีที่แล้ว +7

      got instead get. Don't mind him though, your english is fine.

  • @denischikita
    @denischikita 3 ปีที่แล้ว

    hardest video so far

  • @mrprofile101
    @mrprofile101 9 หลายเดือนก่อน

    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?

    • @zhulikkulik
      @zhulikkulik 9 หลายเดือนก่อน +1

      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.

  • @周绍阳-y9z
    @周绍阳-y9z 4 ปีที่แล้ว

    auto lambda = [=](int) {std::cout

  • @chinmayanand896
    @chinmayanand896 6 ปีที่แล้ว +2

    I want help cherno...I want classes I mean live face to face..guide me how I can get that from you

    • @emilamenda9649
      @emilamenda9649 6 ปีที่แล้ว

      Join his discord: thecherno.com/discord

  • @yadavdhakal2044
    @yadavdhakal2044 5 ปีที่แล้ว

    Cherno is born for C and C++

  • @bulentgercek
    @bulentgercek 4 ปีที่แล้ว

    Wait, as i look at the handle of the window behind Cherno, it seems that window opens to outside.

  • @DrGreenGiant
    @DrGreenGiant 5 ปีที่แล้ว

    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

  • @laureven
    @laureven 3 ปีที่แล้ว

    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)

    • @andrefaustino5514
      @andrefaustino5514 2 ปีที่แล้ว +1

      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