替代 C++11 的 std::nextafter 和 std::nexttowards for C++03?
Alternative to C++11's std::nextafter and std::nexttoward for C++03?
正如标题所说,我所追求的功能是由c++ 11的数学库提供的,用于查找特定值的下一个浮点值。
除了从std库中提取代码(我可能不得不诉诸于此)之外,还有其他方法可以使用c++ 03(使用GCC 4.4.6)来完成此操作吗?
与平台相关,假设IEEE754,并且端序模,您可以将浮点数的数据存储在整数中,递增1,并检索结果:
float input = 3.15;
uint32_t tmp;
unsigned char * p = reinterpret_cast<unsigned char *>(&tmp);
unsigned char * q = reinterpret_cast<unsigned char *>(&input);
p[0] = q[0]; p[1] = q[1]; p[2] = q[2]; p[3] = q[3]; // endianness?!
++tmp;
q[0] = p[0]; q[1] = p[1]; q[2] = p[2]; q[3] = p[3];
return input;
当然要小心零、nan和无穷大。
我意识到这个答案很晚了,但是当我需要非常类似的解决方案时,我偶然发现了这个解决方案,因此为了完整性,我认为应该在这里包括它。在c++ 11中,上述api位于'std'命名空间中。在此之前,只需从math.h:
中删除'std'命名空间限定符 double nextafter (double x , double y);
float nextafterf (float x , float y);
long double nextafterl (long double x, long double y);
虽然我没有GCC4.4.6来验证,但这确实适用于我在一个不支持c++ 11的旧编译器上。
相关文章:
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- std::memory_order for std::atomic:<T>:wait
- 在基于范围的 for 循环期间插入 std::list 的后面
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 运算符 << 操作加载的 API for std::endl?
- google test PrintTo for std::set<std::string>
- std::memcpy vs std::copy_n for legacy c structs
- C++11 基于范围的 for 循环,用于 std::list
- For-loop或std::any_of,我应该使用哪一个?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- std::hash for std::chrono::duration
- 如何修复以下错误"no match for call to '(std::tr1::shared_ptr<_iobuf*>) (FILE*&)'"
- 访问类的 std::vector 与 for 循环中的 custum 类对象
- Hash for a std::pair, for use in an unordered_map
- 计算使用 C++ std 函数而不是 for 循环的大 O
- 使用 OpenMP 在并行 for 循环中使用 std::cout
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- C++ SFINAE : is_constructible for const char[] vs std::strin
- 使用 std::min "no matching function for call to ‘min(<brace-enclosed initializer list>)’"时出错
- 类型安全 - all_of/ any_of/ none_of for std::tuple