nth_element使用
来源:互联网 发布:vb识别网站验证码源码 编辑:程序博客网 时间:2024/06/09 19:39
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);
0 0
- nth_element使用
- stl nth_element使用...
- nth_element
- nth_element
- STL中的nth_element()方法的使用
- STL中的nth_element()方法的使用
- NYOJ 124 中位数(水题,nth_element()使用练习)
- STL<algorithm>中的nth_element()方法的使用
- STL中的nth_element()方法的使用
- STL中的nth_element()方法的使用
- hdu6040 Hints of sd0061【nth_element使用】
- STL 源码分析《2》----nth_element() 使用与源码分析
- std::nth_element
- nth_element()
- STL源码解析 - nth_element
- nth_element的用法
- partial_sort,partial_sort_copy,nth_element
- std::nth_element 排序
- git配置过程中出现错误的解决办法
- Objective-C 注释
- 核密度估计、混合模型,潜变量和EM算法(mixture model,latent variable and EM algorithm)
- Java桌面程序打包成exe可执行文件
- 使用性能监视器找出SQLServer硬件瓶颈
- nth_element使用
- html按钮禁用启用
- 还有一种东西叫物理引擎
- 扩展RBAC用户角色权限设计方案
- UITableView使用之----大全
- View---仿新浪引导界面
- String对象内存分配和基本数据类型的默认值与初始化相关问题
- C++魔方阵的生成
- This Handler class should be static or leaks might occur Android