以下のようなfor文をよく書いてしまうが、標準ライブラリを使ってできるよという話。
#include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; int min = v[0]; int max = v[0]; for(int i : v) { if(i < min) min = i; if(i > max) max = i; } printf("min: %d\n", min); printf("max: %d\n", max); return 0; }
std::min_element(), std::max_element()を使う
min_element(), max_element()にコンテナのイテレータを渡すと、min, maxを指すイテレータを返してくれる。
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4}; decltype(v)::iterator it; it = std::min_element(v.begin(), v.end()); printf("min: %d\n", *it); it = std::max_element(v.begin(), v.end()); printf("max: %d\n", *it); return 0; }
参考
https://cpprefjp.github.io/reference/algorithm/min_element.html https://cpprefjp.github.io/reference/algorithm/max_element.html https://cpprefjp.github.io/reference/algorithm/minmax_element.html https://stackoverflow.com/questions/9874802/how-can-i-get-the-maximum-or-minimum-value-in-a-vector