Suppose I have some value:
double x;
and I want to confine it to some range [a, b]
such that the resulting value is within that range:
double confine(double x, double a, double b)
{
if (x < a) return a;
else if (x > b) return b;
return x;
}
Is there a single boost
or STL function that can do this for me?
Yes, Boost Algorithm has clamp
:
double clamped = clamp(x, a, b);
It requires only operator<
or a custom comparator, and guarantees that it is called only once or twice. The documentation points out that with double
and other floating-point types, NaN could cause unexpected results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With