生活随笔
收集整理的這篇文章主要介紹了
C++类对象排序operator重载操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 類內默認含有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
總結
以上是生活随笔為你收集整理的C++类对象排序operator重载操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。