Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by and then in c++ using lambda functions

Tags:

c++

lambda

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?

like image 884
John Tan Avatar asked Sep 19 '25 08:09

John Tan


2 Answers

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.

like image 199
StoryTeller - Unslander Monica Avatar answered Sep 22 '25 01:09

StoryTeller - Unslander Monica


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);
}
like image 43
Mayank Jain Avatar answered Sep 22 '25 02:09

Mayank Jain