模板--STL之nth_element()--取容器中的第n大值

头文件:#include<algorithm>

作用:nth_element作用为求第n大的元素,并把它放在第n位置上,下标是从0開始计数的,也就是说求第0小的元素就是最小的数;

如:a[start,end]元素区间。排序后a[n]就是数列中第n+1大的数(下标从0開始计数);

注意:1.a[start,n),a[n,end]内的大小顺序还不一定;

2.仅仅能确定a[n]是数列中第n+1大的数。当然a[start,n)中的数肯定不大于a[n,end]中的数;

3.nth_element()函数不过将第n大的数排好了位置,并不返回值;

代码示例:

#include<iostream>
#include<algorithm>
using namespace std; 
int main(){
	int a[]={1,3,4,5,2,6,8,7,9};
	cout<<"数列例如以下:"<<endl;
	for(int i=0;i<9;i++)
	   cout<<a[i]<<" ";
	nth_element(a,a+5,a+9);
    cout<<endl<<"输出第五大的数: "<<a[4]<<endl; //注意下标是从0開始计数的 
	return 0;
}

运行结果:

数列例如以下:
1 3 4 5 2 6 8 7 9
输出第五大的数: 5

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/106161087