namespace std::ranges {
template <class T,
class Proj = identity,
indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less>
constexpr const T&
clamp(const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {}); // (1) C++20
}
概要
値を範囲内に収める。
この関数は、v
の値を範囲[low, high]
に収める。
事前条件
low
の値はhigh
の値より大きくなってはならない
戻り値
v
の値がlow
より小さければlow
を返すv
の値がhigh
より大きければhigh
を返す- そうでなければ
v
を返す
例
#include <iostream>
#include <algorithm>
int main()
{
for (int i = 0; i < 10; ++i) {
// iの値を範囲[2, 7]に収める
int result = std::ranges::clamp(i, 2, 7);
std::cout << i << " : " << result << std::endl;
}
}
出力
0 : 2
1 : 2
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 7
9 : 7
バージョン
言語
- C++20
処理系
- Clang: ??
- GCC: 10.1.0 ✅
- ICC: ??
- Visual C++: 2019 Update 10 ✅