Eken
Eken

Reputation: 79

Sort Lambda Expression C++ by two condition

I am trying to sort data which I have in list. And I need that kind of sort

if a>b sort by a,b
else if a==b sort by c,d

I done this by it is not working.

l_name->sort([](type*& s1, type*& s2)
    {
    if (s1->a() > s2->b())
    return s1->a() > s2->b()
    else if(s1->a() == s2->b())
    return s1->c() > s2->d();
    });

Upvotes: 2

Views: 756

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

You cannot sort with a comparison function like that, because the sorting rules it defines are internally inconsistent. In order to sort, X < Y must imply that Y < X is false.

Consider these two objects:

Name a b
---- - -
X    2 1
Y    2 1

No matter how you compare them, X > Y or Y > X, you would get true, because X.a > Y.b and Y.a > X.b.

Even X > X and Y > Y would produce true, which must never happen.

For that reason, you should define your comparison rules in terms of comparing the same attributes. Otherwise, you will break reflexivity and transitivity rules.

Upvotes: 2

Vittorio Romeo
Vittorio Romeo

Reputation: 93294

What if a < b? You can solve this problem more robustly and concisely:

l_name->sort([](type*& s1, type*& s2)
    {
        if (s1->a() != s2->b())
            return s1->a() < s2->b();

         return s1->c() < s2->d();
    });

Upvotes: 1

Related Questions