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)
.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With