所用方法
用 algorithm 库中的
max_element
min_element
这两个函数返回的是位置指针,*max_element获得最大值;
*min_element获得最小值。
distance(begin(), max_element(, ))获得最大值的下标。
distance(begin(), min_element(, ))获得最小值的下标。
代码示例
1、普通数组中的用法
#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[5] = { 12, 3, 65, 74,55 };
cout << "数组中的最大值为:" << (*max_element(a, a + 5)) <<"最大值的索引"<< distance(begin(a), max_element(a, a + 5)) << endl;
cout << "数组中的最小值为:" << *(min_element(a, a + 5)) <<endl;
return 0;
}
2、vector中的用法
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
int a[] = { 2, 3, 5, 4, 5 };
vector<int>b(a, a + 5);
vector<int>::iterator p = max_element(b.begin(), b.end());
vector<int>::iterator q = min_element(b.begin(), b.end());
cout << *p << endl;
cout << *q << endl;
system("pause");
return 0;
}