nth_element函数的作用是在一个未排序的数组中,寻找如果这个数组按从小到大的顺序排序,第n个位置上应该是哪一个数,在<algorithm>头文件中
具体的使用方法是 nth_element(a+start,a+k,a+end)
就是在a数组的start位置到end范围内从小到大排序应该在第k个位置上的数是哪一个
并且这个函数只是找到了第k个位置上的数,其他的位置并不是有序的,但可以确定的是[start,k-1]上的数都比a[k]小,
[k+1,end]上的数都比a[k]大。
还要注意的一点是这个函数没有返回值。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[11];
for(int i=1;i<=10;i++)
cin>>a[i];
nth_element(a+1,a+5,a+11);
cout<<a[5]<<endl; //输出第五个位置上的数
for(int i=1;i<=10;i++)
cout<<a[i]<<" ";
}
根据这个函数说一个应用,就是找一个数组里第k大的数是哪一个,一般可以直接排序找
但当数据过大的时候,这个就可以派上用场。
如果有n个数,第k大,也就是在按从小到大排序完后第n-k+1的位置上。
例如10个数,找第二大的数,应用nth_element后,第二大的数应该在10-2+1的位置上
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[11];
for(int i=1;i<=10;i++)
cin>>a[i];
nth_element(a+1,a+10-2+1,a+11);
cout<<a[10-2+1]<<endl; //输出第9个位置上的数
for(int i=1;i<=10;i++)
cout<<a[i]<<" ";
}