1.nth_element 求第n大的元素,并把把它放在第n位置上。下标从0开始,不返回值。
nth_element(first,nth,last)
first,last 第一个和最后一个迭代器,也可以直接用数组的位置。
nth,要定位的第n 个元素,能对它进行随机访问.将第n_thn_th 元素放到它该放的位置上,左边元素都小于它,右边元素都大于它.
nth_element(intVect.begin(),intVect.begin()+3,intVect.end());
cout << intVect[3]<< endl;//输出排序时,第四个元素的值
输出中位数:
nth_element(intVect.begin(), intVect.begin() + intVect.size()/2, intVect.end());
cout <<
"The median is "
<< intVect[intVect.size()/2] << endl;
nth_element(intVect.begin(), intVect.begin() + 1, intVect.end(), greater<
int
>());
cout <<
"The second largest is "
<< intVect[1] << endl;
The median is 5
The second largest is 7
9 7 6 5 3 1 0