Tải bản đầy đủ (.pdf) (1,110 trang)

Addison wesley c++ standard library a tutorial and reference

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.58 MB, 1,110 trang )


C++StandardLibrary:ATutorialand
Reference,The
ByNicolaiM.Josuttis


Publisher :AddisonWesley
PubDate :August06,1999
ISBN
:0-201-37926-0
Pages
:832



C++StandardLibraryprovidesasetofcommon
classesandinterfacesthatgreatlyextendthecore
C++language.Thelibrary,however,isnotselfexplanatory.Tomakefulluseofitscomponents-and
tobenefitfromtheirpower-youneedaresourcethat
doesfarmorethanlisttheclassesandtheir
functions.
TheC++StandardLibrarynotonlyprovides
comprehensivedocumentationofeachlibrary
component,italsooffersclearlywrittenexplanations
ofcomplexconcepts,describesthepractical
programmingdetailsneededforeffectiveuse,and
givesexampleafterexampleofworkingcode.


Thisthoroughlyup-to-datebookreflectsthenewest
elementsoftheC++standardlibraryincorporated



intothefullANSI/ISOC++languagestandard.In
Tableof

particular,thetextfocusesontheStandardTemplate
Contents
Library(STL),examiningcontainers,iterators,
functionobjects,andSTLalgorithms.Youwillalso
finddetailedcoverageofspecialcontainers,strings,
numericalclasses,internationalization,andthe
IOStreamlibrary.Eachcomponentispresentedin
depth,withanintroductiontoitspurposeanddesign,
examples,adetaileddescription,trapsandpitfalls,
andtheexactsignatureanddefinitionofitsclasses
andtheirfunctions.Aninsightfulintroductionto
fundamentalconceptsandanoverviewofthelibrary


willhelpbringnewcomersquicklyuptospeed.
Comprehensive,detailed,readable,andpractical,
TheC++StandardLibraryistheC++resourceyou
willturntoagainandagain.

EEn
777

Copyright
Preface
Acknowledgments
Chapter1.AboutthisBook

1.1WhythisBook
1.2WhatYouShouldKnowBeforeReadingthisBook
1.3StyleandStructureoftheBook
1.4HowtoReadthisBook
1.5StateoftheArt
1.6ExampleCodeandAdditionalInformation
1.7Feedback
Chapter2.IntroductiontoC++andtheStandardLibrary
2.1History
2.2NewLanguageFeatures
2.3ComplexityandtheBig-ONotation
Chapter3.GeneralConcepts
3.1Namespace
3.2HeaderFiles
3.3ErrorandExceptionHandling
3.4Allocators
Chapter4.Utilities
4.1Pairs
4.1.1ConvenienceFunction
4.1.2ExamplesofPairUsage


4.2Class
4.3NumericLimits
4.4AuxiliaryFunctions
4.5SupplementaryComparisonOperators
4.6HeaderFiles
Chapter5.TheStandardTemplateLibrary
5.1STLComponents
5.2Containers

5.3Iterators
5.4Algorithms
5.5IteratorAdapters
5.6ManipulatingAlgorithms
5.7User-DefinedGenericFunctions
5.8FunctionsasAlgorithmArguments
5.9FunctionObjects
5.10ContainerElements
5.11ErrorsandExceptionsInsidetheSTL
5.12ExtendingtheSTL
Chapter6.STLContainers
6.1CommonContainerAbilitiesandOperations
6.2Vectors
6.3Deques
6.4Lists
6.5SetsandMultisets
6.6MapsandMultimaps
6.7OtherSTLContainers
6.8ImplementingReferenceSemantics
6.9WhentoUsewhichContainer
6.10ContainerTypesandMembersinDetail
Chapter7.STLIterators
7.1HeaderFilesforIterators
7.2IteratorCategories
7.3AuxiliaryIteratorFunctions
7.4IteratorAdapters
7.5IteratorTraits


Chapter8.STLFunctionObjects

