Home > other >  Why does not C Compare require an integer as its return value?
Why does not C Compare require an integer as its return value?

Time:06-23

According to C 's requirements of Compare, any Compare type function should return something that is true if the first arg is less than the second, otherwise false. This named requirement is used in many standard algorithms, e.g. std::sort, std::map, std::set, etc. However, many of them need to judge if two elements are "equal". As the reference says, the standard lib determines a == b iff !comp(a, b) && !comp(b, a). Obviously it needs twice the time to judge equivalence.

As we know, std::string::compare method returns an int value representing "less", "equal" and "greater" by negative value, zero value and positive value respectively. This seems to be a good idea to express the three possible relationships between two values in just one operation. So my question is, why doesn't the standard lib require Compare to return an integer value or any other type that is able to express at least 3 independent values?

CodePudding user response:

I believe it is because not all data types support the full semantics necessary to do a std::string::compare-style three-way comparison.

For example, take the float type. That seems like a pretty good candidate for a three-way-comparison, until you realize that there are "special" floating point values like NaN that are neither greater than nor less than nor equal to any other floating point value. It's not clear what a three-way-comparson function should return if one or both of its operands is NaN; OTOH the Compare function's expected behavior is clear: it should return false.

CodePudding user response:

Generally the algorithms are coded so you only need to know equivalence once, at the end. So requiring two calls instead of one is not an unreasonable burden.

Requiring only less-than with a bool result makes things simpler.

  • Related