C++中Vector求最大值最小值
#include <iostream> #include <vector> #include <windows.h> #include <algorithm> using namespace std; int main() { vector<int> vec = {-7, 1, 10, 7, 2, 1}; vector<int>::iterator itMax = max_element(vec.begin(), vec.end()); vector<int>::iterator itMin = min_element(vec.begin(), vec.end()); cout << "最大值为:" << *itMax << " " << "所在位置:" << distance(vec.begin(), itMax) << endl; cout << "最小值为:" << *itMin << " " << "所在位置:" << distance(vec.begin(), itMin) << endl; system("pause"); return 0; }
vector<int> v: 最大值: int max = *max_element(v.begin(),v.end()); 最小值: int min = *min_element(v.begin(),v.end());
int a[]={1,2,4,6,4,9};
vector<int>sums(a,a+6);
int idx = max_element(sums.begin(),sums.end())-sums.begin();