[c++] std::clamp
#include <iostream>
#include <algorithm>
int main() {
int value = 25;
int lowerLimit = 10;
int upperLimit = 50;
int clampedValue = std::clamp(value, lowerLimit, upperLimit);
std::cout << "Clamped value: " << clampedValue << std::endl;
return 0;
}
In this example, if value
is less than lowerLimit
, it will be replaced by lowerLimit
. If value
is greater than upperLimit
, it will be replaced by upperLimit
. If value
is within the range, it will remain unchanged.
std::clamp
is a convenient and concise way to ensure that a value stays within specified bounds, eliminating the need for manual range checking.
For more information, you can refer to the cppreference page on std::clamp.