资料课件讲义Savitch_ch_18_第1页
资料课件讲义Savitch_ch_18_第2页
资料课件讲义Savitch_ch_18_第3页
资料课件讲义Savitch_ch_18_第4页
资料课件讲义Savitch_ch_18_第5页
已阅读5页,还剩65页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论