C++之STL学习

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

扫描二维码关注公众号,回复: 5063624 查看本文章

The second largest is 7

9 7 6 5 3 1 0

猜你喜欢

转载自blog.csdn.net/wxq_1993/article/details/86616910
今日推荐