std::clamp() algorithm
- since C++17
// (1)
template< class T >
constexpr const T& clamp( const T& v, const T& lo, const T& hi );
// (2)
template< class T, class Compare >
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp );
-
If
vcompares less thanlo, returnslo. -
Otherwise, if
vcompares more thanhi, returnshi. -
Otherwise returns
v. -
(1) Uses
operator<to compare the values. -
(2) Same as (1), but uses
compto compare the values.
The behavior is undefined if the value of lo is greater than hi.
Parameters
v | The value to clamp. |
lo hi | The boundaries to clamp |
comp | Comparison function object (i.e. an object that satisfies the requirements of Compare)
which returns
|
Type requirements
-
(1)
TLessThanComparable If
NaNis avoided,Tcan be a floating-point type.
Return value
Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise reference to v.
Complexity
At most two comparisons.
Exceptions
The overloads with a template parameter named ExecutionPolicy report errors as follows:
- If execution of a function invoked as part of the algorithm throws an exception and
ExecutionPolicyis one of the standard policies,std::terminateis called. For any otherExecutionPolicy, the behavior is implementation-defined. - If the algorithm fails to allocate memory,
std::bad_allocis thrown.
Possible implementation
clamp (1)
clamp (2)
Notes
Capturing the result of std::clamp by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned:
int n = -1;
const int& r = std::clamp(n, 0, 255); // r is dangling
If v compares equivalent to either bound, returns a reference to v, not the bound.
Examples
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
int main()
{
std::cout << " raw clamped to int8_t clamped to uint8_t\n";
for (const int v : {-129, -128, -1, 0, 42, 127, 128, 255, 256})
{
std::cout
<< std::setw(04) << v
<< std::setw(20) << std::clamp(v, INT8_MIN, INT8_MAX)
<< std::setw(21) << std::clamp(v, 0, UINT8_MAX) << '\n';
}
}
raw clamped to int8_t clamped to uint8_t
-129 -128 0
-128 -128 0
-1 -1 0
0 0 0
42 42 42
127 127 127
128 127 128
255 127 255
256 127 255
Hover to see the original license.