nth_element() 需要头文件<algorithm>。典型参数表为
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;
}
C++ STL nth_element 函数详解

本文介绍了C++ STL中的nth_element函数,该函数能够将容器中的元素按指定位置划分,使得该位置左侧的元素不大于该位置的元素,右侧的元素不小于该位置的元素。文章通过示例代码详细展示了nth_element函数的使用方法。
最低0.47元/天 解锁文章
1035





