Most efficient/elegant way to clip a number?

前端 未结 11 724
予麋鹿
予麋鹿 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:46

    What about boring, old, readable, and shortest yet:

    float clip(float n, float lower, float upper) {
      return std::max(lower, std::min(n, upper));
    }
    

    ?

    This expression could also be 'genericized' like so:

    template 
    T clip(const T& n, const T& lower, const T& upper) {
      return std::max(lower, std::min(n, upper));
    }
    

    Update

    Billy ONeal added:

    Note that on windows you might have to define NOMINMAX because they define min and max macros which conflict

提交回复
热议问题