Limit the Values of a Container to a Range with std::clamp

Learn to limit the values of a container to a range with std::clamp.

We'll cover the following

Introduced with C++17, the std::clamp() function can be used to limit the range of a numeric scalar to within minimum and maximum values. This function is optimized to use move semantics, where possible, for maximum speed and efficiency.

How to do it

We can use clamp() to constrain the values of a container by using it in a loop, or with the transform() algorithm. Let's look at some examples.

  • We'll start with a simple function for printing out the values of a container:

Get hands-on with 1200+ tech skills courses.