std::nth_element 排序


template<class _RanIt, class _Pr> inline
    void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last, _Pr _Pred)

template<class _RanIt> inline
	void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last)

该函数的作用为将迭代器指向的从_First 到 _last 之间的元素进行二分排序,以_Nth 为分界,前面都比 _Nth 小(大),后面都比之大(小);但是两段内并不有序。

特别适用于找出前k个最大(最小)的元素。


例如:

vector<int> temp;
//
// calc the value of temp;
//

nth_element(temp.begin(), temp.begin()+10,temp.end());

// 

如今遇到一个问题:要对结构体按照自定义的方式进行排序,那么可以用到第一个方法了。

首先定义一个返回bool类型的比较函数,然后将函数名作为参数传入。

例如:现要求按照价格挑出最贵的10本书。

bool prizeCompare(const CBook &b1, const CBook &b2)
{
      return b1.prize>b2.prize;
}

// ......

vector<CBook> books;

//挑出最贵的10本书

std::nth_element(books.begin(), books.begin()+10,books.end(), prizeCompare);
books.resize(10);
  

更深一步,如今只对物理学的书进行排序,现有一个vector<int> physics 只记录了书在books中的序号。要求挑出10本最贵的物理学的书。

代码如下:

struct Cmp{
    std::vector<Book> _list;
    Cmp(const std::vector<Book> &_books):_list(_books){}
    bool operator()(int idx1,int idx2)
    {
          return _list[idx1].prize>_list[idx2].prize;
     }
     
  }   
//......

vector<CBook> books;
vector<int> physics;

for(int i=0;i<books.size();i++){ if(books[i].category == PHYSICS) physics.push_back(i);
}

//......

std::nth_element(physics.begin(), physics.begin()+10,physics.end(), Cmp(books));
physics.resize(10);










  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值