简体   繁体   English

NaN 上的宇宙飞船算子

[英]Spaceship Operator on NaN

How does C++ treat floating-point NaN when doing space-ship comparison operations? C++在做飞船比较运算时如何处理浮点NaN? We know that the usual compares always return false, so how does this change with NaN?我们知道通常的比较总是返回 false,那么这对 NaN 有什么影响呢?

std::numeric_limits<double>::quiet_NaN() <=> std::numeric_limits<double>::quiet_NaN()

According to cppreference , in the case of floating point arguments to the built-in <=> operator:根据cppreference ,在浮点 arguments 到内置<=>运算符的情况下:

[...] the operator yields a prvalue of type std::partial_ordering . [...] 运算符产生std::partial_ordering类型的纯右值。 The expression a <=> b yields表达式a <=> b产生

  • std::partial_ordering::less if a is less than b std::partial_ordering::less如果a小于b
  • std::partial_ordering::greater if a is greater than b如果 a 大于b ,则std::partial_ordering::greater
  • std::partial_ordering::equivalent if a is equivalent to b ( -0 <=> +0 is equivalent) std::partial_ordering::equivalent如果a等价于b ( -0 <=> +0等价)
  • std::partial_ordering::unordered (NaN <=> anything is unordered) std::partial_ordering::unordered (NaN <=>任何东西都是无序的)

So, in brief, applying <=> to a floating point value of NaN results in std::partial_ordering::unordered .因此,简而言之,将<=>应用于 NaN 的浮点值会导致std::partial_ordering::unordered

When evaluating an expression like a <=> b == 0 or a <=> b < 0 , if either a or b is NaN then the whole expression returns false , which makes sense coming from NaN's built-in behaviour ( source ).在评估像a <=> b == 0a <=> b < 0这样的表达式时,如果ab是 NaN,则整个表达式返回false ,这从 NaN 的内置行为( source )中是有意义的。 Of course, std::partial_ordering::unordered == std::partial_ordering::unordered holds true or else this type wouldn't be very useful.当然, std::partial_ordering::unordered == std::partial_ordering::unordered成立,否则这种类型不会很有用。

If you can otherwise guarantee the absence of pathological floating point values, take a look at this Q/A for a floating point wrapper whose comparisons yield std::strong_ordering .如果您可以以其他方式保证不存在病态浮点值,请查看此 Q/A以获得浮点包装器,其比较产生std::strong_ordering

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM