Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort with a lambda?

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b)
{ 
    return a.mProperty > b.mProperty; 
});

I'd like to use a lambda function to sort custom classes in place of binding an instance method. However, the code above yields the error:

error C2564: 'const char *' : a function-style conversion to a built-in type can only take one argument

It works fine with boost::bind(&MyApp::myMethod, this, _1, _2).

like image 636
BTR Avatar asked Sep 28 '22 15:09

BTR


People also ask

How do I sort a list of dictionaries by value?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

How do you create a sort function in Python?

The syntax of the sort() method is: list. sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.


2 Answers

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

like image 222
BTR Avatar answered Oct 10 '22 04:10

BTR


You can use it like this:

#include<array>
#include<functional>
using namespace std;
int main()
{
    array<int, 10> arr = { 1,2,3,4,5,6,7,8,9 };

    sort(begin(arr), 
         end(arr), 
         [](int a, int b) {return a > b; });

    for (auto item : arr)
      cout << item << " ";

    return 0;
}
like image 33
Adrian Avatar answered Oct 10 '22 03:10

Adrian