どうも、ちょげ(@chogetarou)です。
Vectorの最大値のインデックスを取得する方法を紹介します。
方法

Vectorの最大値を取得するには、std::distance()
とstd::max_element()
を使います。
まず、std::distance()
を呼び出します。
std::distance()
の第1引数にVectorのbegin()、第2引数にmax_element()
を指定します。
そして、*max_element()
の第1引数にVectorのbegin()、第2引数にVectorのend()を指定します。
//vect=任意のVector
std::distance(vect.begin(), std::max_element(vect.begin(), vect.end()));
上記のstd::distance()
は、begin()とend()を呼び出したVectorの最大値のインデックスを取得します。
使用例
#include <iostream>
#include <vector>
using namespace std;
int main(void){
vector<int> num = { 1, 2, 10, 3, 4, 5 };
int maxIndex = distance(num.begin(), max_element(num.begin(), num.end()));
cout << maxIndex;
}
出力:
2
コメント