C++ nth_element()函数的学习

243 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

原文链接:blog.csdn.net/roufoo/arti…

nth_element() 需要头文件。典型参数表为

nth_element(RandomIt first, RandomIt nth,  RandomIt last, Compare comp = less);

nth_element的作用就是根据nth这个参数,把容器内的元素分为2组,nth之前的都比它小,nth之后的都比它大。类似partition算法。

注意:

nth之前和之后的元素都不保证排序。

nth_element()所支持的容器中只有array, vector和deque这3种可用于随机访问的容器。别的容器不支持随机访问,所以不能用nth_element。

C++ STL里面,deque支持随机访问,stack和queue都不支持随机访问。

下面是典型用法:

 #include <iostream>
 #include <algorithm>
 #include <vector>
 ​
 using namespace std;
 ​
 bool comp1(int a, int b) {
     return a > b;
 }
 
 class comp2{
 public:
     bool operator() (int a, int b) {
         return a > b;
     }
 } cmp2;
 
 int main() {
     vector<int> vec{7, 1, 2, 6, 100};
     nth_element(vec.begin(), vec.begin() + 2, vec.end());
     cout << "after first nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
     nth_element(vec.begin(), vec.begin() + 2, vec.end(), comp1);
     cout << "after second nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
     nth_element(vec.begin(), vec.begin() + 3, vec.end(), cmp2);
     cout << "after third nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
     return 0;
 }

其输出为:

after first nth_element

 2
 1
 6
 7
 100

after second nth_element

100
 7
 6
 2
 1

after third nth_element

 6
 7
 100
 2