• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function template
    <algorithm>

    std::ranges::clamp

    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

    処理系

    参照