生活随笔
收集整理的這篇文章主要介紹了
阿里Set
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上次面阿里巴巴。面試官問了我這樣一個(gè)問題,“C++ STL中的set是如何實(shí)現(xiàn)的”。當(dāng)時(shí)只答了二叉樹,回來查下書,原來一般是紅黑樹,后悔沒好好記住啊。。。
接著,面試官又考了我一道這樣的編程題:定義一個(gè)Student結(jié)構(gòu)體,包括name和age等數(shù)據(jù),要求編程實(shí)習(xí)在set中查找一個(gè)name == "張三",?age == 13的操作。
本來set自己用得不多,當(dāng)時(shí)一下懵了。回來查閱《C++標(biāo)準(zhǔn)程序庫(kù)》這本書,自己試著實(shí)現(xiàn)了下。
#include?<iostream>??#include?<set>??using?namespace?std;????/*Student結(jié)構(gòu)體*/??struct?Student?{??????string?name;??????int?age;??????string?sex;??};????/*“仿函數(shù)"。為Student?set指定排序準(zhǔn)則*/??class?studentSortCriterion?{??????public:??????????bool?operator()?(const?Student?&a,?const?Student?&b)?const?{??????????????/*先比較名字;若名字相同,則比較年齡。小的返回true*/??????????????if(a.name?<?b.name)??????????????????return?true;??????????????else?if(a.name?==?b.name)?{??????????????????if(a.age?<?b.age)??????????????????????return?true;??????????????????else??????????????????????return?false;??????????????}?else??????????????????return?false;??????????}??};????int?main()??{??????set<Student,?studentSortCriterion>?stuSet;????????Student?stu1,?stu2;??????stu1.name?=?"張三";??????stu1.age?=?13;??????stu1.sex?=?"male";????????stu2.name?=?"李四";??????stu2.age?=?23;??????stu2.sex?=?"female";????????stuSet.insert(stu1);??????stuSet.insert(stu2);????????/*構(gòu)造一個(gè)測(cè)試的Student,可以看到,即使stuTemp與stu1實(shí)際上并不是同一個(gè)對(duì)象,??????*但當(dāng)在set中查找時(shí),仍會(huì)查找成功。這是因?yàn)橐讯x的studentSortCriterion的緣故。??????*/??????Student?stuTemp;??????stuTemp.name?=?"張三";??????stuTemp.age?=?13;????????set<Student,?studentSortCriterion>::iterator?iter;??????iter?=?stuSet.find(stuTemp);??????if(iter?!=?stuSet.end())?{??????????cout?<<?(*iter).name?<<?endl;??????}?else?{??????????cout?<<?"Cannot?fine?the?student!"?<<?endl;??????}????????return?0;??}??
總結(jié)
以上是生活随笔為你收集整理的阿里Set的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。