Library Feature: std::clamp
Definition
Clamp is an algorithm added in C++17 that is used to limit a value in a given range.
- If value > max, value is set to max
- If value < min, value is set to min
Syntax
1 2 3 4 5 |
template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ); template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ); |
Before C++17, we were relying on the following code (or similar) to clamp a value.
1 2 3 |
auto value = 300; if (value > maxValue) value = maxValue; else if (value < minValue) value = minValue; |
1 |
value = std::min(maxValue, std::max(minValue, value)); |
Now, with C++17, we can simply use std::clamp.
1 2 3 4 |
int min = 0, max = 100; std::cout << std::clamp(-325, min, max) << endl; // display 0 std::cout << std::clamp( 325, min, max) << endl; // display 100 std::cout << std::clamp( 25, min, max) << endl; // display 25 |