相关疑难解决方法(0)

Do std::min(0.0, 1.0) and std::max(0.0, 1.0) yield undefined behavior?

The question is pretty clear. The following gives the reason why I think these expressions might yield undefined behavior. I would like to know whether my reasoning is right or wrong and why.

Short read:

(IEEE 754) double is not Cpp17LessThanComparable since < is not a strict weak ordering relation due to NaN. Therefore, the Requires elements of std::min<double> and std::max<double> are violated.

Long read:

All references follow n4800. Specifications of std::min and std::max are given …

c++ floating-point undefined-behavior c++-standard-library language-lawyer

50
推荐指数
2
解决办法
1287
查看次数

为什么Release/Debug对std :: min有不同的结果?

这是测试程序:

void testFunc()
{
    double maxValue = DBL_MAX;
    double slope = std::numeric_limits<double>::quiet_NaN();

    std::cout << "slope is " << slope << std::endl;
    std::cout << "maxThreshold is " << maxValue << std::endl;
    std::cout << "the_min is " << std::min( slope, maxValue) << std::endl;
    std::cout << "the_min is " << std::min( DBL_MAX, std::numeric_limits<double>::quiet_NaN()) << std::endl;
}

int main( int argc, char* argv[] )
{
    testFunc();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Debug中,我得到:

slope is nan
maxThreshold is 1.79769e+308
the_min is nan
the_min is 1.79769e+308
Run Code Online (Sandbox Code Playgroud)

在发布中,我得到:

slope …
Run Code Online (Sandbox Code Playgroud)

c++ nan min floating-point-comparison

41
推荐指数
3
解决办法
3263
查看次数

NaN是关联容器的有效键值吗?

考虑C++中有序和无序的关联容器double.

NaN有效的密钥类型吗?

对于有序的容器,我应该说"不",因为它不尊重严格的弱排序.

对于无序容器,我不知道.

以下是GCC 4.6.2中发生的情况:

#include <map>
#include <unordered_map>

#include <cmath>

#include <iostream>
#include <prettyprint.hpp>

int main()
{
  typedef std::map<double, int> map_type; // replace by "unorderd_map"

  map_type dm;
  double d = std::acos(5); // a good nan

  dm[d] = 2;
  dm[d] = 5;
  dm[d] = 7;

  std::cout << "dm[NaN] = " << dm[d] << ", dm = " << dm << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

对于有序地图,我得到:

dm[NaN] = 7, dm = [(nan, 7)]
Run Code Online (Sandbox Code Playgroud)

对于无序地图,我得到:

dm[NaN] = 0, dm …
Run Code Online (Sandbox Code Playgroud)

c++ unordered-map map nan

27
推荐指数
2
解决办法
1600
查看次数