1[/ QuickBook Document version 1.5 ] 2[section:clamp clamp] 3 4[/license 5 6Copyright (c) 2010-2012 Marshall Clow 7 8Distributed under the Boost Software License, Version 1.0. 9(See accompanying file LICENSE_1_0.txt or copy at 10http://www.boost.org/LICENSE_1_0.txt) 11 12] 13 14 15The header file clamp.hpp contains two functions for "clamping" a value between a pair of boundary values. 16 17[heading clamp] 18 19The function `clamp (v, lo, hi)` returns: 20 21* lo if v < lo 22* hi if hi < v 23* otherwise, v 24 25Note: using `clamp` with floating point numbers may give unexpected results if one of the values is `NaN`. 26 27There is also a version that allows the caller to specify a comparison predicate to use instead of `operator <`. 28 29`` 30template<typename T> 31const T& clamp ( const T& val, const T& lo, const T& hi ); 32 33template<typename T, typename Pred> 34const T& clamp ( const T& val, const T& lo, const T& hi, Pred p ); 35`` 36 37The following code: `` 38 int foo = 23; 39 foo = clamp ( foo, 1, 10 ); 40`` 41will leave `foo` with a value of 10 42 43Complexity: 44 `clamp` will make either one or two calls to the comparison predicate before returning one of the three parameters. 45 46[heading clamp_range] 47There are also four range-based versions of clamp, that apply clamping to a series of values. You could write them yourself with std::transform and bind, like this: `std::transform ( first, last, out, bind ( clamp ( _1, lo, hi )))`, but they are provided here for your convenience. 48 49`` 50template<typename InputIterator, typename OutputIterator> 51OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out, 52 typename std::iterator_traits<InputIterator>::value_type lo, 53 typename std::iterator_traits<InputIterator>::value_type hi ); 54 55template<typename Range, typename OutputIterator> 56OutputIterator clamp_range ( const Range &r, OutputIterator out, 57 typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type lo, 58 typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type hi ); 59 60template<typename InputIterator, typename OutputIterator, typename Pred> 61OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out, 62 typename std::iterator_traits<InputIterator>::value_type lo, 63 typename std::iterator_traits<InputIterator>::value_type hi, Pred p ); 64 65template<typename Range, typename OutputIterator, typename Pred> 66OutputIterator clamp_range ( const Range &r, OutputIterator out, 67 typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type lo, 68 typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type hi, 69 Pred p ); 70`` 71 72 73[endsect] 74