Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- From: David Wilkinson <no-reply@xxxxxxxxxxxx>
- Date: Tue, 27 Feb 2007 05:15:48 -0500
Harvey wrote:
On Feb 25, 11:57 pm, "Harvey" <harve...@xxxxxxxx> wrote:
Is there a (mfc) library function like f(lb,x,ub); that will return
the value of x if it is in range, else the bound x exceeded? It would
be equivalent to min(ub,max(lb,x)); but faster and not a macro? I
think I would use it a lot. :)
TIA,
Harvey
Final version:
template <typename T>
T Clamp( T lower, T x, T upper )
{
if ( lower > x )
return lower;
if ( x > upper )
return upper;
return x;
}
I used > for both rather than < so that the flow would follow the
input args.
Thanks to all who commented.
Harvey
Harvey:
Not to beat a dead horse, but I would still follow what the standard library does for min() and max(): use < only and const T&.
The reason to use < is because that is what many standard library algorithms (like std::sort()) require to be defined. If you use > you are placing a requirement on your class that is not required by the standard library.
The reason to use const T& is that it will be much more efficient for a complex type, particularly one that requires memory allocation in the copy constructor. I would need detailed evidence that using T is more efficient for simple types, and even if it was it would be extremely unusual for it to really matter.
The standard library folks must have thought about these things before they defined and implemented min() and max() the way they did.
David Wilkinson
.
- Follow-Ups:
- Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- From: Doug Harrison [MVP]
- Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- From: MrAsm
- Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- References:
- Prev by Date: Re: Redrawing question
- Next by Date: Enhanced CIPAddressCtrl
- Previous by thread: Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- Next by thread: Re: Function f(lb,x,ub); equivalent to min(ub,max(lb,x)); ?
- Index(es):
Relevant Pages
|