
Is there any library to do thing like this more easily? [code] int x = -10; int rating = std::max(std::min(x, 5), 0); [/code] As a result, we will have rating in range 0-5. I looked at the minmax library, but looks like there is not such function :-? Maybe I am looking in a wrong way? Thanks in advance, Vladislav Lazarenko.

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@poly.edu

Hi,
From: Vladislav Lazarenko
Is there any library to do thing like this more easily?
[code]
int x = -10; int rating = std::max(std::min(x, 5), 0);
[/code]
Not yet, but I'm working (slowly, I admit :P) on a constrained types library. With this library it would be as easy as: saturating_int<int, 0, 5>::type rating; rating = -10; // clips the value to 0 rating = 10; // clips the value to 5 Recently I've found some time to continue working on the library and am writing the documentation, but I can't tell whether and when the library will be accepted as a Boost library. This can take some time since there's still some work to do. Therefore if you need the feature urgently you shouldn't count on soon availability of the library. Best regards, Robert
participants (3)
-
Hervé Brönnimann
-
Robert Kawulak
-
Vladislav Lazarenko