




已閱讀5頁,還剩65頁未讀, 繼續(xù)免費(fèi)閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
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等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- “互聯(lián)網(wǎng)+”社交媒體營銷計(jì)劃
- 2025年底電壓反光杯燈項(xiàng)目市場調(diào)查研究報(bào)告
- 金融行業(yè)投資顧問出資證明書(5篇)
- 外研版小學(xué)英語五年級上冊課堂管理計(jì)劃
- 公共圖書館圖書采購合同范文
- 酒店消防安全自查及整改措施
- 汽車保養(yǎng)中心綠色經(jīng)營措施
- 三年級下冊科技創(chuàng)新實(shí)踐活動計(jì)劃
- 一顆頑強(qiáng)的種子寫物4篇
- 2025年湖南美術(shù)出版社二年級下冊校外美術(shù)實(shí)踐計(jì)劃
- 金屬非金屬地下礦山緊急避險(xiǎn)系統(tǒng)建設(shè)規(guī)范培訓(xùn)
- 北京海淀2025屆高考語文三模試卷含解析
- 地域文化(專)-終結(jié)性考試-國開(SC)-參考資料
- 《卵巢無性細(xì)胞瘤》課件
- PRP注射治療膝關(guān)節(jié)炎
- 第一次電力工程例會發(fā)言稿
- 安徽省江南十校2023-2024學(xué)年高一下學(xué)期5月階段聯(lián)考化學(xué)試題2
- 東方電影學(xué)習(xí)通超星期末考試答案章節(jié)答案2024年
- (完整)注冊安全工程師考試題庫(含答案)
- 2024年貴州省貴陽市中考生物地理合卷試題(含答案逐題解析)
- 山西省電子政務(wù)外網(wǎng)初步設(shè)計(jì)方案
評論
0/150
提交評論