std::clamp

Header: <algorithm>

If the value of v is within [lo,hi], returns v; otherwise returns the nearest boundary.

# Declarations

template< class T >
constexpr const T& clamp( const T& v, const T& lo, const T& hi );

(since C++17)

template< class T, class Compare >
constexpr const T& clamp( const T& v, const T& lo, const T& hi,
Compare comp );

(since C++17)

# Parameters

# Return value

Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise reference to v.

# Notes

If v compares equivalent to either bound, returns a reference to v, not the bound.

# Example

#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
 
int main()
{
    std::cout << "[raw] "
                 "[" << INT8_MIN << ',' << INT8_MAX << "] "
                 "[0," << UINT8_MAX << "]\n";
 
    for (const int v : {-129, -128, -1, 0, 42, 127, 128, 255, 256})
        std::cout << std::setw(4) << v
                  << std::setw(11) << std::clamp(v, INT8_MIN, INT8_MAX)
                  << std::setw(8) << std::clamp(v, 0, UINT8_MAX) << '\n';
}

# See also