std::nth_element 排序

来源:互联网 发布:自动化设备编程难点 编辑:程序博客网 时间:2024/06/08 00:42

template<class _RanIt, class _Pr> inline    void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last, _Pr _Pred)template<class _RanIt> inlinevoid 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);


	
				
		
原创粉丝点击