std::clamp
ΠΠΊΡΡΠ°Π»ΡΠ½ΠΎ Π΄Π»Ρ C++23.
#include <algorithm>
ΠΠΊΡΡΠ°Π»ΡΠ½ΠΎ Π½Π° 2024-03-19.
Define overload #1
template<class T> constexpr const T& clamp(const T& v, const T& lo, const T& hi);
ΠΠ³ΡΠ°Π½ΠΈΡΠΈΠ²Π°Π΅Ρ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ "v" Π² ΠΏΡΠ΅Π΄Π΅Π»Π°Ρ ΠΌΠ΅ΠΆΠ΄Ρ "lo" ΠΈ "hi".
ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π² Π΄ΠΈΠ°ΠΏΠ°Π·ΠΎΠ½Π΅ "lo" ΠΈ "hi".
Example, possible implementation
Define overload #2
template<class T, class Compare> constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp);
ΠΠ³ΡΠ°Π½ΠΈΡΠΈΠ²Π°Π΅Ρ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ "v" Π² ΠΏΡΠ΅Π΄Π΅Π»Π°Ρ ΠΌΠ΅ΠΆΠ΄Ρ "lo" ΠΈ "hi".
ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π² Π΄ΠΈΠ°ΠΏΠ°Π·ΠΎΠ½Π΅ "lo" ΠΈ "hi".
ΠΠ½Π°ΡΠ΅Π½ΠΈΡ ΡΡΠ°Π²Π½ΠΈΠ²Π°ΡΡΡΡ Ρ ΠΏΠΎΠΌΠΎΡΡΡ Π±ΠΈΠ½Π°ΡΠ½ΠΎΠ³ΠΎ ΠΏΡΠ΅Π΄ΠΈΠΊΠ°ΡΠ° "comp".
Example, possible implementation
Examples
Example 1:
#include <iostream>
#include <algorithm>
#include <vector>
static void
clamp_range(auto begin, auto end, auto out, auto lo, auto hi)
{
for (auto it=begin; it < end; ++it) {
*out = std::clamp(*it, lo, hi);
++out;
}
}
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
clamp_range(std::begin(v), std::end(v), std::begin(v), 3, 7);
for (auto it : v) {
std::cout << it << '\n';
}
return 0;
}
3 3 3 4 5 6 7 7 7
Changelog
See also
TODO
This page was last modified on 2024-03-19