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?
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);
}
Two ways - either you sort twice, first by y, then use a stable sort on x (be aware that this is exactly inverse as in C#!). Bad luck with std::sort
, though, as it is not stable, fortunately, as Benjamin hinted to, there is std::stable_sort
, too...
The other way is making sure that two points compare such that a difference in x applies first and only in case of equality, y is considered:
std::sort
(
// range to sort
list.begin(), list.end(),
// next the comparator - you wanted a lambda? OK, here it is:
[](point const& a, point const& b)
{
return a.x < b.x || a.x == b.x && a.y < b.y;
}
);
You just need to specify the lambda function to std::list::sort()
.You decide how you want to sort.
list.sort([](Point i,Point j)
{
if(i.x!=j.x)
return i.x<j.x;
else
return i.y<j.y;
}
);