Limit the values of a container to a range with std::clamp
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. The 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'; }
Notice the format string "{:>5} "
. This right-aligns each value to 5
spaces, for a tabular view.
- In the
main()
function, we...