Boost logo

Boost :

From: Hervé Brönnimann (hbr_at_[hidden])
Date: 2006-01-16 22:15:01


On Jan 16, 2006, at 3:18 AM, Vladislav Lazarenko wrote:
> Is there any library to do thing like this more easily?
> As a result, we will have rating in range 0-5.
> [code]
> int x = -10;
> int rating = std::max(std::min(x, 5), 0);
> [/code]

You want to "clip" a value to a range. The code you are describing
seems fine for this purpose. It's hard to imagine something more
easy, apart from a dedicated functor. If you'd have to do it a lot,
you probably would program your own functor:

template <class T>
struct enforce_minmax {
   enforce_minmax(T low, T high) : m_low(low), m_high(high) {}
   T operator()(const T& x) const { return std::max(std::min(x,high),
low); }
   T m_low, m_high;
};

Your code would be rewritten:

enforce_minmax<int> enforce(0, 5);
int rating = enforce(x);

The advantage is to apply to a collection, as in:

std::transform( v.begin(), v.end(), v.begin(), enforce_minmax<int>
(0,5) );

> I looked at the minmax library, but looks like there is not such
> function :-? Maybe I am looking in a wrong way?

That is not the purpose of the minmax library, but if it is widely
useful (and it seems it might be) I'd be happy to add it in.

--
Hervé Brönnimann
CIS, Polytechnic University
hbr_at_[hidden]

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk