Most efficient/elegant way to clip a number?

前端 未结 11 773
予麋鹿
予麋鹿 2020-11-30 03:09

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lo

11条回答
  •  忘掉有多难
    2020-11-30 03:21

    The following header file should work for C and C++. Note that it undefines min and max if the macros are already defined:

    #pragma once
    
    #ifdef min
    #undef min
    #endif
    
    #ifdef max
    #undef max
    #endif
    
    #ifdef __cplusplus
    #include 
    
    template 
    T clip(T in, T low, T high)
    {
        return std::min(std::max(in, low), high);
    }
    #else /* !__cplusplus */
    #define min(a, b) (((a) < (b)) ? (a) : (b))
    #define max(a, b) (((a) < (b)) ? (b) : (a))
    #define clip(a, b, c) min(max((a), (b)), (c))
    #endif /* __cplusplus */
    

提交回复
热议问题