类内默认含有this
指针,bool operator==(const T& a)
类外则需要写两个参数,bool operator==(const T& a, const T& b)
class People
{
public :
string name;
int id;
People ( string n, int i) : name ( n) , id ( i) { }
bool operator == ( const People& a)
{
return id == a. id && name== a. name;
}
bool operator < ( const People& a)
{
if ( id == a. id)
return name < a. name;
return id < a. id;
}
} ;
bool operator == ( const People& a, const People& b)
{
return a. id == b. id && a. name== b. name;
}
bool operator < ( const People & a, const People& b)
{
if ( a. id == b. id)
return a. name < b. name;
return a. id < b. id;
}
int main ( )
{
vector< People> vec;
vec. push_back ( People ( "Michael" , 23 ) ) ;
vec. push_back ( People ( "James" , 23 ) ) ;
vec. push_back ( People ( "Kobe" , 24 ) ) ;
vec. push_back ( People ( "James" , 23 ) ) ;
cout << "-----按id, then name排序----" << endl;
sort ( vec. begin ( ) , vec. end ( ) ) ;
for ( auto & v : vec)
cout << v. id << " " << v. name << endl;
cout << "------去重------------------" << endl;
vec. erase ( unique ( vec. begin ( ) , vec. end ( ) ) , vec. end ( ) ) ;
for ( auto & v : vec)
cout << v. id << " " << v. name << endl;
cout << "-----按名称排序-------------" << endl;
sort ( vec. begin ( ) , vec. end ( ) , [ ] ( People& a, People& b)
{
return a. name < b. name;
} ) ;
for ( auto & v : vec)
cout << v. id << " " << v. name << endl;
return 0 ;
}
运行结果:
-- -- - 按id, then name排序-- --
23 James
23 James
23 Michael
24 Kobe
-- -- -- 去重-- -- -- -- -- -- -- -- --
23 James
23 Michael
24 Kobe
-- -- - 按名称排序-- -- -- -- -- -- -
23 James
24 Kobe
23 Michael