1、功能
使用默认比较器
template <class RandomAccessIterator>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
自定义元素比较器
template <class RandomAccessIterator, class Compare>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,RandomAccessIterator last, Compare comp);
重新排列[first,last),使第n个位置的元素是排序序列中该位置的元素。
剩下的其他元素没有任何特定的顺序,除了第n个元素之前的元素都不大于它,第n个元素之后的元素都不小于它。 第一个版本使用<操作符比较元素,第二个版本使用comp操作符比较元素。
总的来说比较像用快排找第n大的元素。
2、参数
1. first,last
表明排序区间
2. nth
所需的第nth大元素的迭代器
3. comp
接受范围内的两个元素作为参数,并返回可转换为bool类型的值的双参数函数。
3、示例
#include <iostream> // std::cout
#include <string> // std::string, std::stoi
#include <vector>
#include<algorithm>
using namespace std;
struct node
{
int i,j;
};
bool cmp(node a, node b)
{
//先按照i的大小从大到小排
if(a.i != b.i) return a.i > b.i;
//如果i一样就按照j的大小从大到小排
else return a.j > b.j;
}
int main ()
{
vector<int> v_int;
vector<node> v_node;
int a_int[10];
for(int i = 0; i < 10; i ++)
{
v_int.push_back(i);
a_int[i] = i;
for(int j = 0; j < 10; j ++)
{
v_node.push_back({i,j});
}
}
nth_element(v_int.begin(),v_int.begin() + 5, v_int.end());
nth_element(v_node.begin(),v_node.begin() + 5, v_node.end(),cmp);
nth_element(a_int,a_int + 5, a_int + 10);
cout << "v_int :"<< *(v_int.begin() + 5) << endl;
cout << "a_int :"<< *(a_int + 5) << endl;
cout << "v_node :"<< v_node[5].i << " " << v_node[5].j << endl;
return 0;
}
输出
v_int :5
a_int :5
v_node :9 4
4、 时间复杂度
O ( n ) O(n) O(n)
参考资料
https://www.cplusplus.com/reference/algorithm/nth_element/