2

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();
    });

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();
    });

1 Comment

It will cover undefined behavior, but it wouldn't be consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.