0

I was checking an answer to a question posted on stackoverflow:

Answer to: C++, Sort One Vector Based On Another One

The answer has this piece of code:

std::sort(people.begin(), people.end(), 
               [](const auto& i, const auto& j) { return i.Score < j.Score; } );

I just want to understand why "[]" is put before the function here.

Thanks!

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • This is really a lambda, which is not exactly like a function. And `[]` Is used for captures; Lambdas can "capture" outside variables/references to outside variables and use them in the function definition. It's optional though, and in this case, the answerer chose to leave out captures because they weren't needed. – mediocrevegetable1 Feb 12 '21 at 13:06
  • `[](){}` part is basically an anonymous function. – Aykhan Hagverdili Feb 12 '21 at 13:10
  • imho it is amazing that `[](){}();` is now valid c++ syntax, especially if you consider how much code was necessary to achieve the same without a lambda expression – 463035818_is_not_an_ai Feb 12 '21 at 13:13

0 Answers0