8.1TheConceptofFunctionObjects
8.2PredefinedFunctionObjects
8.3SupplementaryComposingFunctionObjects
Chapter9.STLAlgorithms
9.1AlgorithmHeaderFiles
9.2AlgorithmOverview
9.3AuxiliaryFunctions
9.4The
9.5NonmodifyingAlgorithms
9.6ModifyingAlgorithms
9.7RemovingAlgorithms
9.8MutatingAlgorithms
9.9SortingAlgorithms
9.10SortedRangeAlgorithms
9.11NumericAlgorithms
Chapter10.SpecialContainers
10.1Stacks
10.2Queues
10.3PriorityQueues
10.4Bitsets
Chapter11.Strings
11.1Motivation
11.2DescriptionoftheStringClasses
11.3StringClassinDetail
Chapter12.Numerics
12.1ComplexNumbers
12.2Valarrays
12.3GlobalNumericFunctions
Chapter13.Input/OutputUsingStreamClasses
13.1CommonBackgroundofI/OStreams

13.2FundamentalStreamClassesandObjects
13.3StandardStreamOperators<<and>>
13.4StateofStreams


13.5StandardInput/OutputFunctions
13.6Manipulators
13.7Formatting
13.8Internationalization
13.9FileAccess
13.10ConnectingInputandOutputStreams
13.11StreamClassesforStrings
13.12Input/OutputOperatorsforUser-DefinedTypes
13.13TheStreamBufferClasses
13.14PerformanceIssues
Chapter14.Internationalization
14.1DifferentCharacterEncodings
14.2TheConceptofLocales
14.3LocalesinDetail
14.4FacetsinDetail
Chapter15.Allocators
15.1UsingAllocatorsasanApplicationProgrammer
15.2UsingAllocatorsasaLibraryProgrammer
15.3TheDefaultAllocator
15.4AUser-DefinedAllocator
15.5AllocatorsinDetail
15.6UtilitiesforUninitializedMemoryinDetail
InternetResources
Bibliography



Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Wherethose
designationsappearinthisbookandAddisonWesleyLongmanInc.,was
awareofatrademarkclaim,thedesignationshavebeenprintedininitial
capsorallcaps.
Theauthorsandpublisherhavetakencareinthepreparationofthis
book,butmakenoexpressedorimpliedwarrantyofanykindand
assumenoresponsibilityforerrorsoromissions.Noliabilityisassumed
forincidentalorconsequentialdamagesinconnectionwithorarisingout
oftheuseoftheinformationorprogramscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityfor
specialsales.Formoreinformation,pleasecontact:
AWLDirectSales
AddisonWesleyLongman,Inc
OneJacobWay
Reading,Massachusetts01867
(781)944-3700
VisitAWontheWeb:www.awl.com/cseng/
LibraryofCongressCataloging-in-PublicationData
Josuttis,NicolaiM.
TheC++standardlibrary:atutorialandreference/NicolaiM.
Josuttis.
p.cm.


Includesbibliographicalreferencesandindex.
1.C++(Computerprogramlanguage)I.Title.
QA76.73.C153J691999

005.13'3--dc2199-24977
CIP
Copyright©1999byAddisonWesleyLongman,Inc.
Allrightsreserved.Nopartofthispublicationmaybereproduced,stored
inaretrievalsystem,ortransmitted,inanyform,orbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,withoutthe
priorconsentofthepublisher.PrintedintheUnitedStatesofAmerica.
PublishedsimultaneouslyinCanada.
123456789-CRW-0302010099
Firstprinting,July1999


Preface
Inthebeginning,IonlyplannedtowriteasmallGermanbook(400pages
orso)abouttheC++standardlibrary.Thatwasin1993.Now,in1999
youseetheresult—anEnglishbookwithmorethan800pagesoffacts,
figures,andexamples.MygoalistodescribetheC++standardlibraryso
thatall(oralmostall)yourprogrammingquestionsareansweredbefore
youthinkofthequestion.Note,however,thatthisisnotacomplete
descriptionofallaspectsoftheC++standardlibrary.Instead,Ipresent
themostimportanttopicsnecessaryforlearningandprogrammingin
C++byusingitsstandardlibrary.
Eachtopicisdescribedbasedonthegeneralconcepts;thisdiscussion
thenleadstothespecificdetailsneededtosupportevery-day
programmingtasks.Specificcodeexamplesareprovidedtohelpyou
understandtheconceptsandthedetails.
That'sit—inanutshell.Ihopeyougetasmuchpleasurefromreading
thisbookasIdidfromwritingit.Enjoy!

