C++ MinMax Algorithms: std::min, max, minmax_element & clamp

C++ MinMax Algorithms: std::min, max, minmax_element & clamp

이 글의 핵심

Single reference for min/max on values and ranges, plus clamp and practical patterns.

What are MinMax algorithms?

They find minimum and maximum values: overloads for two or more values, and range algorithms returning iterators.

Why use them?

  • Concise code vs manual branches
  • Type-safe comparisons
  • Range algorithms for position and min/max in one pass

Overview

APIInputReturnsTime
min(a,b) / max2 valuesreferenceO(1)
minmax(a,b)2 valuespairO(1)
min_element / max_elementrangeiteratorO(n)
minmax_elementrangepair of iteratorsO(n)
clamp(v, lo, hi)value + boundsclamped valueO(1)

std::min, std::max, std::minmax (values)

  • min / max: return references; watch dangling with temporaries (dangling reference).
  • minmax(a,b): one structured pair result.
  • min({a,b,c,...}): initializer_list overload for several values.

min_element, max_element, minmax_element

Return iterators so duplicate values can pick the first occurrence. Empty range → undefined behavior — check empty() first.


std::clamp (C++17)

clamp(v, lo, hi) equals min(max(v, lo), hi). Requires lo <= hi or UB. Useful for UI bounds, physics caps, color channels.


Performance notes

  • Two-argument min/max is often inlined and negligible.
  • Prefer min_element over sort + front when you only need extremal values.
  • minmax_element: one scan for both extrema vs two separate passes.

Production patterns

Statistics (min/max + mean), range validation with clamp, and normalization using minmax_element span — same logic as the Korean article.


FAQ

min/max vs min_element? Values vs iterators / positions.

minmax? Pair of extrema for two values.

clamp? Bound value to [lo, hi] (C++17).

Empty range? UB for *_element — guard with empty().

Resources? Effective STL, C++ Primer, cppreference — min.


  • C++ Algorithm Search
  • C++ Algorithm Guide
  • C++ Algorithm Sort

Keywords

std::min, std::max, minmax_element, clamp, min_element, max_element, STL