min_element() ,max_element () 和 nth_element()
头文件:#include<algorithm>
作用:返回容器中最小值和最大值。
max_element(first,end,cmp);其中cmp为可选择参数!
(转载学长的,感觉写全了已经,简洁明了。)
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int num[]={2,3,1,6,4,5};
cout<<"最小值是 "<<*min_element(num,num+6)<<endl;
cout<<"最大值是 "<<*max_element(num,num+6)<<endl;
cout<<"最小值是 "<<*min_element(num,num+6,cmp)<<endl;
cout<<"最大值是 "<<*max_element(num,num+6,cmp)<<endl;
return 0;
*nth_element() :
作用:求第n个元素,并将其排到第n个位置,当然array[first,nth) > array[nth,last]。但并没有完全从大到小排序。
注意:数组下标是从0开始的。并不返回值。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int iarray[]={5,6,15,89,7,2,1,3,52,63,12,64,47};
int len=sizeof(iarray)/sizeof(int);//数组长度
int i;
for(i=0;i<len;i++)
cout<<iarray[i]<<" ";
nth_element(iarray,iarray+6,iarray+len); //排序第6个元素
cout<<endl;<span style="white-space:pre"> </span> //数组首元素,nth,尾元素
for(i=0;i<len;i++)
cout<<iarray[i]<<" ";
cout<<" 第6-th个元素 "<<iarray[6]<<endl;<span style="font-family:Arial, Helvetica, sans-serif;">}</span>
运行结果:
5 6 15 89 7 2 1 3 52 63 12 64 47
5 3 1 2 6 7 12 15 47 63 52 64 89 第6-th个元素 12
Process returned 0 (0x0) execution time : 1.326 s
Press any key to continue.