nth_element()函數
頭文件:#include<algorithm>
作用:nth_element作用為求第n大的元素,並把它放在第n位置上,下標是從0開始計數的,也就是說求第0小的元素就是最小的數。
如:a[start,end]元素區間。排序后a[n]就是數列中第n+1大的數(下標從0開始計數)。要注意的是a[start,n),
a[n,end]內的大小順序還不一定。
僅僅能確定a[n]是數列中第n+1大的數。
當然a[start,n)中的數肯定不大於
a[n,end]中的數。
注意:nth_element()函數不過將第n大的數排好了位置,並不返回值。
實例代碼例如以下:
#include<iostream> #include<algorithm> using namespace std; int main() { int a[]={1,3,4,5,2,6,8,7,9}; int i; cout<<"數列例如以下:"<<endl; for(i=0;i<9;i++) cout<<a[i]<<" "; nth_element(a,a+5,a+9); cout<<endl<<"輸出第五大的數: "<<a[4]<<endl; //注意下標是從0開始計數的 return 0; }