【问题标题】:How to find the next greater value generically in C++ for integers and floats?如何在 C++ 中为整数和浮点数找到下一个更大的值?
【发布时间】:2020-05-12 16:28:22
【问题描述】:

我天真地尝试过

template<typename T>
void foo(T a, T b){
   if(min==max){
      max += std::numeric_limits<T>::epsilon();
   }
   // Do some other stuff
}

但是我发现 epsilon 为整数类型返回 0 而不是 1,这似乎是一个疏忽。如何解决上述问题,包括整数?

【问题讨论】:

  • 对于整数max,下一个更大的值是max+1。在执行此操作之前,请检查 max 是否已经不是最大可表示值。

标签: c++ c++11 numbers numeric-limits


【解决方案1】:

例如:

template<typename T>
T next(T v) {
    if constexpr (std::is_integral_v<T>) {
        return v + 1;
    } else {
        return std::nextafter(v, std::numeric_limits<T>::infinity);   
    }
}

如果您没有if constexpr,请改用重载或模板特化。


max += std::numeric_limits<T>::epsilon();

对于许多浮点值,v + epsilon == v。对于许多其他值,它将跳过邻居。

【讨论】:

  • C++11 没有 constexpr if 对不起!!虽然这是一个很好的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 2014-02-27
  • 2014-10-23
  • 2011-08-07
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
相关资源
最近更新 更多