C++ std::clamp
Clamp a value to an inclusive interval.
A simple example
std::clamp
- Start with 8, allowed range 1–5
- Do this Keep the value inside the range
- Result 5
#include <iostream>
#include <algorithm>
int main() {
std::cout << (std::clamp(8, 1, 5)) << '\n';
}
5
Syntax
std::clamp(125, 0, 100)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonKeep a brightness setting inside the slider range
A display accepts brightness values only within a fixed range. Limit an out-of-range request before sending it to the device, and keep valid settings at their requested levels.
#include <iostream>
#include <algorithm>
int main() {
std::cout << (std::clamp(125, 0, 100)) << "\n";
return 0;
}
100
The slider accepts zero through one hundred, so an incoming value of 125 becomes 100.
Set a reading lamp’s brightness
A classroom lamp accepts an intensity from 10 to 90. A saved preference of 4 falls below the allowed interval.
The lower bound becomes the setting when the request is below the range.
Keep a valid camera zoom
A camera interface allows a zoom level between one and eight. A photographer recalls level five from a preset.
A request inside the permitted interval passes through.
What to watch for
Keep the lower bound at or below the upper bound.