Files
cppdraft_translate/cppdraft/alg/clamp.md
2025-10-25 03:02:53 +03:00

58 lines
2.3 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[alg.clamp]
# 26 Algorithms library [[algorithms]](./#algorithms)
## 26.8 Sorting and related operations [[alg.sorting]](alg.sorting#alg.clamp)
### 26.8.10 Bounded value [alg.clamp]
[🔗](#lib:clamp)
`template<class T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi);
template<class T, class Compare>
constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp);
template<class T, class Proj = identity,
[indirect_strict_weak_order](indirectcallable.indirectinvocable#concept:indirect_strict_weak_order "24.3.6.3Indirect callables[indirectcallable.indirectinvocable]")<projected<const T*, Proj>> Comp = ranges::less>
constexpr const T&
ranges::clamp(const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {});
`
[1](#1)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/algorithms.tex#L11714)
Let comp be less{} for the overloads with no parameter comp,
and let proj be identity{} for the overloads with no parameter proj[.](#1.sentence-1)
[2](#2)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/algorithms.tex#L11720)
*Preconditions*: bool(invoke(comp, invoke(proj, hi), invoke(proj, lo))) is false[.](#2.sentence-1)
For the first form, type T meets the [*Cpp17LessThanComparable*](utility.arg.requirements#:Cpp17LessThanComparable "16.4.4.2Template argument requirements[utility.arg.requirements]") requirements (Table [29](utility.arg.requirements#tab:cpp17.lessthancomparable "Table 29: Cpp17LessThanComparable requirements"))[.](#2.sentence-2)
[3](#3)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/algorithms.tex#L11727)
*Returns*: lo if bool(invoke(comp, invoke(proj, v), invoke(proj, lo))) is true,hi if bool(invoke(comp, invoke(proj, hi), invoke(proj, v))) is true,
otherwise v[.](#3.sentence-1)
[4](#4)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/algorithms.tex#L11733)
[*Note [1](#note-1)*:
If NaN is avoided, T can be a floating-point type[.](#4.sentence-1)
— *end note*]
[5](#5)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/algorithms.tex#L11738)
*Complexity*: At most two comparisons and three applications of the projection[.](#5.sentence-1)