Namespaces
Variants

std:: clamp

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
clamp
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <algorithm>
template < class T >
constexpr const T & clamp ( const T & v, const T & lo, const T & hi ) ;
(1) (C++17부터)
template < class T, class Compare >

constexpr const T & clamp ( const T & v, const T & lo, const T & hi,

Compare comp ) ;
(2) (C++17부터)

v 값이 [ lo , hi ] 범위 내에 있으면 v 를 반환하고, 그렇지 않으면 가장 가까운 경계값을 반환합니다.

1) 값을 비교하기 위해 operator < (C++20까지) std:: less { } (C++20 이후) 를 사용합니다.
만약 T LessThanComparable 가 아니라면, 동작은 정의되지 않습니다. [1]
2) 값을 비교하기 위해 비교 함수 comp 를 사용합니다.

만약 lo hi 보다 크면, 동작은 정의되지 않습니다.

  1. 만약 NaN 을 피한다면, T 는 부동소수점 타입이 될 수 있습니다.

목차

매개변수

v - 제한할 값
lo, hi - v 를 제한할 경계값
comp - 비교 함수 객체(즉, Compare 요구 사항을 만족하는 객체)로 첫 번째 인수가 두 번째 인수보다 작은 경우 true 를 반환합니다.

비교 함수의 시그니처는 다음과 동등해야 합니다:

bool cmp ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 가 명시되지 않아도 함수는 전달된 객체를 수정해서는 안 되며, 값 범주 에 관계없이 (가능한 const인) Type1 Type2 타입의 모든 값을 수용할 수 있어야 합니다 (따라서 Type1 & 는 허용되지 않으며, Type1 Type1 에 대해 이동이 복사와 동등하지 않는 한 허용되지 않습니다 (C++11부터) ).
Type1 Type2 타입은 T 타입의 객체가 두 타입 모두로 암시적으로 변환 가능해야 합니다.

반환값

lo v 보다 작으면 lo 에 대한 참조, hi v 보다 작으면 hi 에 대한 참조, 그렇지 않으면 v 에 대한 참조.

복잡도

1) 최대 두 번의 비교를 사용하여 operator < (C++20 이전) std:: less { } (C++20 이후) .
2) 비교 함수 comp 를 최대 두 번 적용합니다.

가능한 구현

clamp (1)
template<class T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi)
{
    return clamp(v, lo, hi, less{});
}
clamp (2)
template<class T, class Compare>
constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp)
{
    return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}

참고 사항

Capturing the result of std::clamp by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned:
int n = -1;
const int& r = std::clamp(n, 0, 255); // r은 댕글링 참조입니다

만약 v 가 어느 한 경계와 동등하게 비교되면, 경계가 아닌 v 에 대한 참조를 반환합니다.

기능 테스트 매크로 표준 기능
__cpp_lib_clamp 201603L (C++17) std::clamp

예제

#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';
}

출력:

[raw] [-128,127] [0,255]
-129       -128       0
-128       -128       0
  -1         -1       0
   0          0       0
  42         42      42
 127        127     127
 128        127     128
 255        127     255
 256        127     255

참고 항목

주어진 값들 중 더 작은 값을 반환합니다
(함수 템플릿)
주어진 값들 중 더 큰 값을 반환합니다
(함수 템플릿)
(C++20)
정수 값이 주어진 정수 타입의 범위 내에 있는지 확인합니다
(함수 템플릿)
값을 한 쌍의 경계값 사이로 고정합니다
(알고리즘 함수 객체)