Acknowledgments

Thisbookpresentsideas,concepts,solutions,andexamplesfrommany
sources.Inawayitdoesnotseemfairthatmynameistheonlynameon
thecover.Thus,I'dliketothankallthepeopleandcompanieswho
helpedandsupportedmeduringthepastfewyears.
First,I'dliketothankDietmarKühl.DietmarisanexpertonC++,
especiallyoninput/outputstreamsandinternationalization(he
implementedanI/Ostreamlibraryjustforfun).Henotonlytranslated
majorpartsofthisbookfromGermantoEnglish,healsowrotesections
ofthisbookusinghisexpertise.Inaddition,heprovidedmewith
invaluablefeedbackovertheyears.
Second,I'dliketothankallthereviewersandeveryoneelsewhogave
metheiropinion.Thesepeopleendowthebookwithaqualityitwould


neverhavehadwithouttheirinput.(Becausethelistisextensive,please
fogivemeforanyoversight.)ThereviewersfortheEnglishversionofthis
bookincludedChuckAllison,GregComeau,JamesA.Crotinger,Gabriel
DosReis,AlanEzust,NathanMeyers,WernerMossner,Todd
Veldhuizen,ChichiangWan,JudyWard,andThomasWikehult.The
GermanreviewersincludedRalfBoecker,DirkHerrmann,DietmarKühl,
EddaLörke,HerbertScheubner,DominikStrasser,andMartinWeitzel.
AdditionalinputwasprovidedbyMattAustern,ValentinBonnard,Greg
Colvin,BemanDawes,BillGibbons,LoisGoldthwaite,AndrewKoenig,
SteveRumbsby,BjarneStroustrup,andDavidVandevoorde.
SpecialthankstoDaveAbrahams,JanetCocker,CatherineOhala,and
MaureenWillardwhoreviewedandeditedthewholebookverycarefully.
Theirfeedbackwasanincrediblecontributiontothequalityofthisbook.
Aspecialthanksgoestomy"personallivingdictionary"—HerbSutter—
theauthorofthefamous"GuruoftheWeek"(aregularseriesofC++
programmingproblemsthatispublishedonthe

comp.std.C++.moderatedInternetnewsgroup).
I'dalsoliketothankallthepeopleandcompanieswhogavemethe
opportunitytotestmyexamplesondifferentplatformswithdifferent
compilers.ManythankstoSteveAdamczyk,MikeAnderson,andJohn
SpicerfromEDGfortheirgreatcompilerandtheirsupport.Itwasabig
helpduringthestandardizationprocessandthewritingofthisbook.
ManythankstoP.J.PlaugerandDinkumware,Ltd,fortheirearly
standard-conformingimplementationoftheC++standardlibrary.Many
thankstoAndreasHommelandMetrowerksforanevaluativeversionof
theirCodeWarriorProgrammingEnvironment.Manythankstoallthe
developersofthefreeGNUandegcscompilers.Manythanksto
MicrosoftforanevaluativeversionofVisualC++.ManythankstoRoland
HartingerfromSiemensNixdorfInformationsSystemsAGforatest
versionoftheirC++compiler.ManythankstoTopjectsGmbHforan
evaluativeversionoftheObjectSpacelibraryimplementation.
ManythankstoeveryonefromAddisonWesleyLongmanwhoworked
withme.AmongothersthisincludesJanetCocker,MikeHendrickson,
DebbieLafferty,MarinaLang,ChandaLeary,CatherineOhala,Marty
Rabinowitz,SusanneSpitzer,andMaureenWillard.Itwasfun.


Inaddition,I'dliketothankthepeopleatBREDEXGmbHandallthe
peopleintheC++community,particularlythoseinvolvedwiththe
standardizationprocess,fortheirsupportandpatience(sometimesIask
reallysillyquestions).
Lastbutnotleast,manythanksandkissesformyfamily:Ulli,Lucas,
Anica,andFrederic.Idefinitelydidnothaveenoughtimeforthemdueto
thewritingofthisbook.
Havefunandbehuman!



CONTENTS


Chapter1.AboutthisBook
1.1WhythisBook
1.2WhatYouShouldKnowBeforeReadingthisBook
1.3StyleandStructureoftheBook
1.4HowtoReadthisBook
1.5StateoftheArt
1.6ExampleCodeandAdditionalInformation
1.7Feedback

