Time and Numeric Utilities
Clamp Value
std::clamp keeps a value inside a minimum and maximum range.
clamp
`std::clamp(value, low, high)` returns `low`, `high`, or the original value depending on the range.
bounds
Bounds make invalid or extreme values fit a rule before later calculations use them.
Clamp Value
clamp_value.cpp
Replay: real traced execution (multi-file project)
#include <algorithm>
#include <iostream>
int main() {
int score = 120;
int bounded = std::clamp(score, 0, 100);
bool changed = bounded != score;
std::cout << "score=" << score << std::endl;
std::cout << "bounded=" << bounded << std::endl;
std::cout << "changed=" << changed << std::endl;
return 0;
}
#include <algorithm>
#include <iostream>
int main() {
int score = -10;
int bounded = std::clamp(score, 0, 100);
bool changed = bounded != score;
std::cout << "score=" << score << std::endl;
std::cout << "bounded=" << bounded << std::endl;
std::cout << "changed=" << changed << std::endl;
return 0;
}
#include <algorithm>
#include <iostream>
int main() {
int score = 75;
int bounded = std::clamp(score, 0, 100);
bool changed = bounded != score;
std::cout << "score=" << score << std::endl;
std::cout << "bounded=" << bounded << std::endl;
std::cout << "changed=" << changed << std::endl;
return 0;
}
score ← 120, bounded ← 100, changed ← 1
4int main() {5 int score→ 120 = 120; //@score=-10, 7567 int bounded→ 100 = std::clamp(score120, 0, 100);8 bool changed→ 1 = bounded100 != score120;910 std::cout << "score=" << score120 << std::endl;11 std::cout << "bounded=" << bounded100 << std::endl;12 std::cout << "changed=" << changed1 << std::endl;13 return 0;14}outputscore=120 bounded=100 changed=1
score ← -10, bounded ← 0, changed ← 1
4int main() {5 int score→ -10 = -10;67 int bounded→ 0 = std::clamp(score-10, 0, 100);8 bool changed→ 1 = bounded0 != score-10;910 std::cout << "score=" << score-10 << std::endl;11 std::cout << "bounded=" << bounded0 << std::endl;12 std::cout << "changed=" << changed1 << std::endl;13 return 0;14}outputscore=-10 bounded=0 changed=1
score ← 75, bounded ← 75, changed ← 0
4int main() {5 int score→ 75 = 75;67 int bounded→ 75 = std::clamp(score75, 0, 100);8 bool changed→ 0 = bounded75 != score75;910 std::cout << "score=" << score75 << std::endl;11 std::cout << "bounded=" << bounded75 << std::endl;12 std::cout << "changed=" << changed0 << std::endl;13 return 0;14}outputscore=75 bounded=75 changed=0