




已閱讀5頁(yè),還剩65頁(yè)未讀, 繼續(xù)免費(fèi)閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Overview,18.1Iterators18.2Containers18.3GenericAlgorithms,Slide18-2,18.1,Iterators,Iterators,STLhascontainers,algorithmsandIteratorsContainersholdobjects,allofaspecifiedtypeGenericalgorithmsactonobjectsincontainersIteratorsprovideaccesstoobjectsinthecontainersyethidetheinternalstructureofthecontainer,Slide18-4,UsingDeclarations,Usingdeclarationsallowuseofafunctionornamedefinedinanamespace:usingns:fun();usingns:iterator;usingstd:vector;usingstd:vector:iterator;,Slide18-5,IteratorBasics,AniteratorisageneralizationofpointerNotapointerbutusuallyimplementedusingpointersThepointeroperationsmaybeoverloadedforbehaviorappropriateforthecontainerinternalsTreatingiteratorsaspointerstypicallyisOK.Eachcontainerdefinesanappropriateiteratortype.Operationsareconsistentacrossalliteratortypes.,Slide18-6,BasicIteratorOperations,Basicoperationssharedbyalliteratortypes+(pre-andpostfix)toadvancetothenextdataitem=and!=operatorstotestwhethertwoiteratorspointtothesamedataitem*dereferencingoperatorprovidesdataitemaccessc.begin()returnsaniteratorpointingtothefirstelementofcontainercc.end()returnsaniteratorpointingpastthelastelementofcontainerc.Analogoustothenullpointer.Unlikethenullpointer,youcanapply-totheiteratorreturnedbyc.end()togetaniteratorpointingtolastelementinthecontainer.,Slide18-7,MoreIteratorOperations,-(pre-andpostfix)movestopreviousdataitemAvailabletosomekindsofiterators.*paccessmayberead-onlyorread-writedependingonthecontainerandthedefinitionoftheiteratorp.STLcontainersdefineiteratortypesappropriatetothecontainerinternals.Somecontainersprovideread-onlyiterators,Slide18-8,Display18.1,KindsofIterators,ForwarditeratorsprovidethebasicoperationsBidirectionaliteratorsprovidethebasicoperationsandthe-operators(pre-andpostfix)tomovetothepreviousdataitem.RandomaccessiteratorsprovideThebasicoperationsandIndexingp2returnsthethirdelementinthecontainerIteratorarithmeticp+2returnsaniteratortothethirdelementinthecontainer,Slide18-9,Display18.2(1-2),ConstantandMutableIterators,Categoriesofiteratordivideintoconstantandmutableiterator.ConstantIteratorcpdoesnotallowassigningelementatpusingstd:vector:const_iterator;const_iteratorcp=v.begin();*cp=something;/illegalMutableiteratorpdoesallowchangingtheelementatp.usingstd:vector:iterator;iteratorp=v.begin();*p=something;/OK,Slide18-10,ReverseIterators,Areverseiteratorenablescyclingthroughacontainerfromtheendtothebeginning.Reverseiteratorsreversethemoreusualbehaviorof+andrp-movesthereverseiteratorrptowardsthebeginningofthecontainer.rp+movesthereverseiteratorrptowardstheendofthecontainer.reverse_iteratorrp;for(rp=c.rbegin();rp!=c.rend();rp+)process_item_at(rp);Objectcisacontainerwithbidirectionaliterators,Slide18-11,Display18.3(1-2),OtherKindsofIterators,Twootherkindsof(weaker)iteratorAninputiteratorisaforwarditeratorthatcanbeusedwithinputstreams.Anoutputiteratorisaforwarditeratorthatcanbeusedwithoutputstreams.,Slide18-12,18.2,Containers,Containers,TheSTLprovidesthreekindscontainers:SequentialContainersarecontainerswheretheultimatepositionoftheelementdependsonwhereitwasinserted,notonitsvalue.ContainerAdaptersusethesequentialcontainersforstorage,butmodifytheuserinterfacetostack,queueorotherstructure.AssociativeContainersmaintainthedatainsortedordertoimplementthecontainerspurpose.Thepositiondependsonthevalueoftheelement.,Slide18-14,SequentialContainers,TheSTLsequentialcontainersarethelist,vectoranddeque.(TheslistisnotintheSTL.)Sequentialmeansthecontainerhasafirst,element,asecondelementandsoon.AnSTLlistisadoublylinkedlist.AnSTLvectorisessentiallyanarraywhoseallocatedspacecangrowwhiletheprogramruns.AnSTLdeque(“d-que”or“deck”)isa“doubleendedqueue”.Datacanbeaddedorremovedateitherendandthesizecanchangewhiletheprogramruns.,Slide18-15,Display18.4,Display18.5,CommonContainerMembers,TheSTLsequentialcontainerseachhavedifferentcharacteristics,buttheyallsupportthesemembers:container();/createsemptycontainercontainer();/destroyscontainer,erasesallmembersc.empty()/trueiftherearenoentriesincc.size()const;/numberofentriesincontainercc=v;/replacecontentsofcwithcontentsofv,Slide18-16,MoreCommonContainerMembers,c.swap(other_container);/swapscontentsof/candother_container.c.push_back(item);/appendsitemtocontainercc.begin();/returnsaniteratortothefirst/elementincontainercc.end();/returnsaniteratortoaposition/beyondtheendofthecontainerc.c.rbegin();/returnsaniteratortothelastelement/inthecontainer.Servestoasstartof/reversetraversal.,Slide18-17,MoreCommonContainerMembers,c.rend();/returnsaniteratortoaposition/beyondtheofthecontainer.c.front();/returnsthefirstelementinthe/container(sameas*c.begin();)c.back();/returnsthelastelementinthecontainer/sameas*(-c.end();c.insert(iter,elem);/insertcopyofelementelem/beforeiteIrc.erase(iter);/removeselementiterpointsto,/returnsaniteratortoelement/followingerasure.returnsc.end()if/lastelementisremoved.,Slide18-18,MoreCommonContainerMembers,c.clear();/makescontainercemptyc1=c2/returnstrueifthesizesequaland/correspondingelementsinc1andc2are/equalc1!=c2/returns!(c1=c2)c.push_front(elem)/insertelementelematthe/frontofcontainerc./NOTimplementedforvectorduetolarge/run-timethatresults,Slide18-19,PITFALL:IteratorsandRemovingElements,Removingelementswillinvalidatessomeiterators.erasememberreturnsaniteratorpointingtothenextelementpasttheerasedelement.Withlistweareguaranteedthatonlyiteratorspointingtotheerasedelementareinvalidated.Withvectoranddeque,treatalloperationsthateraseorinsertasinvalidatingpreviousiterators.,Slide18-20,OperationSupport,Slide18-21,(X)Indicatesthisoperationissignificantlyslower.,Display18.6,TheContainerAdaptersstackandqueue,ContainerAdaptersusesequencecontainersforstoragebutsupplyadifferentuserinterface.AstackusesaLast-In-First-Outdiscipline.AqueueusesaFirst-In-First-Outdiscipline.Apriorityqueuekeepsitsitemssortedonapropertyoftheitemscalledthepriority,sothatthehighestpriorityitemisremovedfirst.Thedequeisthedefaultcontainerforbothstackandqueue.Avectorcannotbeusedforaqueueasthequeuerequiresoperationsatthefrontofthecontainer.,Slide18-22,ContainerAdapterstack,Declarations:stacks;/usesdequeasunderlyingstorestackt;/usesthespecified/containerasunderlyingcontainerforstackStacks(sequence_container);/initializesstackto/toelementsinsequence_container.Header:#includeDefinedtypes:value_type,size_typeNoiteratorsaredefined.,Slide18-23,stackMemberFunctions,Slide18-24,Display18.10(1-2),ContainerAdapterqueue,Declarations:queueq;/usesdequeasunderlyingstorequeueq;/usesthespecified/containerasunderlyingcontainerforqueueStacks(sequence_container);/initializesqueueto/toelementsinsequence_container.Header:#includeDefinedtypes:value_type,size_typeNoiteratorsaredefined.,Slide18-25,queueMemberFunctions,Slide18-26,AssociativeContainerssetandmap,Associativecontainerskeepelementssortedonasomepropertyoftheelementcalledthekey.Onlythefirstinsertionofavalueintoasethaseffect.Theorderrelationtobeusedmaybespecified:sets;Thedefaultorderistherelationaloperatorforbothsetandmap.,Slide18-27,ThesetAssociativeContainer,Declarations:sets;/usesdequeasunderlyingstoresets;/usesthespecified/orderrelationtosortelementsintheset/usesDefinedtypes:value_type,size_typeIterators:iterator,const_iterator,reverse_iterator,const_reverse_iterator,Slide18-28,setMemberFunctions,Slide18-29,Display18.12,Themapassociativecontainer,AmapisafunctiongivenasasetoforderedpairsForeachfirstinanorderedpairthereisatmostonevalue,second,thatappearsinanorderedpairinthemap.Firstandsecondcanbedifferentdatatypes,soforexampleyoucouldmapanintegertoastringTheSTLprovidesatemplateclasspairdefinedintheutilityheaderfile.Youmaywishtoreadaboutthemultisetandmultimap.SeeJosuttis,TheC+StandardLibraryAddisonWesley.,Slide18-30,Mapsasassociativearrays,Analternativeinterpretationisthatamapisanassociativearray.Forexample,numbermapc+=5associatestheinteger5withthestringc+TheeasiestwaytoaddandretrievedatafromamapistousetheoperatorHowever,ifyouattempttoaccessmapkeyandkeyisnotalreadyinthemap,thenanewentrywiththedefaultvaluewillbeadded!,Slide18-31,Display18.14(1-2),mapMemberFunctions,Slide18-32,Efficiency,TheSTLwasdesignedwithefficiencyasanimportantconsideration.STLrequirescompliantimplementationstoguaranteeamaximumrunningtime.STLimplementationsstrivetobeoptimallyefficient.SortingisusuallyspecifiedtobeO(N*log(N)whereNisthenumberofitemsbeingsortedSearchisusuallyspecifiedtobeO(log(N)whereNisthenumberofitemsbeingsearched.,Slide18-33,18.3,GenericAlgorithms,GenericAlgorithms,“GenericAlgorithm”areatemplatefunctionsthatuseiteratorsastemplateparameters.ThischapterwilluseGenericAlgorithm,Genericfunction,andSTLfunctiontemplatetomeanthesamething.Functioninterfacespecifiestask,minimumstrengthofiteratorarguments,andprovidesrun-timespecification.,Slide18-35,RunningTimesandBig-ONotation,Tobeuseful,runningtimesforanalgorithmmustspecifytimeasafunctionoftheproblemsize.Wecantimeaprogramwithastopwatchorinstrumentthecodewithcallstothesystemclocktoempiricallydeterminerunningtime.Whatproblemsdoyouseethere?Thereisabetterway.,Slide18-36,Worstcaserunningtime,Intherestofthechapterwewillalwaysmean“worstcaserunningtime”whenwespecifyarunningtime.Howdoweproceed?Dowecount“steps”or“operations”?Whatisastep?Whatisanoperation?Disagreementabounds,butmostlyweagreetocount=,boolfound=false;while(iN)Assumetargetisnotinarray.LooprunsNtimes,6operation
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝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ù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 風(fēng)電工程培訓(xùn)課件下載
- 腎內(nèi)科飲食護(hù)理宣教
- 愛護(hù)眼睛健康小班教育指南
- 大班學(xué)校安全教育
- 氣血淤積健康指導(dǎo)
- 2025年5山東省威海市中考招生考試數(shù)學(xué)真題試卷(真題+答案)
- 預(yù)防網(wǎng)戀主題班會(huì)課件
- 預(yù)防梅毒的課件模板
- 外科急腹癥患者術(shù)后護(hù)理
- 顧客管理課件
- 車輛轉(zhuǎn)讓及新能源充電樁安裝與運(yùn)營(yíng)服務(wù)合同
- 2025年視覺傳達(dá)設(shè)計(jì)考試試題及答案解析
- 貸款逾期催收保證合同范本
- 2025至2030中國(guó)鄰氨基苯甲酸市場(chǎng)發(fā)展趨勢(shì)及未來前景展望報(bào)告
- 中心血站培訓(xùn)課件
- 2025至2030中國(guó)現(xiàn)金支付行業(yè)發(fā)展分析及投資風(fēng)險(xiǎn)預(yù)警與發(fā)展策略報(bào)告
- DB 5201∕T 152.2-2025 交通大數(shù)據(jù) 第2部分:數(shù)據(jù)資源目錄
- 2025-2030中國(guó)建筑項(xiàng)目管理軟件行業(yè)應(yīng)用狀況與需求趨勢(shì)預(yù)測(cè)報(bào)告
- 中國(guó)常識(shí)課件
- 5.3.1探究酵母菌的呼吸方式課件高一上學(xué)期生物人教版必修1
- 政府采購(gòu)法律法規(guī)及操作實(shí)務(wù)
評(píng)論
0/150
提交評(píng)論