1.1WhythisBook
Soonafteritsintroduction,C++becameadefactostandardinobjectorientedprogramming.Thisledtothegoalofstandardization.Onlyby
havingastandard,couldprogramsbewrittenthatwouldrunondifferent
platforms—fromPCstomainframes.Furthermore,astandardlibrary
wouldenableprogrammerstousegeneralcomponentsandahigher
levelofabstractionwithoutlosingportability,ratherthanhavingto
developallcodefromscratch.
Thestandardizationprocesswasstartedin1989byaninternational
ANSI/ISOcommittee.ItdevelopedthestandardbasedonBjarne
Stroustrup'sbooksTheC++ProgrammingLanguageandTheAnnotated
C++ReferenceManual.Afterthestandardwascompletedin1997,
severalformalmotionsbydifferentcountriesmadeitaninternationalISO
andANSIstandardin1998.Thestandardizationprocessincludedthe
developmentofaC++standardlibrary.Thelibraryextendsthecore
languagetoprovidesomegeneralcomponents.ByusingC++'sabilityto
programnewabstractandgenerictypes,thelibraryprovidesasetof
commonclassesandinterfaces.Thisgivesprogrammersahigherlevel

ofabstraction.Thelibraryprovidestheabilitytouse
Stringtypes
Differentdatastructures(suchasdynamicarrays,linkedlists,and
binarytrees)


Differentalgorithms(suchasdifferentsortingalgorithms)
Numericclasses
Input/output(I/O)classes
Classesforinternationalizationsupport
Allofthesearesupportedbyafairlysimpleprogramminginterface.
Thesecomponentsareveryimportantformanyprograms.Thesedays,
dataprocessingoftenmeansinputting,computing,processing,and
outputtinglargeamountsofdata,whichareoftenstrings.
Thelibraryisnotself-explanatory.Tousethesecomponentsandto
benefitfromtheirpower,youneedagoodintroductionthatexplainsthe
conceptsandtheimportantdetailsinsteadofsimplylistingtheclasses
andtheirfunctions.Thisbookiswrittenexactlyforthatpurpose.First,it
introducesthelibraryandallofitscomponentsfromaconceptionalpoint
ofview.Next,itdescribesthedetailsneededforpracticalprogramming.
Examplesareincludedtodemonstratetheexactusageofthe
components.Thus,thisbookisadetailedintroductiontotheC++library
forboththebeginnerandthepracticalprogrammer.Armedwiththedata
providedherein,youshouldbeabletotakefulladvantageoftheC++
standardlibrary.
Caveat:Idon'tpromisethateverythingdescribediseasyandselfexplanatory.Thelibraryprovidesalotofflexibility,butflexibilityfor
nontrivialpurposeshasaprice.Bewarethatthelibraryhastrapsand
pitfalls,whichIpointoutwhenweencounterthemandsuggestwaysof
avoidingthem.


1.2WhatYouShouldKnowBeforeReadingthis
Book
TogetthemostfromthisbookyoushouldalreadyknowC++.(Thebook
describesthestandardcomponentsofC++,butnotthelanguageitself.)
Youshouldbefamiliarwiththeconceptsofclasses,inheritance,
templates,andexceptionhandling.However,youdon'thavetoknowall


oftheminordetailsaboutthelanguage.Theimportantdetailsare
describedinthebook(theminordetailsaboutthelanguagearemore
importantforpeoplewhowanttoimplementthelibraryratherthanuseit).
Notethatthelanguagehaschangedduringthestandardizationprocess,
soyourknowledgemightnotbeuptodate.Section2.2,providesabrief
overviewandintroductionofthelatestlanguagefeaturesthatare
importantforusingthelibrary.Youshouldreadthissectionifyouarenot
surewhetheryouknowallthenewfeaturesofC++(suchasthekeyword
typenameandtheconceptofnamespaces).

