1 回答

TA贡献1998条经验 获得超6个赞
nth_element()是一个典型的部分排序算法。
它的第1和第3个参数,定义的是排序的范围(或则说nth_element这个算法或函数的作用范围),称着first和last,是一个[ )区间。在你的例子,分别对应那个vector的begin和end;
第2个参数的意思是:如果一个序列的first和last半包含的范围内,如果这个序列被排序了,那个第n个位置上的元素应该是什么。---- 白话的解释就是:如果给你一堆数据,我想看看中间值是多少,第2大的数是什么? 你该如何解决呢? 全排序当然可以,但如果数据多,效率也许就差了。这是只有部分排序即可,也就是说只有这第n个的位置被排对了,那么其他的就不管了,排序就可以解释了。-- 这是nth_element的应用意义。
以你的代码为例:你的第2个参数是intVect.begin()+3,就是想看看intVect这个序列中,【如果排序的话】,它的第4个应该是多少?这个intVect如果全排序,应该是:
0 1 3 5 6 7 9,
因此nth_element在确保第4个元素=5的时候,就停止排序了。 因此你后面输出intVect的值是:
1 0 3 5 9 6 7
就是第4个=5后,当时intVect的值。
一般在nth_element()后,都有一个类似这样的语句:
12 | nth_element(intVect.begin(),intVect.begin()+3,intVect.end()); cout << intVect[3]<< endl; |
给你添加一点代码,体会一下nth_element的概念,它其实可以有【第4个参数】的:
1234 | 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; |
之后在看看intVect的输出:
123 | The median is 5 The second largest is 7 9 7 6 5 3 1 0 |
- 1 回答
- 0 关注
- 308 浏览
添加回答
举报