为什么不c++比较需要整数作为返回值?

发布于 2025-02-10 00:00:19 字数 629 浏览 1 评论 0原文

根据 c ++比较的要求类型函数应返回true的内容,如果第一个ARG小于第二个,则false。此命名要求在许多标准算法中使用,例如std :: Sortstd :: mapstd :: set等。但是,他们中的许多人需要判断两个要素是否“平等”。如引用所述,标准lib确定a == b iff !comp(a,b)&& !comp(b,a)。显然,它需要两倍的时间来判断等价。

如我们所知,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天生の放荡 2025-02-17 00:00:19

我相信这是因为并非所有数据类型都支持执行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 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-comparison 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.

白衬杉格子梦 2025-02-17 00:00:19

通常,对算法进行了编码,因此您只需要知道一次等价。因此,需要两个电话而不是一个电话并不是一个不合理的负担。

仅需<代码> 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文