1.3StyleandStructureoftheBook
TheC++standardlibraryprovidesdifferentcomponentsthatare
somewhatbutnottotallyindependentofeachother,sothereisnoeasy
waytodescribeeachpartwithoutmentioningothers.Iconsidered
severaldifferentapproachesforpresentingthecontentsofthisbook.
OnewasontheorderoftheC++standard.However,thisisnotthebest
waytoexplainthecomponentsoftheC++standardlibraryfromscratch.
Anotherwastostartwithanoverviewofallcomponentsfollowedby
chaptersthatprovidedmoredetails.Alternatively,Icouldhavesortedthe
components,tryingtofindanorderthathadaminimumofcrossreferencestoothersections.Mysolutionwastouseamixtureofallthree
approaches.Istartwithabriefintroductionofthegeneralconceptsand
theutilitiesthatareusedbythelibrary.Then,Idescribeallthe

components,eachinoneormorechapters.Thefirstcomponentisthe
standardtemplatelibrary(STL).ThereisnodoubtthattheSTListhe
mostpowerful,mostcomplex,andmostexcitingpartofthelibrary.Its
designinfluencesothercomponentsheavily.ThenIdescribethemore
self-explanatorycomponents,suchasspecialcontainers,strings,and
numericclasses.Thenextcomponentdiscussedisoneyouprobably
knowandusealready:theIOStreamlibrary.Itisfollowedbyadiscussion
ofinternationalization,whichhadsomeinfluenceontheIOStreamlibrary.
Eachcomponentdescriptionbeginswiththecomponent'spurpose,
design,andsomeexamples.Next,adetaileddescriptionfollowsthat
beginswithdifferentwaystousethecomponent,aswellasanytraps
andpitfallsassociatedwithit.Thedescriptionusuallyendswitha
referencesection,inwhichyoucanfindtheexactsignatureanddefinition


ofacomponent'sclassesanditsfunctions.
Thefollowingisadescriptionofthebook'scontents.Thefirstfour
chaptersintroducethisbookandtheC++standardlibraryingeneral:
Chapter1:AboutthisBook
Thischapter(whichyouarereadingrightnow)introducesthebook's
subjectanddescribesitscontents.
Chapter2:IntroductiontoC++andtheStandardLibrary
ThischapterprovidesabriefoverviewofthehistoryoftheC++
standardlibraryandthecontextofitsstandardization.Italso
containssomegeneralhintsregardingthetechnicalbackgroundfor
thisbookandthelibrary,suchasnewlanguagefeaturesandthe
conceptofcomplexity.
Chapter3:GeneralConcepts
Thischapterdescribesthefundamentalconceptsofthelibrarythat
youneedtounderstandtoworkwithallthecomponents.In

particular,itintroducesthenamespacestd,theformatofheader
files,andthegeneralsupportoferrorandexceptionhandling.
Chapter4:Utilities
Thischapterdescribesseveralsmallutilitiesprovidedfortheuserof
thelibraryandforthelibraryitself.Inparticular,itdescribesauxiliary
functionssuchasmax(),min(),andswap(),typespair
andauto_ptr,aswellasnumeric_limits,whichprovide
moreinformationaboutimplementation-specificdetailsofnumeric
datatypes.
Chapters5through9describeallaspectsoftheSTL:
Chapter5:TheStandardTemplateLibrary
Thischapterpresentsadetailedintroductiontotheconceptofthe


STL,whichprovidescontainerclassesandalgorithmsthatareused
toprocesscollectionsofdata.Itexplainsstep-by-steptheconcept,
theproblems,andthespecialprogrammingtechniquesoftheSTL,
aswellastherolesofitsparts.
Chapter6:STLContainers
Thischapterexplainstheconceptsanddescribestheabilitiesofthe
STL'scontainerclasses.Firstitdescribesthedifferencesbetween
vectors,deques,lists,sets,andmaps,thentheircommonabilities,
andallwithtypicalexamples.Lastlyitlistsanddescribesall
containerfunctionsinformofahandyreference.
Chapter7:STLIterators
ThischapterdealsindetailwiththeSTL'siteratorclasses.In
particular,itexplainsthedifferentiteratorcategories,theauxiliary
functionsforiterators,andtheiteratoradapters,suchasstream
iterators,reverseiterators,andinsertiterators.
Chapter8:STLFunctionObjects

