对象数组排序这里展示了两种方法,定义比较函数或通过重载比较运算符使得类本身是可以比较的,就像基本类型一样。
定义比较函数,既可以通过定义比较运算符(如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;
- }