std::clamp
From cppreference.com
                    
                                        
                    
                    
                                                            
                    | Defined in header  <algorithm> | ||
| template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ); | (1) | (since C++17) | 
| template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ); | (2) | (since C++17) | 
1) If 
v compares less than hi, returns the larger of v and lo, otherwise returns the smaller of v and hi. Uses operator< to compare the values.2) Same as (1), but uses 
comp to compare the values.| Contents | 
[edit] Parameters
| v | - | the value to clamp | 
| lo,hi | - | the boundaries to clamp vto | 
| comp | - | comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true iflois less thanvandvis less thanhi.The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function object must not modify the objects passed to it. | 
| Type requirements | ||
| - Tmust meet the requirements ofLessThanComparablein order to use overloads (1). | ||
[edit] Return value
Reference to v if it is between the bounds, lo if v is smaller than lo, and hi if v is larger than hi.
If v compares equivalent to either bound, returns v.
[edit] Complexity
1) At most two comparisons
[edit] Possible implementation
| First version | 
|---|
| template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ) { return clamp( v, lo, hi, std::less<>() ); } | 
| Second version | 
[edit] Notes
Capturing the result of std::clamp by reference if one of the parameters is rvalue produces a dangling reference if that parameter is returned:
int n = -1; const int& r = std::clamp(n, 0, 255); // r is dangling
[edit] Example
| This section is incomplete Reason: no example | 
[edit] See also
| returns the smaller of the given values (function template) | |
| returns the greater of the given values (function template) | 