ThischapterdetailstheSTL'sfunctionobjectclasses.
Chapter9:STLAlgorithms
ThischapterlistsanddescribestheSTL'salgorithms.Afterabrief
introductionandcomparisonofthealgorithms,eachalgorithmis
describedindetailfollowedbyoneormoreexampleprograms.
Chapters10through12describe"simple"individualstandardclasses:
Chapter10:SpecialContainers
Thischapterdescribesthedifferentspecialcontainerclassesofthe
C++standardlibrary.Itcoversthecontaineradaptersforqueuesand
stacks,aswellastheclassbitset,whichmanagesabitfieldwith
anarbitrarynumberofbitsorflags.
Chapter11:Strings


ThischapterdescribesthestringtypesoftheC++standardlibrary
(yes,therearemorethanone).Thestandardprovidesstringsas
kindof"self-explanatory"fundamentaldatatypeswiththeabilityto
usedifferenttypesofcharacters.
Chapter12:Numerics
ThischapterdescribesthenumericcomponentsoftheC++standard
library.Inparticular,itcoverstypesforcomplexnumbersandclasses
fortheprocessingofarraysofnumericvalues(thelattermaybe
usedformatrices,vectors,andequations).
Chapters13and14dealwithI/Oandinternationalization(twoclosely
relatedsubjects):
Chapter13:Input/OutputUsingStreamClasses
ThischaptercoverstheI/OcomponentofC++.Thiscomponentis
thestandardizedformofthecommonlyknownIOStreamlibrary.The
chapteralsodescribesdetailsthatmaybeimportanttoprogrammers
butaretypicallynotsowellknown.Forexample,itdescribesthe

correctwaytodefineandintegratespecialI/Ochannels,whichare
oftenimplementedincorrectlyinpractice.
Chapter14:Internationalization
Thischaptercoverstheconceptsandclassesforthe
internationalizationofprograms.Inparticular,itdescribesthe
handlingofdifferentcharactersets,aswellastheuseofdifferent
formatsforsuchvaluesasfloating-pointnumbersanddates.
Therestofthebookcontains:
Chapter15:Allocators
Thischapterdescribestheconceptofdifferentmemorymodelsin
theC++standardlibrary.
Anappendixwith


InternetResources
Bibliography
Index

1.4HowtoReadthisBook
Thisbookisamixofintroductoryuser'sguideandstructuredreference
manualregardingtheC++standardlibrary.Theindividualcomponentsof
theC++standardlibraryareindependentofeachother,tosomeextent,
soafterreadingChapters2through4youcouldreadthechaptersthat
discusstheindividualcomponentsinanyorder.Bearinmind,that
Chapter5throughChapter9alldescribethesamecomponent.To
understandtheotherSTLchapters,youshouldstartwiththeintroduction
totheSTLinChapter5.
IfyouareaC++programmerwhowantstoknow,ingeneral,the
conceptsandallpartsofthelibrary,youcouldsimplyreadthebookfrom
thebeginningtotheend.However,youshouldskipthereference

sections.ToprogramwithcertaincomponentsoftheC++standard
library,thebestwaytofindsomethingistousetheindex.Ihavetriedto
maketheindexverycomprehensivetosaveyoutimewhenyouare
lookingforsomething.
Inmyexperience,thebestwaytolearnsomethingnewistolookat
examples.Therefore,you'llfindalotofexamplesthroughoutthebook.
Theymaybeafewlinesofcodeorcompleteprograms.Inthelatter
case,you'llfindthenameofthefilecontainingtheprogramasthefirst
commentline.YoucanfindthefilesontheInternetatmyWebsiteat
/>
1.5StateoftheArt
WhileIwaswritingthisbook,theC++standardwascompleted.Please
bearinmindthatsomecompilersmightnotyetconfirmtoit.Thiswill
mostlikelychangeinthenearfuture.Asaconsequence,youmight


