Jinchul
Jinchul

Reputation: 39

why does the equivalent condition necessary?

I have a question on the code piece from C++ standard library. My question is that !(p2.lastname() < p1.lastname()) seems not to be necessary because I think the condition represents the last names are in p1 and p2 equivalent. If I removed the condition, the code seems to work properly. I saw this strict weak ordering. I read the relevant article but I did not fully understand the concept. Would you please explain why the condition is required?

class Person {
public:
  string firstname() const;
  string lastname() const;
};

class PersonSortCriterion {
public:
  bool operator() (const Person& p1, const Person& p2) const {
    // 1) Compare the lastnames.
    // 2) If the lastnames are equivalent, compare the firstnames.
    return p1.lastname() < p2.lastname() ||
       (!(p2.lastname() < p1.lastname()) &&
          p1.firstname() < p2.firstname());
  }
};

Upvotes: 1

Views: 52

Answers (1)

john
john

Reputation: 87932

So I think you are saying that the following is OK

return p1.lastname() < p2.lastname() ||
      p1.firstname() < p2.firstname());

but that is incorrect. Consider two people "Andy Zerkis" and "Zebedee Archer". Using the code above both AZ < ZA and ZA < AZ. So both names are less than the other one. Not surprisingly this will confuse sorting algorithms. Another way of saying this is that the code above does not impose a strict weak ordering. In particular it breaks the rule that it cannot be that case that both x < y and y < x are true.

Strict weak ordering seems confusing if you aren't familiar with it, but really it just says the obvious things you would expect from any sorting criterion.

Upvotes: 3

Related Questions