パープルハット

※当サイトではGoogleアドセンス広告を利用しています

C++ 3値以上の最大値・最小値



最大値(max)

  • 日本語リファレンス:max - cpprefjp C++日本語リファレンス
  • 3つ以上の変数の最大値をとるには、2値の最大値を求めるmax関数の引数をinitializer_listにすればOKです。
  • initializer_listと聞くと難しく感じますが、vectorなどの初期化で使う{}のことです。
// 右辺がinitializer_list
vector<int> a = {1, 2, 3};


サンプルコード

#include<iostream>
#include<vector>
#include <algorithm>

int main() {
	int a = 4, b = 3, c = 7, d = 0;
	int maxValue = std::max({a, b, c, d});
	std::cout << "a~dの最大値は" << maxValue << std::endl;
}

実行結果

a~dの最大値は7





最小値(min)

サンプルコード

#include<iostream>
#include<vector>
#include <algorithm>

int main() {
	int a = 4, b = 3, c = 7, d = 0;
	int minValue = std::min({ a, b, c, d });
	std::cout << "a~dの最小値は" << minValue << std::endl;
}

実行結果

a~dの最小値は0




最大・最小値を同時に求める(minmax)

  • 日本語リファレンス:minmax - cpprefjp C++日本語リファレンス
  • minmax関数を使うと、これまでと同様の方法で最大値・最小値を同時に取得できます。
  • 返り値の型はpairですが、autoを使うことで2つの変数に分けることも可能です。

サンプルコード

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
	int a = 4, b = 3, c = 7, d = 0;
	auto [x, y] = std::minmax({a, b, c, d});
	std::cout << "a~dの最小値は" << x << std::endl;
	std::cout << "a~dの最大値は" << y << std::endl;
}

実行結果

a~dの最小値は0
a~dの最大値は7





vectorの最大値・最小値をとる場合

max_elementなどの関数を使うことで最大値・最小値を取得できます。
別記事にまとめました⇒C++ vectorの最大値・最小値 - パープルハット