Most efficient/elegant way to clip a number?

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

    Why rewrite something that's already been written for you?

    #include 
    boost::algorithm::clamp(n, lower, upper);
    

    As of C++17, this is now part of the STL:

    #include 
    std::clamp(n, lower, upper);
    

提交回复
热议问题