Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clamp
c++ range
c++ clamp value
c++ clamp

What is the C++ clamp value?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Imagine you are a programmer and want to make a program where a number input should always be within a specified range. It is very difficult to notify or even remember the ranges after the program is made. Therefore, the C++ Clamp is used.

Scenario

You want to build a program so whenever a user enters a number, you make sure it is changed to fall into a specific range of [10-20]. For a number greater than 20, it should be clamped to 20. For a number less than 10, it should be clamped to 10. For numbers within the range, no modifications are made.

1 of 3

Code

#include <iostream>
// important to include algorithm library
#include <algorithm>
using namespace std;
// Range [10 - 20]
int low = 10, high = 20;
int main()
{
// Array of 5 having elements to be clamped
int arr[5] = { 8, 12, 20, 25, 5};
// Printing the array after clamped
cout<<"Numbers before Clamp: ";
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
cout<<endl;
// clamp the elements at every index of array
for (int i = 0; i < 5; i++) {
arr[i] = std::clamp(arr[i], low, high);
}
// Printing the array after clamped
cout<<"Numbers After Clamp: ";
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
cout<<endl;
}
Numbers before Clamp: 8 12 20 25 5
Numbers after Clamp: 10 12 20 20 10

In the code above, we can see how 8 and 5 were clamped to 10 since they are less than 10. Number 25 was clamped to 20 since it is greater than 20. Numbers 12 and 20 were within range, so no modifications were made.

In real-life scenarios, clamps ensure that the list of inputs is specified to a given range. Moreover, it prevents size overflow.

RELATED TAGS

clamp
c++ range
c++ clamp value
c++ clamp
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring