课件文稿教案mastering the17stl make full use of standard library components_第1页
课件文稿教案mastering the17stl make full use of standard library components_第2页
课件文稿教案mastering the17stl make full use of standard library components_第3页
课件文稿教案mastering the17stl make full use of standard library components_第4页
课件文稿教案mastering the17stl make full use of standard library components_第5页
已阅读5页,还剩38页未读 继续免费阅读

下载本文档

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

文档简介

MasteringtheC++17MakefulluseofthestandardlibrarycomponentsinArthurBIRMINGHAM-MasteringtheC++17Copyright©2017PacktAllrights .Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisFirstpublished:SeptemberProductionPublishedbyPacktPublishing. 35LiveryStreetB32PB,ISBN978-1-78712-682-CopyArthurSafisArthurProjectWillPrajaktaWill MerintThomasSafisSandeep lContentDevelopmentLawrenceNileshTechnicalDhirajAbouttheArthurO'DwyerhasusedmodernC++inhisdayjobforabouttenyears--sincethedayswhen"modernC++"meant"classicC++."Between2006and2011heworkedontheGreenHillsC++compiler.Since2014hehasorganizedaweeklyC++meetupintheSanFranciscoBayArea,andhespeaksregularlyontopicssuchasthosetobefoundinthisbook.Laterthisyear,hewillattendanISOC++committeemeetingforthesecondtime.ThisishisfirstAbouttheWillBrennanisaC++/PythondeveloperbasedinLondonwithexperienceworkingonhighperformanceimageprocessingandmachinelearningapplications.Youcanvisithis linkat Forsupportfilesanddownloadsrelatedtoyourbook,pleaseDidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.Pandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat formore youcanalsoreadacollectionoftechnicalarticles,signupforarangeofnewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks. Getthemostin-demandsoftwareskillswithMapt.MaptgivesyoufullaccesstoallPacktbooksand courses,aswellasindustry-leadingtoolstohelpyounyour aldevelopmentandadvanceyourcareer.WhyFullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebCustomerThanksforpurchasingthisPacktbook.AtPackt,qualityisattheheartofoureditorialprocess.Tohelpusimprove,pleaseleaveusanhonestreviewonthisbook'sAmazonpageathttp X.Ifyou'dliketojoinourteamofregularreviewers,youcan usat .WeawardourregularreviewerswitheBooksandsinexchangefortheirvaluablefeedback.Helpusberelentlessinimprovingourproducts!TableofWhatthisbookcoversWhatyouneedforthisbookWhothisbookisforReaderfeedbackCustomerDownloadingtheexamplecodeClassicalPolymorphismandGenericConcretemonomorphicfunctionsClassicallypolymorphicfunctionsGenericprogrammingwithtemtes torsandTheproblemwithintegerindicesOnbeyondpointersConst Apairofi torsdefinesarange torcategoriesInputandoutputi PuttingitalltogetherThedeprecatedstd::i The tor-PairAnoteaboutRead-onlyrangealgorithmsShuntingdatawithVariationsonatheme-std::moveandstd::move_i Complicatedcopyingwithstd::transformWrite-onlyrangeAlgorithmsthataffectobjectlifetimeOurfirstpermutativealgorithm:std::sortSwap,reversing,andpartitioningRotationandpermutationHeapsandheapsortMergesandmergesortSearchingandinsertinginasortedarraywithstd::lower_boundDeletingfromasortedarraywithstd::remove_ifTheContainerThenotionofThesimplestcontainer:std::array<T,N>Theworkhorse:std::vector<T>ResizingaInsertinganderasinginastd::vectorPitfallswithvector<bool>Pitfallswithnon-noexceptmoveThespeedyhybrid:Aparticularsetofskills:WhatarethespecialskillsofRoughingitwithingwithstd::stack<T>andstd::queue<T>Theusefuladaptor:std::priority_queue<T>Thetrees:std::set<T>andstd::map<K,V>AnoteabouttransparentOddballs:std::multiset<T>andstd::multimap<K,MovingelementswithoutmovingThehashes:std::unordered_set<T>andstd::unordered_map<K,V>LoadfactorandbucketlistsWheredoesthememorycomefrom?VocabularyThestoryofTaggingreferencetypeswithreference_wrapperC++11andalgebraictypesWorkingwithstd::tupleManipulatingtuplevaluesAnoteaboutnamedclassesExpressingalternativeswithstd::variantVisitingWhataboutmake_variant?andanoteonvaluesemanticsDelayinginitializationwithstd::optionalRevisitingInfinitealternativeswithstd::anyversuspolymorphicclasstypesTypeerasureinanutsstd::anyandAgainwiththetypeerasure:std::functionstd::function,copyability,andallocationSmartTheoriginsofsmartSmartpointersneverAutomaticallymanagingmemorywithstd::unique_ptr<T>WhyC++doesn'thavethefinallykeywordCustomizingthedeletioncallbackManagingarrayswithstd::unique_ptr<T[]>Referencecountingwithstd::shared_ptr<T>Don'tdouble-HoldingnullablehandleswithTalkingaboutoneselfwithstd::enable_shared_from_thisTheCuriouslyRecurringTemtePatternAfinalDenotingun-special-nesswithobserver_ptr<T>TheproblemwithUsingstd::atomic<T>forthread-safeaccessesngcomplicatedoperationsatomicallyBigTakingturnswithstd::mutex"Takinglocks"therightwayAlwaysassociateamutexwithitscontrolleddataSpecial-purposemutextypesUpgradingaread-writeDowngradingaread-writelockWaitingforaconditionPromisesaboutfuturesPackaginguptasksforlaterThefutureoffuturesSpeakingofthreads...IdentifyingindividualthreadsandthecurrentThreadexhaustionandstd::asyncBuildingyourownthreadpoolImprovingourthreadpool'sperformanceAnallocatorisahandletoamemoryresourceRefresher-InterfacesversusconceptsDefiningaheapwithmemory_resourceUsingthestandardmemoryresourcesAllocatingfromapoolresourceThe500hatsofthestandardallocatorCarryingmetadatawithfancyStickingacontainertoasinglememoryresourceUsingthestandardallocatortypesSettingthedefaultmemoryMakingacontainerallocator-Propagatingdownwardswithscoped_allocator_adaptorPropagatingdifferentallocatorsThetroublewithI/OinC++BufferingversusUsingthePOSIXAPIUsingthestandardCAPIBufferinginthestandardCFormattingwithprintfandsnprintfTheclassicaliostreamshierarchyStreamingandmanipulatorsStreamingandwrappersSolvingthesticky-manipulatorproblemFormattingwithostringstreamAnoteonlocalesConvertingnumberstostringsConvertingstringstonumbersReadingalineorwordatatimeRegularWhatareregularexpressions?Anoteonbackslash-escaReifyingregularexpressionsintostd::regexobjectsMatchingandsearchingPullingsubmatchesoutofamatchConvertingsubmatchestodatavalues tingovermultipleUsingregularexpressionsforstringrecementAprimerontheECMAScriptregexgr Non-consumingObscureECMAScriptfeaturesandpitfallsRandomRandomnumbersversuspseudo-randomnumbersTheproblemwithrand()Solvingproblemswith<random>DealingwithgeneratorsTrulyrandombitswithstd::random_devicePseudo-randombitswithstd::mt19937FilteringgeneratoroutputswithadaptorsDealingwithdistributionsRollingdicewithuniform_int_distributionGeneratingpopulationswithnormal_distributionMakingweightedchoiceswithdiscrete_distributionShufflingcardswithstd::shuffleAnoteaboutAverylongnoteonerror-reportingUsing<system_error>ErrorcodesanderrorThrowingerrorswithstd::system_errorFilesystemsandpathsRepresentingpathsinC++OperationsonpathsStattingfileswithdirectory_entryWalkingdirectorieswithdirectory_i RecursivedirectorywalkingModifyingthefilesystemReportingdiskusageTheC++languagehasalonghistory,datingbacktothe1980s.Recentlyithasundergonearenaissance,withmajornewfeaturesbeingintroducedin2011and2014.Atpresstime,theC++17standardisjustaroundthecorner.C++11practicallydoubledthesizeofthestandardlibrary,addingsuchheadersas<tuple>,<type_traits>,and<regex>.C++17doublesthelibraryagain,withadditionssuchas<optional>,<any>,and<filesystem>.Aprogrammerwho’sbeenspendingtimewritingcodeinsteadofwatchingthestandardizationprocessmightfairlyfeelthatthestandardlibraryhasgottenawayfromhim--thatthere’ssomanynewthingsinthelibrarythathe'llneverbeabletomasterthewholething,oreventosortthewheatfromthechaff.Afterall,whowantstospendamonthreadingtechnical ationonstd::localeandstd::ratio,justtofindoutthattheyaren'tusefulinyourdailywork?Inthisbook,I'llteachyouthemostimportantfeaturesoftheC++17standardlibrary.Intheinterestofbrevity,Iomitsomeparts,suchastheaforementioned<type_traits>;butwe'llcovertheentiremodernSTL(everystandardcontainerandeverystandardalgorithm),plussuchimportanttopicsassmartpointers,randomnumbers,regularexpressions,andthenew-in-C++17<filesystem>library.I'llteachbyexample.You'lllearntobuildyourownitortype;yourownmemoryallocatorusingstd::pmr::memory_resource;yourownthreadpoolusingI'llteachconceptsbeyondwhatyou'dfindinareferencemanual.You'lllearnthedifferencebetweenmonomorphic,polymorphic,andgenericalgorithms(Chapter1,ClassicalPolymorphismandGenericProgramming);whatitmeansforstd::stringorstd::anytobetermeda"vocabularytype"(Chapter5,VocabularyTypes);andwhatwemightexpectfromfutureC++standardsin2020andbeyond.IassumethatyouarealreadyreasonablyfamiliarwiththecorelanguageofC++11;forexample,thatyoualreadyunderstandhowtowriteclassandfunctiontemtes,thedifferencebetweenlvalueandrvaluereferences,andsoon.WhatthisbookChapter1,ClassicalPolymorphismandGenericProgramming,coversclassicalpolymorphism(virtualmemberfunctions)andgenericprogrammingChapter2,ItorsandRanges,exinstheconceptofitorasageneralizationofpointer,andtheutilityofhalf-openrangesexpressedasapairofitors.Chapter3,TheItor-PairAlgorithms,exploresthevastvarietyofstandardgenericalgorithmsthatoperateonrangesexpressedasitor-pairs.Chapter4,TheContainerZoo,exploresthealmostequallyvastvarietyofstandardcontainerclasstemtes,andwhichcontainersaresuitableforwhichjobs.Chapter5,VocabularyTypes,walksyouthroughalgebraictypessuchstd::optional.andABI-friendlytype-erasedtypessuchasChapter6,SmartPointers,teachesthepurposeanduseofsmartChapter7,Concurrency,coversatomics,mutexes,conditionvariables,threads,futures,andpromises.Chapter8,Allocators,exinsthenewfeaturesofC++17'sChapter9,Iostreams,explorestheevolutionoftheC++I/Omodel,<unistd.h>to<stdio.h>toChapter10,RegularExpressions,teachesregularexpressionsinChapter11,RandomNumbers,walksyouthroughC++'ssupportforpseudo-randomnumbergeneration.Chapter12,Filesystem,coversthenew-in-C++17<filesystem>WhatyouneedforthisAsthisbookisnotareferencemanual,itmightbeusefulforyoutohaveareferencemanual,suchascppreference(e /w/cpp),atyoursidetoclarifyanyconfusingpoints.ItwilldefiniyhelptohaveaC++17compilerhandy.Atpresstime,thereareseveralmoreorless pleteC++17implementations,includingGCC,Clang,and VisualStudio.Youcanrunthemlocallyorviamanyonlinecompilerservices,suchasWandbox(),Godbolt(),andRextester WhothisbookisThisbookisfordeveloperswhowouldliketomastertheC++17STLandmakefulluseofitscomponents.PriorC++knowledgeisassumed.Inthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexnationoftheirmeaning.Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,and handlesareshownasfollows:"Thebuffer()functionacceptsargumentsoftypeint."Ablockofcodeissetastry}catch(conststd::future_error&{assert(ex.code()==}NewtermsandimportantwordsareshowninWarningsorimportantnotesappearlikeTipsandnotesappearlikeReaderFeedbackfromourreadersisalways e.Letusknowwhatyouthinkaboutthisbook--whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.Tosendusgeneralfeedback,simplye-mailfee ,andmentionthebook'stitleinthesubjectofyourmessage.Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideat CustomerNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.DownloadingtheexampleYoucandownloadtheexamplecodefilesforthisbookfromyouraccount .Ifyoupurchasedthisbookelsewhere,youcanvisithttp://pportandregistertohavethefilese-maileddirectlytoYoucandownloadthecodefilesbyfollowingtheseLoginorregistertoourwebsiteusingyoure-mailaddressandHoverthemousepointerontheSUPPORTtabattheClickonCodeDownloads&EnterthenameofthebookintheSearchSelectthebookforwhichyou'relookingtodownloadthecodeChoosefromthedrop- whereyoupurchasedthisbookClickonCodeOncethefileisdownloaded,pleasemakesurethatyouunziporextractthefolderusingthelatestversionof:WinRAR/7-ZipforWindowsZipeg/iZip/UnRarXforMac7-Zip/PeaZipforLinuxThecodebundleforthebookisalsohostedon ublishing/Mastering-the-Cpp17-STL.Wealsohaveothercodebundlesfromourrichcatalogofbooksand savailableat /PacktPublishing/.Checkthemout!Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks--maybeamistakeinthetextorthecode--wewouldbegratefulifyoucouldreportthistous.Byngso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp: /submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.Toviewthepreviouslysubmittederrata,gotohttps: /books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.PiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediaysothatwecanpursuearemedy.Pleasecontactusat withalinktotheedpiratedmaterial.Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.Ifyouhaveaproblemwithanyaspectofthisbook,youcancontactus ,andwewilldoourbesttoaddresstheClassicalPolymorphismandGenericProgrammingTheC++standardlibraryhastwodistinct,yetequallyimportant,missions.Oneofthesemissionsistoproviderock-solidimplementationsofcertainconcretedatatypesorfunctionsthathavetendedtobeusefulinmanydifferentprograms,yetaren'tbuiltintothecorelanguagesyntax.Thisiswhythestandardlibrarycontainsstd::string,std::regex,std::filesystem::exists,andsoon.Theothermissionofthestandardlibraryistoproviderock-solidimplementationsofwidelyused algorithmssuchassorting,searching,reversing,collating,andsoon.Inthisfirstchapter,wewillnaildownexactlywhatwemeanwhenwesaythataparticularpieceofcodeis ,"anddescribethetwoapproachesthatthestandardlibraryusesto ion:classicalpolymorphismandgenericprogramming.Wewilllookatthefollowingtopicsinthis Classicalpolymorphismbymeansofbaseclasses,virtualmemberfunctions,andinheritanceGenericprogrammingbymeansofconcepts,requirements,andmodelsThepracticaladvantagesanddisadvantagesofeachapproachConcretemonomorphicWhatdistinguishesan algorithmfromaconcretefunction?Thisisbestshownbyexample.Let'swriteafunctiontomultiplyeachoftheelementsinanarrayby2:class{intdata[10]={};intsize()const{return10;}int&at(inti){returndata[i];}{for(inti=0;i<arr.size();{arr.at(i)*=}}Ourfunctiondouble_each_elementworksonlywithobjectsoftypearray_of_int;passinginanobjectofadifferenttypewon'twork(norevencompile).Werefertofunctionslikethisversionofdouble_each_elementasconcreteormonomorphicfunctions.Wecallthemconcretebecausetheyare forourpurposes.JustimaginehowpainfulitwouldbeiftheC++standardlibraryprovidedaconcretesortroutinethatworkedonlyononespecificdatatype!ClassicallypolymorphicWecanincreasethe ionlevelofouralgorithmsviathetechniquesofclassicalobject-oriented(OO)programming,asseeninlanguagessuchasJavaandC#.TheOOapproachistodecideexactlywhichbehaviorswe'dliketobecustomizable,andthendeclarethemasthepublicvirtualmemberfunctionsofan baseclass:class{virtualintsize()const=0;virtualint&at(int)=0;classarray_of_ints:public{intdata[10]={};intsize()constoverride{return10;}int&at(inti)override{returndata[i];}classlist_of_ints:public{structnode{intdata;node*next;node*head_=nullptr;intsize_=0;intsize()constoverride{returnsize_;}int&at(inti)override{if(i>=size_)throwstd::out_of_range("at");node*p=head_;for(intj=0;j<i;{p=p-}returnp-}{for(inti=0;i<arr.size();{arr.at(i)*=}}void{array_of_intsarr;list_of_intslst;}Insidetest,thetwodifferentcallstodouble_each_elementcompilebecauseinclassicalOOterminology,anarray_of_intsIS-Acontainer_of_ints(thatis,itinheritsfromcontainer_of_intsandimplementstherelevantvirtualmemberfunctions),andalist_of_intsIS-Acontainer_of_intsaswell.However,thebehaviorofanygivencontainer_of_intsobjectisparameterizedbyitsdynamictype;thatis,bythetableoffunctionpointersassociatedwiththisparticularSincewecannowparameterizethebehaviorofthedouble_each_elementfunctionwithouteditingitssourcecodedirectly--simplybypassinginobjectsofdifferentdynamictypes--wesaythatthefunctionhas epolymorphic.Butstill,thispolymorphicfunctioncanhandleonlythosetypeswhicharedescendantsofthebaseclasscontainer_of_ints.Forexample,youcouldn'tpassastd::vector<int>tothisfunction;you'dgetacompileerrorifyoutried.Classicalpolymorphismisuseful,butitdoesnotgetusallthewaytofullAnadvantageofclassical(object-oriented)polymorphismisthatthesourcecodestillbearsaone-to-onecorrespondencewiththemachinecodethatisgeneratedbythecompiler.Atthemachine-codelevel,westillhavejustonedouble_each_elementfunction,withonesignatureandonewell-definedentrypoint.Forexample,wecantaketheaddressofdouble_each_elementasafunctionGenericprogrammingwithInmodernC++,thetypicalwaytowriteafullygenericalgorithmistoimplementthealgorithmasatemte.We'restillgoingtoimplementthefunctiontemteintermsofthepublicmemberfunctions.size()and.at(),butwe'renolongergoingtorequirethattheargumentarrbeofanyparticulartype.Becauseournewfunctionwillbeatemte,we'llbelingthecompiler"Idon'tcarewhattypearris.Whatevertypeitis,justgenerateabrand-newfunction(thatis,atemteinstantiation)withthattypeasitsparametertype." te<class{for(inti=0;i<arr.size();{arr.at(i)*=}}void{array_of_intsarr;list_of_intslst;std::vector<int>vec={1,2,3};}Inmostcases,ithelpsusdesignbetterprogramsifwecanputdowninwordsexactlywhatoperationsmustbesupportedbyourtemtetypeparameterContainerModel.Thatsetofoperations,takentogether,constituteswhat'sknowninC++asaconcept;inthisexamplewemightsaythattheconceptContainerconsistsof"havingamemberfunctionnamedsizethatreturnsthesizeofthecontainerasanint(orsomethingcomparabletoint);andhavingamemberfunctionnamedatthattakesanintindex(orsomethingimplicitlyconvertiblefromint)andproducesanon-constreferencetotheindex'thelementofthecontainer."Wheneversomeclassarray_of_intscorrectlystheoperationsrequiredbytheconceptContainer,suchthatarray_of_intsisusablewithdouble_each_element,wesaythattheconcreteclassarray_of_intsisamodeloftheContainerconcept.ThisiswhyIgavethenameContainerModeltothetemtetypeparameterintheprecedingexample.ItwouldbemoretraditionaltousethenameContainerforthetemtetypeparameteritself,andIwilldothatfromnowon;Ijustdidn'twanttostartusoffonthewrongfootbymuddyingthedistinctionbetweentheContainerconceptandtheparticulartemtetypeparametertothisparticularfunctiontemtethathappenstodesireasitsargumentaconcreteclassthatmodelstheContainerconcept.Whenweimplementan algorithmusingtemtes,sothatthebehaviorofthealgorithmcanbeparameterizedatcompiletimebyanytypesmodelingtheappropriateconcepts,wesaywearenggenericNoticethatourdescriptionoftheContainerconceptdidn'tmentionthatweexpectthetypeofthecontainedelementstobeint;andnotco ally,wefindthatwecannowuseourgenericdouble_each_elementfunctionevenwithcontainersthatdon'tholdint!std::vector<double>vecd={1.0,2.0,3.0};ThisextralevelofgenericityisoneofthebigbenefitsofusingC++temtesforgenericprogramming,asopposedtoclassicalpolymorphism.Classicalpolymorphismhidesthevaryingbehaviorofdifferentclassesbehindastableinterfacesignature(forexample,.at(i)alwaysreturnsint&),butonceyoustartmessingwithvaryingsignatures,classicalpolymorphismisnolongeragoodtoolforthejob.Anotheradvantageofgenericprogrammingisthatitoffersblazingspeedthroughincreasedopportunitiesforinlining.Theclassicallypolymorphicexamplemustrepeatedlyquerythecontainer_of_intobject'svirtualtabletofindtheaddressofitsparticularvirtualatmethod,andgenerallycannotseethroughthevirtualdispatchatcompiletime.Thetemtefunctiondouble_each_element<array_of_int>cancompileinadirectcalltoarray_of_int::atoreveninlinethecallcompley.Becausegenericprogrammingwithtemtescansoeasilydealwithcomplicatedrequirementsandissoflexibleindealingwithtypes--evenprimitivetypeslikeint,whereclassicalpolymorphismfails--thestandardlibraryusestemtesforallitsalgorithmsandthecontainersonwhichtheyoperate.Forthisreason,thealgorithms-and-containerspartofthestandardlibraryisoftenreferredtoastheStandardTemteLibraryorSTL.That'sright--technically,theSTLisonlyasmallpartoftheC++standardlibrary!However,inthisbook,asinreallife,wemayoccasionallyslipupandusethetermSTLwhenwemeanstandardlibrary,orviceversa.Let'slookatacouplemorehand-writtengenericalgorithms,beforewediveintothestandardgenericalgorithmsprovidedbytheSTL.Hereisafunctiontemtecount,returningthetotalnumberofelementsinacontainer: te<classintcount(constContainer&{intsum=for(auto&&elt:{sum+=}return}Andhereiscount_if,whichreturnsthenumberofelementssatisfyingauser-dpredicatefunction: te<classContainer,classintcount_if(constContainer&container,Predicate{intsum=for(auto&&elt:{if(pred(elt)){sum+=1;}}return}Thesefunctionswouldbeusedlikestd::vector<int>v={3,1,4,1,5,9,2,assert(count(v)==8);intnumber_above=count_if(v,[](inte){returne>5;});intnumber_below=count_if(v,[](inte){returne<5;assert(number_above==assert(number_below==Thereissomuchpowerpackedintothatlittleexpressionpred(elt)!Iencourageyoutotryre-implementingthecount_iffunctionintermsofclassicalpolymorphism,justtogetasenseofwherethewholethingbreaksdown.TherearealotofvaryingsignatureshiddenunderthesyntacticsugarofmodernC++.Forexample,therangedfor-loopsyntaxinourcount_iffunctionisconverted(orlowered")bythecompilerintoafor-loopintermsofcontainer.begin()andcontainer.end(),eachofwhichneedstoreturnanitorwhosetypeisdependentonthetypeofcontaineritself.Foranotherexample,inthegeneric-programmingversion,weneverspecify--weneverneedtospecify--whetherpredtakesitsparametereltbyvalueorbyreference.ngthatwithavirtualboolSpeakingofitors:youmayhavenoticedtha

温馨提示

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

评论

0/150

提交评论