C++<algorithm>中sort的比较函数写法
2015-08-10 10:54
465 查看
转自:http://www.wl566.com/biancheng/98907.html
C++<algorithm>中sort的比较函数写法,有需要的朋友可以参考下。
定义排序函数:
方法1:声明外部比较函数
注意:比较函数必须写在类外部(全局区域)或声明为静态函数
当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。
否则,会出现错误
方法2:重载类的比较运算符
方法3:声明比较类
C++<algorithm>中sort的比较函数写法,有需要的朋友可以参考下。
定义排序函数:
方法1:声明外部比较函数
bool Less(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } std::sort(sutVector.begin(), stuVector.end(), Less);
注意:比较函数必须写在类外部(全局区域)或声明为静态函数
当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。
否则,会出现错误
方法2:重载类的比较运算符
bool operator<(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } std::sort(sutVector.begin(), stuVector.end());
方法3:声明比较类
struct Less { bool operator()(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } }; std::sort(sutVector.begin(), stuVector.end(), Less());
相关文章推荐
- C/C++知识要点5——智能指针原理及自定义实现
- LeetCode 211. Add and Search Word - Data structure design
- I2C总线之(三)---以C语言理解IIC
- C++学习笔记与思考_2 --const限定符及其引用,typedef符号
- C++ Builder XE8 安卓开发之使用TIdThreadComponent控件接收客户端的数据
- C语言-04-函数
- c++ 显示调用dll
- C++/C语言_宏函数存在的问题
- C++单例模式
- [leetcode-92]Reverse Linked List II(c++)
- 详解C语言中的常量指针和指针常量
- C++_inline内联函数
- 第二章 cpp-empty-test:还是那个HelloWorld!
- 最小二乘法拟合直线 C++/OpenCV
- 贪心算法之Stripies
- c++命名空间
- C/C++ const使用
- 详解C语言中const关键字的用法
- 跳
- C++常用术语及其英文翻译的含义和简单用途总结(六)