为什么不c++比较需要整数作为返回值?
如我们所知,std :: string ::比较
方法返回int
值代表“少”,“等于”和“较大”和“较大”,按负值,零值和正面值价值分别。这似乎是一个好主意,即仅在一个操作中表达两个值之间的三个可能的关系。因此,我的问题是,为什么标准lib不需要比较
返回整数值或任何其他能够至少表达3个独立值的类型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这是因为并非所有数据类型都支持执行
std :: String ::比较
风格的三路比较所需的完整语义。例如,以
float
类型。这似乎是三路繁殖的一个很好的候选人,直到您意识到有“特殊”的浮点值,例如nan
都不大于也不等于或等于任何其他浮动点值。目前尚不清楚如果一个或两个操作数是nan
,则应返回三向相比的功能; OTOH比较
函数的预期行为很明确:它应该返回false。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 likeNaN
that are neither greater than nor less than nor equal to any other floating point value. It's not clear what a three-way-comparison function should return if one or both of its operands isNaN
; OTOH theCompare
function's expected behavior is clear: it should return false.通常,对算法进行了编码,因此您只需要知道一次等价。因此,需要两个电话而不是一个电话并不是一个不合理的负担。
仅需<代码> bool 结果就需要少的结果使事情变得更简单。
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.