std::clamp
(on partitioned ranges)
<algorithm>
constexpr const T& clamp( const T& v, const T& lo, const T& hi,
If the value of v is within [
lo,
hi]
, returns v; otherwise returns the nearest boundary.
If lo is greater than hi, the behavior is undefined.
NaN
is avoided, T
can be a floating-point type.
The signature of the comparison function should be equivalent to the following:
bool cmp(const Type1& a, const Type2& b);
While the signature does not need to have const&, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1
and Type2
regardless of value category (thus, Type1& is not allowed, nor is Type1 unless for Type1
a move is equivalent to a copy(since C++11)).
The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both of them.
Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise reference to v.
clamp (1) |
---|
template<class T> constexpr const T& clamp(const T& v, const T& lo, const T& hi) { return clamp(v, lo, hi, less{}); } |
clamp (2) |
template<class T, class Compare> constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) { return comp(v, lo) ? lo : comp(hi, v) ? hi : v; } |
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.
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_clamp |
201603L |
(C++17) | std::clamp
|
#include <algorithm> #include <cstdint> #include <iomanip> #include <iostream> int main() { std::cout << "[raw] " "[" << INT8_MIN << ',' << INT8_MAX << "] " "[0," << UINT8_MAX << "]\n"; for (const int v : {-129, -128, -1, 0, 42, 127, 128, 255, 256}) std::cout << std::setw (4) << v << std::setw (11) << std::clamp(v, INT8_MIN, INT8_MAX ) << std::setw (8) << std::clamp(v, 0, UINT8_MAX ) << '\n'; }
Output:
[raw] [-128,127] [0,255] -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