看懂STL中的sort排序
来源:互联网 发布:玩dnf网络冲突怎么办 编辑:程序博客网 时间:2024/05/17 08:56
该例子旨在说明对于自定义类型如何做排序:
方法1:重载"<"或者">"运算符,对于less函数,对应重载<,对于greater函数,对应重载>;
方法2:采用自己写的比较函数,将函数名当做形参传入sort函数中去,如:sort(v.begin(),v.end(),MysortFunction);
方法1:重载"<"或者">"运算符,对于less函数,对应重载<,对于greater函数,对应重载>;
方法2:采用自己写的比较函数,将函数名当做形参传入sort函数中去,如:sort(v.begin(),v.end(),MysortFunction);
代码测试:
#include <iostream>#include <algorithm>#include <functional>#include <vector>#include <string>using namespace std;class student{public: student(const string &a, int b) :name(a), score(b){} string name; int score; bool operator < (const student &m)const //重载小于号 { return score < m.score; } bool operator > (const student &m)const //重载大于号 { return score > m.score; }};//自定义比较函数bool MySortFunction(const student &a, const student &b){ return a.score < b.score;}int main() { vector< student> vect; student st1("Tom", 74); vect.push_back(st1); st1.name = "Jimy"; st1.score = 56; vect.push_back(st1); st1.name = "Mary"; st1.score = 92; vect.push_back(st1); st1.name = "Jessy"; st1.score = 85; vect.push_back(st1); st1.name = "Jone"; st1.score = 56; vect.push_back(st1); st1.name = "Bush"; st1.score = 52; vect.push_back(st1); st1.name = "Winter"; st1.score = 77; vect.push_back(st1); st1.name = "Andyer"; st1.score = 63; vect.push_back(st1); st1.name = "Lily"; st1.score = 76; vect.push_back(st1); st1.name = "Maryia"; st1.score = 89; vect.push_back(st1); cout << "---------------原有数据------------------" << endl; for (int i = 0; i < vect.size(); i++) cout << vect[i].name << ":\t" << vect[i].score << endl; cout << "---------------重载小于号升序排序------------" << endl; stable_sort(vect.begin(), vect.end(), less<student>()); for (int i = 0; i < vect.size(); i++) cout << vect[i].name << ":\t" << vect[i].score << endl; cout << "---------------重载大于号降序排序------------" << endl; stable_sort(vect.begin(), vect.end(), greater<student>()); for (int i = 0; i < vect.size(); i++) cout << vect[i].name << ":\t" << vect[i].score << endl; cout << "---------------自己写升序比较函数------------" << endl; stable_sort(vect.begin(), vect.end(), MySortFunction); for (int i = 0; i < vect.size(); i++) cout << vect[i].name << ":\t" << vect[i].score << endl; return 0;}运行结果:
阅读全文
0 0
- 看懂STL中的sort排序
- STL中的sort排序
- STL中的sort排序(转载)
- STL中的sort对结构体排序
- STL 排序(Sort)
- STL 排序(Sort)
- STL 排序(Sort)
- STL sort 排序
- STL - sort排序算法
- STL 排序(Sort)
- C++ STL 排序(Sort)
- STL之sort 排序
- stl sort排序
- c++STL sort()排序
- STL中的排序算法 sort stable_sort patition_sort等
- STL中的排序算法 sort stable_sort patition_sort等
- STL中的排序算法 sort stable_sort patition_sort等
- STL中的排序算法 sort stable_sort patition_sort等
- Seal Report使用教程(二)——项目文件
- 不使用第三个值,实现两个变量的互换
- 网络编程(一)--URL
- 数据库视频|自己不懂的点汇总
- Android widght之PopupWindow
- 看懂STL中的sort排序
- 带内管理
- UVA658-It's not a Bug, it's a Feature!-最短路
- C语言入门:查找子串
- 1045. 快速排序
- 南阳oj108--士兵杀敌(一)(线段树,求和)
- 集合框架(集合的继承体系结构)
- python模块以及导入出现ImportError: No module named 'xxx'问题
- CSS