discoverthatnotallthingscoveredinthisbookworkasdescribedon
yoursystem,andyoumayhavetochangeexampleprogramstofityour
specificenvironment.Icancompilealmostallexampleprogramswith
version2.8orhigheroftheEGCScompiler,whichisfreeforalmostall
platformsandavailableontheInternet(seeand
onseveralsoftwareCDs.

1.6ExampleCodeandAdditionalInformation
Youcanaccessallexampleprogramsandacquiremoreinformations
aboutthisbookandtheC++standardlibraryfrommyWebsiteat
Also,youcanfindalotofadditional
informationaboutthistopicontheInternet.SeeInternetResourcesfor
details.


1.7Feedback
Iwelcomeyourfeedback(goodandbad)onthisbook.Itriedtoprepareit
carefully;however,I'mhuman,andatsometimeIhavetostopwriting
andtweaking.So,youmayfindsomeerrors,inconsistencies,orsubjects
thatcouldbedescribedbetter.Yourfeedbackwillgivemethechanceto
improvelatereditions.ThebestwaytoreachmeisbyEmail:


Youcanalsoreachmebyphone,fax,or"snail"mail:
NicolaiM.Josuttis
Berggarten9
D-38108Braunschweig
Germany
Phone:+495309574


Fax:+4953095774
Manythanks.
CONTENTS


CONTENTS


Chapter2.IntroductiontoC++andthe
StandardLibrary
2.1History
2.2NewLanguageFeatures
2.3ComplexityandtheBig-ONotation


2.1History
ThestandardizationofC++wasstartedin1989andfinishedattheendof
1997,althoughsomeformalmotionsdelayedthefinalpublicationuntil
September1998.Theresultwasareferencemanualwithapproximately
750pages,publishedbytheInternationalStandardsOrganization(ISO).
Thestandardhasthetitle"InformationTechnology—Programming
Languages—C++."ItsdocumentnumberisISO/IEC14882-1998,andit
isdistributedbythenationalbodiesoftheISO,suchastheANSIinthe
UnitedStates.[1]
ThestandardwasanimportantmilestoneforC++.Becauseitdefinesthe
exactcontentsandbehaviorofC++,itmakesiteasiertoteachC++,to
useC++inapplications,andtoportC++programstodifferentplatforms.
ItalsogivesusersgreaterfreedomofchoiceregardingdifferentC++
implementations.Itsstabilityandportabilityhelplibraryprovidersandtool
providersaswellasimplementers.Thus,thestandardhelpsC++
applicationdevelopersbuildbetterapplicationsfaster,andmaintainthem
withlesscostandeffort.
Partofthestandardisastandardlibrary.Thislibraryprovidescore
componentsforI/O,strings,containers(datastructures),algorithms
(suchassort,search,andmerge),supportfornumericcomputation,and
(ascouldbeexpectedfromaninternationalstandard)supportfor
internationalization(suchasdifferentcharactersets).
Youmaywonderwhythestandardizationprocesstookalmost10years,
andifyouknowsomedetailsaboutthestandardyoumightwonderwhy


afterallthistimeitisstillnotperfect.Tenyears,infact,wasnotenough
time!Although,accordingtothehistoryandthecontextofthe
standardizationprocess,alotwasaccomplished.Theresultisusablein
practice,butitisnotperfect(nothingeveris).

Thestandardisnottheresultofacompanywithabigbudgetandalotof
time.Standardsorganizationspaynothingoralmostnothingtothe
peoplewhoworkondevelopingstandards.So,ifaparticipantdoesn't
workforacompanythathasaspecialinterestinthestandard,thework
isdoneforfun.Thankgoodnesstherewerealotofdedicatedpeople
whohadthetimeandthemoneytodojustthat.
TheC++standardwasnotdevelopedfromscratch.Itwasbasedonthe
languageasdescribedbyBjarneStroustrup,thecreatorofC++.The
standardlibrary,however,wasnotbasedonabookoronanexisting
library.Instead,different,existingclasseswereintegrated.[2]Thus,the
resultisnotveryhomogeneous.Youwillfinddifferentdesignprinciples
fordifferentcomponents.Agoodexampleisthedifferencebetweenthe
stringclassandtheSTL,whichisaframeworkfordatastructuresand
algorithms:
Stringclassesaredesignedasasafeandconvenientcomponent.
Thus,theyprovideanalmostself-explanatoryinterfaceandcheck
formanyerrorsintheinterface.
TheSTLwasdesignedtocombinedifferentdatastructureswith
differentalgorithmswhileachievingthebestperformance.Thus,the
STLisnotveryconvenientanditisnotrequiredtocheckformany
logicalerrors.Tobenefitfromthepowerfulframeworkandgreat
performanceoftheSTL,youmustknowtheconceptsandapply
themcarefully.
Bothofthesecomponentsarepartofthesamelibrary.Theywere
harmonizedabit,buttheystillfollowtheirindividual,fundamentaldesign
philosophies.
Onecomponentofthelibraryexistedasadefactostandardbefore
standardizationbegan:theIOStreamlibrary.Developedin1984,itwas
reimplementedandpartiallyredesignedin1989.Becausemany



programswereusingitalready,thegeneralconceptoftheIOStream
librarywasnotchanged,thuskeepingitbackwardcompatible.
Ingeneral,thewholestandard(languageandlibrary)istheresultofalot
ofdiscussionsandinfluencefromhundredsofpeopleallovertheworld.
Forexample,theJapanesecameupwithimportantsupportfor
internationalization.Ofcourse,mistakesweremade,mindswere
changed,andpeoplehaddifferentopinions.Then,in1994,whenpeople
thoughtthestandardwasclosetobeingfinished,theSTLwas
incorporated,whichchangedthewholelibraryradically.However,toget
finished,thethinkingaboutmajorextensionswaseventuallystopped,
regardlessofhowusefultheextensionwouldbe.Thus,hashtablesare
notpartofthestandard,althoughtheyshouldbeapartoftheSTLasa
commondatastructure.
Thecurrentstandardisnottheendoftheroad.Therewillbefixesof
bugsandinconsistencies,andtherelikelywillbeanextversionofthe
standardinfiveyearsorso.Howeverforthenextfewyears,C++
programmershaveastandardandthechancetowritepowerfulcodethat
isportabletoverydifferentplatforms.

2.2NewLanguageFeatures
ThecorelanguageandthelibraryofC++werestandardizedinparallel.
Inthisway,thelibrarycouldbenefitfromimprovementsinthelanguage
andthelanguagecouldbenefitfromexperiencesoflibrary
implementation.Infact,duringthestandardizationprocessthelibrary
oftenusedspeciallanguagefeaturesthatwerenotyetavailable.
C++isnotthesamelanguageitwasfiveyearsago.Ifyoudidn'tfollowits
evolution,youmaybesurprisedwiththenewlanguagefeaturesusedby
thelibrary.Thissectiongivesyouabriefoverviewofthosenewfeatures.
Fordetails,refertobooksonthelanguageinquestion.

WhileIwaswritingthisbook(in1998),notallcompilerswereableto
provideallofthenewlanguagefeatures.Ihope(andexpect)thatthiswill
changeverysoon(mostcompilervendorswerepartofthe
standardizationprocess).Thus,youmayberestrictedinyouruseofthe


library.Portableimplementationsofthelibrarytypicallyconsiderwhether
featuresarepresentintheenvironmenttheyuse(theyusuallyhave
sometestprogramstocheckwhichlanguagefeaturesarepresent,and
thensetpreprocessordirectivesaccordingtotheresultofthecheck).I'll
mentionanyrestrictionsthataretypicalandimportantthroughoutthe
bookbyusingfootnotes.
Thefollowingsubsectionsdescribethemostimportantnewlanguage
featuresthatarerelevantfortheC++standardlibrary.

2.2.1Templates
Almostallpartsofthelibraryarewrittenastemplates.Withouttemplate
support,youcan'tusethestandardlibrary.Moreover,thelibraryneeded
newspecialtemplatefeatures,whichIintroduceafterashortoverviewof
templates.
Templatesarefunctionsorclassesthatarewrittenforoneormoretypes
notyetspecified.Whenyouuseatemplate,youpassthetypesas
arguments,explicitlyorimplicitly.Thefollowingisatypicalexample—a
functionthatreturnsthemaximumoftwovalues:

template<classT>
inlineconstT&max(constT&a,constT&b)
{
//ifareturna

}
Here,thefirstlinedefinesTasanarbitrarydatatypethatisspecifiedby
thecallerwhenthecallercallsthefunction.Youcanuseanyidentifieras
aparametername,butusingTisverycommon,ifnotadefacto
convention.Thetypeisclassifiedbyclass,althoughitdoesnothave
tobeaclass.Youcanuseanydatatypeaslongasitprovidesthe
operationsthatthetemplateuses.[3]


×