std::ranges::clamp
来自 cppreference.cn
定义于头文件 <algorithm> |
||
调用签名 |
||
template< class T, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<const T*, Proj>> Comp = |
(自 C++20) | |
如果 v 的值在 [
lo,
hi]
范围内,则返回 v;否则返回最近的边界。
如果 lo 大于 hi,则行为未定义。
此页面上描述的类函数实体是 算法函数对象(非正式地称为 niebloids),即
内容 |
[编辑] 参数
v | - | 要钳制的值 |
lo, hi | - | 钳制 v 的边界 |
comp | - | 应用于投影元素的比较 |
proj | - | 应用于 v、lo 和 hi 的投影 |
[编辑] 返回值
如果 v 的投影值小于 lo 的投影值,则返回对 lo 的引用;如果 hi 的投影值小于 v 的投影值,则返回对 hi 的引用;否则返回对 v 的引用。
[编辑] 复杂度
最多两次比较和三次投影的应用。
[编辑] 可能的实现
struct clamp_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<const T*, Proj>> Comp = std::ranges::less> constexpr const T& operator()(const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {}) const { auto&& pv = std::invoke(proj, v); if (std::invoke(comp, std::forward<decltype(pv)>(pv), std::invoke(proj, lo))) return lo; if (std::invoke(comp, std::invoke(proj, hi), std::forward<decltype(pv)>(pv))) return hi; return v; } }; inline constexpr clamp_fn clamp; |
[编辑] 注解
std::ranges::clamp
的结果会产生悬空引用int n = -1; const int& r = std::ranges::clamp(n, 0, 255); // r is dangling
如果 v 与任一边界比较等效,则返回对 v 的引用,而不是边界。
如果投影按值返回,并且比较器按值接受参数,则不应使用此函数,除非从投影结果类型到比较器参数类型的移动等同于复制。如果通过 std::invoke 进行比较会更改投影结果,则由于 std::regular_invocable
的语义要求(被 std::indirect_strict_weak_order 包含),行为是未定义的。
标准要求保留投影结果的值类别,并且 proj 只能对 v 调用一次,这意味着对于比较器的两次调用,必须缓存作为纯右值的投影结果并从中移动两次。
- libstdc++ 不符合此要求,并且始终将投影结果作为左值传递。
- libc++ 过去会运行两次投影,这已在 Clang 18 中得到纠正。
- MSVC STL 过去会运行两次投影,这已在 VS 2022 17.2 中得到纠正。
[编辑] 示例
运行此代码
#include <algorithm> #include <cstdint> #include <iomanip> #include <iostream> #include <string> using namespace std::literals; namespace ranges = std::ranges; int main() { std::cout << "[raw] [" << INT8_MIN << ',' << INT8_MAX << "] " "[0" << ',' << UINT8_MAX << "]\n"; for (int const v : {-129, -128, -1, 0, 42, 127, 128, 255, 256}) std::cout << std::setw(4) << v << std::setw(11) << ranges::clamp(v, INT8_MIN, INT8_MAX) << std::setw(8) << ranges::clamp(v, 0, UINT8_MAX) << '\n'; std::cout << std::string(23, '-') << '\n'; // Projection function const auto stoi = [](std::string s) { return std::stoi(s); }; // Same as above, but with strings for (std::string const v : {"-129", "-128", "-1", "0", "42", "127", "128", "255", "256"}) std::cout << std::setw(4) << v << std::setw(11) << ranges::clamp(v, "-128"s, "127"s, {}, stoi) << std::setw(8) << ranges::clamp(v, "0"s, "255"s, {}, stoi) << '\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 ----------------------- -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) |
返回给定值中较小的值 (算法函数对象) |
(C++20) |
返回给定值中较大的值 (算法函数对象) |
(C++20) |
检查整数值是否在给定整数类型的范围内 (函数模板) |
(C++17) |
将值钳制在一对边界值之间 (函数模板) |