STL之*min_element , *max_element ,*nth_element()[取容器中最大元素 最小元素 第n元素]

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值