std::clamp in C++ 17
Clamps a variable to a given range[high – low].
If num > high, num is assigned high. If num < low, num is assigned low. If num is already clamped, no modifications.
Note : This function is defined in header from C++17 onwards.
Input : num = 100, Range : 10 - 90 Output : num = 90 Input : num = 5, Range : 10 - 90 Output : num = 10 Input : num = 50, Range : 10 - 90 Output : num = 50
templateconstexpr const T& clamp( const T& num, const T& low, const T& high ); template constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ); Parameters num - the value to clamp low, high - the boundaries to clamp num to comp - comparison function object which returns ?true if low is less than num and num is less than high. Return value Reference to low if num is less than low, Reference to high if high is less than num, otherwise reference to num. Applications : To keep a list of inputs specified to a given range. Preventing size overflow.
100 10 50
30 30 30 40 50 60 60 60
With Binary Predicate
100 10 50
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.