3要素以上のstd::min, std::maxを取る

プログラミングC/C++

c++03の知識で止まっていたので懺悔のメモ。

std::min, std::max, std::minmax で3要素以上にわたる演算をしたい場合は、std::initializer_list<T> 型を引数に取るオーバーロードを用いればよい1

#include <algorithm>
#include <iostream>

int main() {
  std::cout << std::max({3, 3, 4}) << std::endl;
  // => 4

  int x = 2;
  int y = 6;
  int z = 4;
  std::cout << std::min({x, y, z}) << std::endl;
  // => 2
}

参考:max – cpprefjp C++日本語リファレンス

notes

  1. この機能を知るまでは std::max(std::max(3, 3), 4) したり可変長引数のmaxを自作したりしていた

プログラミングC/C++

Posted by komori