Monday, 1 May 2017

c++11 - C++ using inline function in std::sort




I've been learning C++ for a last few months.In C++ in order to pass a comparator in std::sort we can easily define a comparator function and pass it as argument to the sorting method.




bool myComp(Edge a, Edge b) { return a.wt > b.wt; }
std::sort(arr.begin(), arr.end(), myComp);


But i wonder whether there is some more elegant way to do the same thing so that i don't have to explicitly define another function for just one use. In Javascript i can do the same thing by just passing an anonymous function like this:



arr.sort(function(a, b) { return a.wt > b.wt; }); 


Is that kind of thing possible in C++ or C++11?



Answer



As has been discussed previously, lambdas do indeed exist in C++11: What is a lambda expression in C++11?


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...