1

I am wondering how does a lambda expression take its arguments?

Usually, when we pass variables into parameters, we need to match the number of arguments and number of variables. for example, for regular function void foo(int a, int b) we need to pass two int variables to the functions.

However, with lambda expression we don't need to do it. for example:

sort(intContainer.begin(), intContainer.end(), [](int i, int j){return i>j;});

This function will sort the container in descending order.

I am wondering how the lambda expression takes int j argument. (when I assume that one iterator holds one int value taking variable for int i is makes sense) does it related with the way how an iterator works??

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 5
    I think you are asking about the details of `std::sort` more than _lambdas_. The "comparison object" passed to `std::sort` does not have to be a lambda. It could be a function, or anything that satifies the [compare predicate](https://en.cppreference.com/w/cpp/named_req/Compare). – Drew Dormann Sep 09 '21 at 19:35
  • 1
    A lambda expression is an abbreviated way to create a functor. Very related/maybe dupe: https://stackoverflow.com/questions/356950/what-are-c-functors-and-their-uses – NathanOliver Sep 09 '21 at 19:36
  • 4
    You seem to think that the lambda is called with one argument here? Why is that? It's not called in the line you're showing us; `std::sort` calls it internally (with two arguments). – HolyBlackCat Sep 09 '21 at 19:40
  • You can use https://cppinsights.io/ to see how a lambda looks: [here is yours](https://cppinsights.io/lnk?code=aW50IG1haW4oKSB7CiAgICBhdXRvIGNvbXAgPSBbXShpbnQgaSwgaW50IGopIHsgcmV0dXJuIGkgPiBqOyB9Owp9&std=cpp17&rev=1.0) – Ted Lyngmo Sep 09 '21 at 19:41
  • 1
    _"How does std::sort provide the two parameters that are passed to my lambda?"_ Is that a valid rephrasing of what your question is? – Drew Dormann Sep 09 '21 at 19:58

0 Answers0