In C# given a struct:
struct Point {int x, int y}
We can write something like:
List<Point> list;
list.OrderBy(p => p.x).ThenBy(q => q.y);
How can I express this logic in C++ using lambda functions?
It looks too me like you want a lexicographic sort on (y, x)
1. You can leverage the library function std::tie
. That one returns a tuple of references, and a std::tuple
has a less-than operator which performs lexicographic comparison. So you only need to specify the order in which you want the items compared.
Here's how it would look for std::vector
(your go to container type in C++, always start with std::vector
):
std::vector<Point> my_list;
// Fill my_list
std::sort(begin(my_list), end(my_list), [](auto const& l, auto const& r){
return std::tie(l.y, l.x) < std::tie(r.y, r.x);
});
1 - I'm basing this on the method names only, so this may not be what you are really after.
You can use STL function std::sort. Example:
struct point{
int x;
int y;
};
// Compare function. This can be lambda function too.
bool comp(const point& a,const point& b){
if(a.x > b.x) return true;
else if(a.x == b.x) return a.y > b.y;
return false;
}
int main(){
// v is vector (or any other container which can be iterated) containing points
std::sort(v.begin(),v.end(),comp);
}
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