Limit the Values of a Container to a Range with std::clamp
Explore how to use the std::clamp function to limit the values in C++ containers within specified ranges. Understand its efficient implementation using move semantics and apply clamp through both loops and the transform algorithm for better value control in your STL containers.
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:
void printc(auto& c, string_view s = "") {if(s.size()) cout << format("{}: ", s);for(auto e : c) cout << format("{:>5} ", e);cout << '\n';}
Note: The format string
{:>5}right-aligns each value tospaces, for a tabular view.
In the
main()function, we'll define an initializer ...