std::ranges::clamp
来自cppreference.com
在标头 <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 则行为未定义。
此页面上描述的函数式实体是 niebloid,即:
实践中,可以作为函数对象,或者用某些特殊编译器扩展实现它们。
参数
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 - 1, n + 1); // r 悬垂
若 v 与任一边界比较等价,则返回到 v 而非到边界的引用。
不应同时将按值返回的投影以及按值接收实参的比较器用于此函数,除非从投影结果类型到比较器形参类型的移动等价于复制。如果经由 std::invoke 的比较会改变投影结果,则由于(std::indirect_strict_weak_order 所蕴含的) std::regular_invocable
的语义要求行为未定义。
标准要求保持投影结果的值类别,并且只能在 v 上调用 proj 一次,这表示必须缓存纯右值投影结果并对两次比较器的调用各将它移动一次。
- 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'; // 投影函数 const auto stoi = [](std::string s) { return std::stoi(s); }; // 同上,但用字符串 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) |
返回给定值的较小者 (niebloid) |
(C++20) |
返回给定值的较大者 (niebloid) |
(C++20) |
检查整数值是否在给定整数类型的范围内 (函数模板) |
(C++17) |
在一对边界值间夹逼一个值 (函数模板) |