Most efficient/elegant way to clip a number?

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

    UPDATE: C++17's header added std::clamp(value, low, high).

    In older C++ versions, I'd very rarely go beyond...

    return n <= lower ? lower : n >= upper ? upper : n;
    

    ...or, if you find it more readable keeping the left-to-right ordering of lower, n and upper...

    return n <= lower ? lower : n <= upper ? n : upper;
    

    (using <= lower is better than < lower because when n == lower it avoids having to compare with upper)

    If you know you might have them, you'd want to check if NaN / Inf etc. are preserved....

    I say rarely and not never just because sometimes less branching can be faster, but you'd sure want to profile it and prove it helped and mattered....

提交回复
热议问题