max_element() and min_element
这两个函数是在头文件algorithm中的,分别返回的是容器中的最大值和最小值。
只介绍max_element(),min_element同理。
max_element():
returns an iterator pointing to the element with the largest value in the range [first, last)。
也就是说它返回的是一个迭代器,所以要想得到最大值,要加“*”。
代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[10];
for(int i=0; i<5; i++)
{
cin>>a[i];
}
cout<<*max_element(a, a+5);
return 0;
}
当然我们还可以利用返回的迭代器减去初始地址得到最大值的下标index
代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[10];
for(int i=0; i<5; i++)
{
cin>>a[i];
}
cout<<max_element(a, a+5)-a;
return 0;
}
min_element用法同上,这个函数不需要使用循环,速度也快很多。