需要引入头文件<algorithm>,用*max_element()直接求值,用distance求下标。
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
int main() {
vector<int> nums{1, 3, 4, 2};
for (int num : nums) {
cout << num << " ";
}
cout << endl;
int value = *max_element(nums.begin(),nums.end());
auto valueIter = max_element(nums.begin(), nums.end());
int index = distance(nums.begin(), valueIter);
cout << "max value = "<<value << endl;
cout << "max value index = " << index << endl;
return 0;
}