max_element, min_element を使ってみる (C++)
C++
Published: 2019-12-19

やったこと

配列、vector の最大値、最小値とそれらのインデックスを取得します。

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;

int main() {
    // 配列
    int A[] = {4, 10, 2};
    cout << "配列" << endl;
    cout << *max_element(A, A + 3) << endl;
    cout << max_element(A, A + 3) - A << endl;
    cout << *min_element(A, A + 3) << endl;
    cout << min_element(A, A + 3) - A << endl;

    cout << endl;

    // vector
    cout << "vector" << endl;
    vector<int> B = {30, 10, 6, 20, 55, 2};

    cout << "最大値" << endl;
    auto max_iter = max_element(B.begin(), B.end());
    cout << *max_iter << endl;
    cout << distance(B.begin(), max_iter) << endl;
    cout << max_iter - B.begin() << endl;

    cout << "最小値" << endl;
    auto min_iter = min_element(B.begin(), B.end());
    cout << *min_iter << endl;
    cout << distance(B.begin(), min_iter) << endl;
    cout << min_iter - B.begin() << endl;
}

出力結果

配列
10
1
2
2

vector
最大値
55
4
4
最小値
2
5
5

参考