![C-程序設(shè)計(jì)教學(xué)課件chapter-6-template-Part2_第1頁(yè)](http://file4.renrendoc.com/view8/M00/2C/37/wKhkGWbvt5yAOxtPAABSvuj9H8k448.jpg)
![C-程序設(shè)計(jì)教學(xué)課件chapter-6-template-Part2_第2頁(yè)](http://file4.renrendoc.com/view8/M00/2C/37/wKhkGWbvt5yAOxtPAABSvuj9H8k4482.jpg)
![C-程序設(shè)計(jì)教學(xué)課件chapter-6-template-Part2_第3頁(yè)](http://file4.renrendoc.com/view8/M00/2C/37/wKhkGWbvt5yAOxtPAABSvuj9H8k4483.jpg)
![C-程序設(shè)計(jì)教學(xué)課件chapter-6-template-Part2_第4頁(yè)](http://file4.renrendoc.com/view8/M00/2C/37/wKhkGWbvt5yAOxtPAABSvuj9H8k4484.jpg)
![C-程序設(shè)計(jì)教學(xué)課件chapter-6-template-Part2_第5頁(yè)](http://file4.renrendoc.com/view8/M00/2C/37/wKhkGWbvt5yAOxtPAABSvuj9H8k4485.jpg)
版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
C++ProgrammingChapter6TemplatesandSTLPartⅡIndex
1.IntroductiontoSTL
2.Containers
2.1SequenceContainers
2.2AssociativeContainers
2.3Containeradapters
3.Iterators
4.Algorithms1.IntroductiontoSTL
TheStandardTemplateLibrary(STL):
AlibraryofstandardtemplatesVerypowerfulVeryfastVeryflexible
Turnsoutyouwon'tactuallyhavetocodeanytemplateclassesyourselfanyway
It'sallbeendoneforyou1.IntroductiontoSTL
Thestandardtemplatelibrary(STL)contains:Containers,Algorithms,andIterators
Acontainerisawaythatstoreddataisorganizedinmemory,forexampleanarrayofelements.
AlgorithmsintheSTLareproceduresthatareappliedtocontainerstoprocesstheirdata,forexamplesearchforanelementinanarray,orsortanarray.
Iteratorsareageneralizationoftheconceptofpointers,theypointtoelementsinacontainer,forexampleyoucanincrementaniteratortopointtothenextelementinanarray1.IntroductiontoSTL
AlgorithmsuseiteratorstointeractwithobjectsstoredincontainersContainerContainerIteratorAlgorithmObjectsIteratorIteratorAlgorithmIteratorAlgorithm2.Containers
Acontainerisawaytostoredata,eitherbuilt-indatatypeslikeintandfloat,orclassobjects.
Threetypesofcontainers:Sequencecontainers,AssociativecontainersandContaineradapters2.1SequenceContainers
Asequencecontainerstoresasetofelementsinsequence,inotherwordseachelement(exceptforthefirstandlastone)isprecededbyonespecificelementandfollowedbyanother,<vector>,<list>and<deque>aresequentialcontainers
InanordinaryC++arraythesizeisfixedandcannotchangeduringrun-time,itisalsotedioustoinsertordeleteelements.Advantage:quickrandomaccess.2.1SequenceContainers
<vector>isanexpandablearraythatcanshrinkorgrowinsize,butstillhasthedisadvantageofinsertingordeletingelementsinthemiddle.
<list>isadoublelinkedlist(eachelementhaspointstoitssuccessorandpredecessor),itisquicktoinsertordeleteelementsbuthasslowrandomaccess.
<deque>isadouble-endedqueue,thatmeansonecaninsertanddeleteelementsfrombothends,itisakindofcombinationbetweenastack(lastinfirstout)andaqueue(firstinfirstout)andconstitutesacompromisebetweena<vector>anda<list>.2.1.1VectorContainerintarray[5]={12,7,9,21,13};vector<int>v(array,array+5);12792113v.pop_back();v.push_back(15);127921127921150123412792115v.begin();v[3]2.1.1VectorContainers#include<vector>#include<iostream>vector<int>v(3);//createavectorofintsofsize3v[0]=23;v[1]=12;v[2]=9;//vectorfullv.push_back(17);//putanewvalueattheendofarrayfor(inti=0;i<v.size();i++)//memberfunctionsize()ofvectorcout<<v[i]<<””;//randomaccesstoi-thelementcout<<endl;2.1.1VectorContainer#include<vector>#include<iostream>intarr[]={12,3,17,8};//standardCarrayvector<int>v(arr,arr+4);//initializevectorwithCarraywhile(!v.empty())//untilvectorisempty{cout<<v.back()<<””;//outputlastelementofvectorv.pop_back();//deletethelastelement}cout<<endl;2.1.2ListContainer
AnSTLlistcontainerisadoublelinkedlist,inwhicheachelementcontainsapointertoitssuccessorandpredecessor.
Itispossibletoaddandremoveelementsfrombothendsofthelist
Listsdonotallowrandomaccessbutareefficienttoinsertnewelementsandtosortandmergelists2.1.2ListContainerintarray[5]={12,7,9,21,13};list<int>li(array,array+5);12792113li.pop_back();li.push_back(15);12792112792115li.pop_front();li.push_front(8);7921812792115li.insert()7121721232.2AssociativeContainers
Anassociativecontainerisnon-sequentialbutusesakeytoaccesselements.Thekeys,typicallyanumberorastring,areusedbythecontainertoarrangethestoredelementsinaspecificorder,forexampleinadictionarytheentriesareorderedalphabetically.2.2AssociativeContainers
A<set>storesanumberofitemswhichcontainkeys.Thekeysaretheattributesusedtoordertheitems,forexampleasetmightstoreobjectsoftheclassPersonwhichareorderedalphabeticallyusingtheirname
A<map>storespairsofobjects:akeyobjectandanassociatedvalueobject.A<map>issomehowsimilartoanarrayexceptinsteadofaccessingitselementswithindexnumbers,youaccessthemwithindicesofanarbitrarytype.
<set>and<map>onlyallowonekeyofeachvalue,whereas<multiset>and<multimap>allowmultipleidenticalkeyvalues.2.3Containeradapters
Thereareafewclassesactingaswrappersaroundothercontainers,adaptingthemtoaspecificinterface
stack–ordinaryLIFO
queue–single-endedFIFO
priority_queue–thesortingcriterioncanbespecified
Programmerscanspecifytheunderlyingdatatype3.Iterators
Iteratorsarepointer-likeentitiesthatareusedtoaccessindividualelementsinacontainer.
Oftentheyareusedtomovesequentiallyfromelementtoelement,aprocesscallediteratingthroughacontainer.vector<int>array_17vector<int>::iterator42312Theiteratorcorrespondingtotheclassvector<int>isofthetypevector<int>::iteratorsize_43.Iterators
Thememberfunctionsbegin()andend()returnaniteratortothefirstandpastthelastelementofacontainer.vector<int>varray_v.begin()1742312v.end()size_43.Iterators
Onecanhavemultipleiteratorspointingtodifferentoridenticalelementsinthecontainervector<int>varray_i1174i22312i3size_43.Iterators#include<vector>#include<iostream>intarr[]={12,3,17,8};//standardCarrayvector<int>v(arr,arr+4);//initializevectorwithCarrayfor(vector<int>::iteratori=v.begin();i!=v.end();i++)//initializeiwithpointertofirstelementofv//i++incrementiterator,moveiteratortonextelement{cout<<*i<<””;//de-referencingiteratorreturnsthe//valueoftheelementtheiteratorpointsat}cout<<endl;3.Iterators#include<vector>#include<iostream>intmax(vector<int>::iteratorstart,vector<int>::iteratorend){intm=*start;while(start!=stop){if(*start>m)m=*start;++start;}returnm;}cout<<”maxofv=”<<max(v.begin(),v.end());3.Iterators
Noteveryiteratorcanbeusedwitheverycontainerforexamplethelistclassprovidesnorandomaccessiterator
Everyalgorithmrequiresaniteratorwithacertainlevelofcapabilityforexampletousethe[]operatoryouneedarandomaccessiterator
Iteratorsaredividedintofivecategoriesinwhichahigher(morespecific)categoryalwayssubsumesalower(moregeneral)category,e.g.Analgorithmthatacceptsaforwarditeratorwillalsoworkwithabidirectionaliteratorandarandomaccessiterator.inputforwardbidirectionalrandomaccessoutput3.Iterators
Containersanditeratorscategories
vector–Randomaccessiterator
deque–Randomaccessiterator
list–Bidirectionaliterator
set,multiset–Bidirectionaliterator,dataisconstant
map,multimap–Bidirectionaliterator,keyisconstant
Containeradapters(stack,queueandpriority_queue)–Donotsupportiterators4.Algorithms
Implementsimple,ornot-so-simpleloopsonranges
copy,find,butalsopartition,sort,next-permutation
Specifytheirneedintermsofiteratorcategories
TheydonotcareabouttheexactclassMustpayattentiontotheiteratorsprovidedbycontainers
Oftenexistinseveralversions
Oneusesdefaultcomparison,user-definedvalueOthercallsuser-providedpredicate,function4.Algorithms
Algorithmsvs.memberfunctions
Algorithmsaresimple,generic.Theyknownothingaboutthecontainerstheyworkontemplate<classInpItor,classUnaryFunc>inlineUnaryFunctionfor_each(InpItorFirst,InpItorLast,UnaryFuncFunc){for(;First!=Last;++First)Func(*First);return(Func);}
Specializedalgorithmsmayhavebetterperformance,thosealgorithmsareimplementedasmemberfunctions.Usememberfunctionswhentheyexisteg.list::sort()vs.sort()4.Algorithms
For_Each()Algorithm#include<vector>#include<algorithm>#include<iostream>voidshow(intn){cout<<n<<””;}intarr[]={12,3,17,8};//standardCarrayvector<int>v(arr,arr+4);//initializevectorwithCarray//list<int>isalsookeyfor_each(v.begin(),v.end(),show);//applyfunctionshow//toeachelementofvectorv4.Algorithms
Find()Algorithm#include<vector>#include<algorithm>#include<iostream>intkey;intarr[]={12,3,17,8,34,56,9};//standardCarrayvector<int>v(arr,arr+7);//initializevectorwithCarrayvector<int>::iteratoriter;cout<<”entervalue:”;cin>>key;iter=find(v.begin(),v.end(),key);//findsintegerkeyinvif(iter!=v.end())//foundtheelementcout<<”Element”<<key<<
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 高鐵建設(shè)項(xiàng)目合作開(kāi)發(fā)協(xié)議
- 農(nóng)業(yè)資源管理實(shí)務(wù)手冊(cè)
- 放射科醫(yī)生雇傭合同
- 養(yǎng)殖場(chǎng)轉(zhuǎn)讓協(xié)議合同
- 汽車融資租賃合同
- 2025年克孜勒蘇州道路客貨運(yùn)輸從業(yè)資格證b2考試題庫(kù)
- 小學(xué)二年級(jí)下冊(cè)數(shù)學(xué)除法口算題專項(xiàng)訓(xùn)練
- 2025年吉林貨運(yùn)從業(yè)資格證考試題技巧及答案
- 2025年毫州貨運(yùn)上崗證考試考哪些科目
- 電力系統(tǒng)集成合同(2篇)
- 膿包瘡護(hù)理查房
- 《信號(hào)工程施工》課件 項(xiàng)目一 信號(hào)圖紙識(shí)讀
- 設(shè)備日常維護(hù)及保養(yǎng)培訓(xùn)
- 設(shè)計(jì)院個(gè)人年終總結(jié)
- 中石油高空作業(yè)施工方案
- 避孕藥具知識(shí)培訓(xùn)
- 醫(yī)保違規(guī)檢討書(shū)
- 鋼結(jié)構(gòu)實(shí)習(xí)報(bào)告
- 2024年建房四鄰協(xié)議范本
- FTTR-H 全光組網(wǎng)解決方案裝維理論考試復(fù)習(xí)試題
- 2024年廣東佛山市中醫(yī)院三水醫(yī)院招聘61人歷年高頻考題難、易錯(cuò)點(diǎn)模擬試題(共500題)附帶答案詳解
評(píng)論
0/150
提交評(píng)論