std::clamp in C++ 17
Last Updated :
07 Aug, 2017
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.
Examples:
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
Syntax :
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.
#include <bits/stdc++.h>
int main()
{
int high = 100, low = 10;
int num1 = 120;
int num2 = 5;
int num3 = 50;
num1 = std::clamp(num1, low, high);
num2 = std::clamp(num2, low, high);
num3 = std::clamp(num3, low, high);
std::cout << num1 << " " << num2 << " " << num3;
}
|
Output:
100 10 50
#include <iostream>
#include <algorithm>
int low = 30, high = 60;
void clamp_arr_in_range( int arr[], int n)
{
for ( int i = 0; i < n; i++) {
arr[i] = std::clamp(arr[i], low, high);
}
}
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60, 70, 80 };
int n = sizeof (arr) / sizeof (arr[0]);
clamp_arr_in_range(arr, n);
for ( int i = 0; i < n; i++)
std::cout << arr[i] << " " ;
}
|
Output :
30 30 30 40 50 60 60 60
With Binary Predicate
#include <bits/stdc++.h>
bool comp( int a, int b)
{
return (a < b);
}
int main()
{
int high = 100, low = 10;
int num1 = 120;
int num2 = 5;
int num3 = 50;
num1 = std::clamp(num1, low, high, comp);
num2 = std::clamp(num2, low, high, comp);
num3 = std::clamp(num3, low, high, comp);
std::cout << num1 << " " << num2 << " " << num3;
}
|
Output:
100 10 50
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...