STL中sort的用法举例
2010-07-03 15:13
393 查看
date:2010-07-02
对象数组排序这里展示了两种方法,定义比较函数或通过重载比较运算符使得类本身是可以比较的,就像基本类型一样。
定义比较函数,既可以通过定义比较运算符(如operator <),也可以直接定义函数(如compare)。
重载运算符之后,可以在sort函数中通过less或greater或less_equal等来调整升序还是降序,默认是升序。
另外,重载运算符后,函数bool operator < 就不要了,否则用g++编译出错。
参考:http://www.cppblog.com/mzty/archive/2009/11/17/1770.html
对象数组排序这里展示了两种方法,定义比较函数或通过重载比较运算符使得类本身是可以比较的,就像基本类型一样。
定义比较函数,既可以通过定义比较运算符(如operator <),也可以直接定义函数(如compare)。
重载运算符之后,可以在sort函数中通过less或greater或less_equal等来调整升序还是降序,默认是升序。
另外,重载运算符后,函数bool operator < 就不要了,否则用g++编译出错。
#include <algorithm> #include <iostream> #include <vector> using namespace std; class MyClass { public: int id; MyClass() {} MyClass(int i): id( i ) {} bool operator < ( const MyClass &b ) const { return id < b.id; } bool operator > ( const MyClass &b ) const { return id > b.id; } }; /* bool operator < ( MyClass a, MyClass b ) { return a.id < b.id; } */ bool compare( MyClass a, MyClass b ) { return a.id < b.id; } int main() { //数组 cout<<"数组"<<endl; MyClass arr[10]; srand(time(NULL)); for( int i = 0; i < 10; i++ ) arr[i].id = rand()%101; cout<<"before sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<arr[i].id<<endl; sort(arr,arr+10,less<MyClass>()); cout<<"after sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<arr[i].id<<endl; //动态数组vector cout<<"动态数组vector"<<endl; vector<MyClass> list; for( int i = 0; i < 10; i++ ) list.push_back( MyClass( rand()%101 ) ); cout<<"before sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list[i].id<<endl; sort(list.begin(),list.end(),greater<MyClass>()); cout<<"after sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list[i].id<<endl; //定义比较函数 cout<<"定义比较函数"<<endl; vector<MyClass> list2; for( int i = 0; i < 10; i++ ) list2.push_back( MyClass( rand()%101 ) ); cout<<"before sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list2[i].id<<endl; sort(list2.begin(),list2.end(),compare); cout<<"after sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list2[i].id<<endl; //使得类本身就是可以比较的 cout<<"使得类本身就是可以比较的"<<endl; vector<MyClass> list3; for( int i = 0; i < 10; i++ ) list3.push_back( MyClass( rand()%101 ) ); cout<<"before sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list3[i].id<<endl; sort(list3.begin(),list3.end()); cout<<"after sort"<<endl; for( int i = 0; i < 10; i++ ) cout<<list3[i].id<<endl; return 0; }
参考:http://www.cppblog.com/mzty/archive/2009/11/17/1770.html
相关文章推荐
- STL中sort的用法举例
- STL中泛型算法find_if()与sort()的应用举例及详解
- STL中泛型算法find_if()与sort()的应用举例及详解
- stl里list的sort()用法
- STL中sort用法小实例
- C++STL 排序函数sort和qsort的用法与区别
- STL中常用的vector,map,set,sort 用法
- STL中sort()函数的用法
- C++ stl队列Queue用法介绍:删除,插入等操作代码举例
- STL中的常用的vector,map,set,sort用法
- STL 中sort、qsort 的用法
- Linux sort的选项(参数)与用法举例
- STL中常用的vector,map,set,sort 用法
- STL中的常用的vector,map,set,Sort用法
- STL中的常用的vector,map,set,Sort用法
- STL:sort()用法
- STL:algorithm中排序函数sort(升序排列函数)和reverse(反转排列函数)的简单用法
- stl里list的sort()用法
- STL之sort和for_each的用法
- c++ stl容器set成员函数介绍及set集合插入,遍历等用法举例