在线文档教程
C++
算法 | Algorithm

std::clamp

STD::夹子

Defined in header
template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi (1)(since C++17)
template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp (2)(since C++17)

1%29v相比较hi,返回较大的v和lo,否则返回较小的v和hi.用途operator<来比较这些值。

2%29与%281%29相同,但使用comp来比较这些值。

如果lo大于hi...

参数

v-the value to clamp
lo,hi-the boundaries to clamp v to
comp-comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if lo is less than v and v is less than hi. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b The signature does not need to have const &, but the function object must not modify the objects passed to it. The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both of them. ​

类型要求

-T必须符合LessThanable的要求,才能使用过载%281%29。

返回值

参照lo如果v小于lo,提及hi如果hi小于v,否则引用v...

复杂性

1%29最多两次比较

可能的实施

第一版

*。

模板<class T>Const T&箝位%28 Const T&v,Const T&lo,Const T&hi%29{返回钳位%28 v,lo,hi,std::<>%28%29%29;}

第二版

模板<类T,类比较>Const T&钳%28 Const T&v,Const T&lo,Const T&hi,比较comp%29{返回断言%28%21 comp%28 hi,lo%29%29,comp%28V,lo%29?罗:比较%28嗨,v%29?嗨:V;}

注记

捕获结果std::clamp通过引用,如果其中一个参数是rvalue,则如果返回该参数,则生成一个悬空引用:

二次

int n = -1; const int& r = std::clamp(n, 0, 255 // r is dangling

二次

如果v将等效于任一绑定的值进行比较,则返回v而不是束缚。

只适用于浮点。T如果NaN我们避免了。

二次

#include <cstdint> #include <algorithm> #include <iostream> #include <iomanip> #include <random> int main() { std::mt19937 g(std::random_device{}() std::uniform_int_distribution<> d(-300, 300 std::cout << " raw clamped to int8_t clamped to uint8_t\n"; for(int n = 0; n < 5; ++n) { int v = d(g std::cout << std::setw(4) << v << std::setw(20) << std::clamp(v, INT8_MIN, INT8_MAX) << std::setw(21) << std::clamp(v, 0, UINT8_MAX) << '\n'; } }

二次

可能的产出:

二次

.raw clamped to int8_t clamped to uint8_t 168 127 168 128 127 128 -137 -128 0 40 40 40 -66 -66 0

二次

另见

minreturns the smaller of the given values (function template)
maxreturns the greater of the given values (function template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/Algorithm/箝位