C++ nth_element 介绍

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值