GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::clamp - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. algorithm
  3. clamp

最終更新日時: 2026年08月24日 16時04分46秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<algorithm>

std::clamp(C++17)

namespace std {
  template <class T>
  constexpr const T& clamp(const T& v, const T& low, const T& high);

  template <class T, class Compare>
  constexpr const T& clamp(const T& v, const T& low, const T& high, Compare comp);
}

概要

値を範囲内に収める。

この関数は、vの値を範囲[low, high]に収める。

テンプレートパラメータ制約

  • (1) : 型TはLessThanComparableの要件を満たしていること

事前条件

  • lowの値はhighの値より大きくなってはならない

戻り値

  • vの値がlowより小さければlowを返す
  • vの値がhighより大きければhighを返す
  • そうでなければvを返す

備考

  • clamp(v, low, high)はmin(max(v, low), high)と等価

例

#include <iostream>
#include <algorithm>

int main()
{
  for (int i = 0; i < 10; ++i) {
    // iの値を範囲[2, 7]に収める
    int result = std::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++17

処理系

  • Clang: 3.9 ✅
  • GCC: 7.1 ✅
  • Visual C++: ??

関連項目

  • ranges::clamp

参照

  • N4536 An algorithm to "clamp" a value between a pair of boundary values
  • P0025R0 An algorithm to "clamp" a value between a pair of boundary values (revision 1)
  • LWG Issue 2688. clamp misses preconditions and has extraneous condition on result
    • C++17で、事前条件(lowはhighより大きくてはならない)が追加され、戻り値の規定が整理された
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.