C++之set自定義排序問題
set簡介
set一般插入元素時,默認使用關(guān)鍵字類型的<
運算符來比較兩個關(guān)鍵字,
故一般插入后為升序,但是針對自定義數(shù)據(jù)結(jié)構(gòu),
如結(jié)構(gòu)體,沒有<
運算符,故無法進行比較。
針對自定義數(shù)據(jù)結(jié)構(gòu)或者說自定義set排序規(guī)則有如下幾種方法:
方法一 重載<
在自定義結(jié)構(gòu)體中重載<
則可以實現(xiàn)默認排序,
示例代碼如下:
#include<iostream> #include<set> using namespace std; struct Students { string id; int age,height; Students(string s,int a,int h):id(s),age(a),height(h){} Students() {} bool operator <(const Students &s) const { if(id!=s.id) return id<s.id; else return age<s.age; } }; int main(){ set<Students> se; se.insert(Students("zhou",12,134)); se.insert(Students("wu",13,42)); se.insert(Students("zheng",34,43)); se.emplace("wang",13,43); se.emplace("zhou",23,43); for(auto it=se.begin();it!=se.end();it++){ cout<<it->id<<" "<<it->age<<" "<<it->height<<endl; } return 0; }
運行結(jié)果如下:
方法二 重載()
示例代碼如下:
#include<iostream> #include<set> using namespace std; struct Students { string id; int age,height; Students(string s,int a,int h):id(s),age(a),height(h){} Students() {} }; class comp{ public: bool operator()(const Students &s1,const Students &s2){ if(s1.id!=s2.id) return s1.id<s2.id; return s1.age<s2.age; } }; int main(){ set<Students,comp> se; se.insert(Students("zhou",12,134)); se.insert(Students("wu",13,42)); se.insert(Students("zheng",34,43)); se.emplace("wang",13,43); se.emplace("zhou",23,43); for(auto it=se.begin();it!=se.end();it++){ cout<<it->id<<" "<<it->age<<" "<<it->height<<endl; } return 0; }
方法三 參考《C++ primer(第五版)》
示例代碼如下:
#include<iostream> #include<set> using namespace std; struct Students { string id; int age,height; Students(string s,int a,int h):id(s),age(a),height(h){} Students() {} }; bool cmp(const Students &s1,const Students &s2){ if(s1.id!=s2.id) return s1.id<s2.id; return s1.age<s2.age; } int main(){ set<Students,decltype(cmp)*> se(cmp); se.insert(Students("zhou",12,134)); se.insert(Students("wu",13,42)); se.insert(Students("zheng",34,43)); se.emplace("wang",13,43); se.emplace("zhou",23,43); for(auto it=se.begin();it!=se.end();it++){ cout<<it->id<<" "<<it->age<<" "<<it->height<<endl; } return 0; }
上述代碼中,用decltype
來指出自定義操作的類型。
當使用decltype
來獲得一個函數(shù)指針類型時,必須加上一個*
來指出我們要使用一個給定函數(shù)類型的指針。
用cmp
來初始化se
對象,這表示當我們向se
中插入元素時,通過調(diào)用cmp
來為這些元素排序。
可以使用cmp
代替&cmp
作為構(gòu)造函數(shù)的參數(shù),因為當我們使用一個函數(shù)的名字時,在需要的情況下會自動轉(zhuǎn)化為一個指針,使用&cmp
效果也是一樣的。
insert 和 emplace 的使用
emplace
對應(yīng)insert
,emplace_back
對應(yīng)于push_back
;
但是insert
和push_back
是直接將對象拷貝至容器當中,而emplace
和emplace_back
是先調(diào)用存儲對象構(gòu)造函數(shù),在內(nèi)存中生成對象,然后拷貝至容器中。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
c語言實現(xiàn)從源文件從文本到可執(zhí)行文件經(jīng)歷的過程
這篇文章主要介紹了c語言實現(xiàn)從源文件從文本到可執(zhí)行文件經(jīng)歷的過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07C語言數(shù)據(jù)結(jié)構(gòu)之順序數(shù)組的實現(xiàn)
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)之順序數(shù)組的實現(xiàn)的相關(guān)資料,這里提供實現(xiàn)實例,希望通過本文能幫助到大家,需要的朋友可以參考下2017-08-08Linux下控制(統(tǒng)計)文件的生成的C代碼實現(xiàn)
這篇文章主要介紹了Linux下控制(統(tǒng)計)文件的生成的C代碼實現(xiàn),感興趣的小伙伴們可以參考一下2016-01-01