Table Of ContentThis electronic edition is available only as a pdf-file. It is a revised and improved
versionofthebookmentionedinthecopyrightnoticebelow.
This material is made available by Pearson Education Ltd in electronic form
subjecttotheconditionthatthematerialnoranypartofthematerialmaynot
becopied,printed,downloaded,savedortransferredtoanyothercomputerfile,
ordistributedonanetwork. ThismaterialfirstappearedinUlrichBreymann,
Designing Components with the C++ STL, ISBN 0 201 67488 2, (cid:13)c Pearson
EducationLimited2000,publishedbyPearsonEducationLtd.
UlrichBreymann
Designing Components with the C++ STL
revised edition
Dateofprint: September22,2002
for Lena, Niko and Anne
Foreword
Ironically,itwasinWaterloothattheSTLwasadoptedaspartoftheISO/ANSIStan-
dardC++Library,andfromthatdayonitwentontoatriumphalmarch. Alexander
Stepanov and Meng Lee had proposed the result of years of research at Hewlett-
Packard, a standard template library, to the standards committee. The committee
gracefullyadoptedtheSTLaspartoftheC++Standardatacommitteemeetingin
Waterloointhesummerof1994,aftercountlesscontroversialdiscussionsandmuch
work spent by committee members on making the STL fit for a standard. Most
importantly, the adoption was tied to the condition that the source code had to be
madepubliclyavailable. SincethentheSTLhasbecomemoreandmorepopularin
the C++ community and conquered the hearts of quite a number of programmers.
Personally, I know of software developers who cannot imagine getting their work
done anymore without a general-purpose library like the STL. Obviously, not all
Waterloosarethesame. ThisWaterloowasinOntario–seeminglyagoodomen.
Much of the merit, however, is not seriously due to picking the right location
for presenting a library. The STL is an invaluable foundation library that makes
programmersmoreproductiveintwoways. Itcontainsalotofdifferentcomponents
that can be plugged together, so it provides a flexible and extensible framework.
Plus,ithasanelegant,consistent,andeasytocomprehendarchitecture.
WhenUlrichaskedmeinfall1995whetherIwouldfeellikewritingthisbook
with him, my first thought was: Does the world really need another STL book?
Threebookshadalreadybeenoutatthatpointintime;Ihadvolunteeredforwriting
aregularcolumnabouttheSTLforamagazineofhighrenownlikeC++Report;nu-
merousconferenceorganizersinvitedmetospeakabouttheSTL;evenmyemployer
had me prepare and conduct courses on the STL. In sum, there were countless re-
sourcesavailabletomeetthegrowinginterestintheC++community.Isimplyques-
tionedtheneedforyetanotherSTLtutorial. Aboutayearlater,IheldtheGerman
editionofhisbookinmyhands,skimmedthroughthepages,andstartedreading–
with increasing enjoyment. And I must admit, he convinced me. This book goes
beyondthetutorialsIhadseenuptothenandhasanapproachandappealofitsown:
itexplainstechniquesforbuildingyourowndatastructuresandalgorithmsontopof
theSTLandthiswayappreciatestheSTLforwhatitis–aframework. Ihadbeen
lookingforthisaspectintutorials,ofteninvain.
Ascanbeexpected,thebookstartsoffwithanintroductiontotheSTL.Already
theinitial explanationsprovideyou withinsights intotheinternals ofthe STLthat
youmissinotherintroductorymaterial. Forinstance,Ulrichexplainswhattheim-
plementationofaniteratortypicallylookslike.Thiskindofinformationisprofound
vi FOREWORD
enough to lay the foundations for leaving the realm of simple STL usage, and en-
ables you to understand and eventually extend the STL framework by adding your
owncontainersandalgorithms. ThemostdistinguishingpartofthisbookisPartIII:
BeyondtheSTL.Youwillseedemonstrationsofelegantandsophisticatedusageof
the STL – well-known data structures like matrices and graphs built on top of the
STL,aswellasexamplesofadditionstotheSTL,likehash-basedcontainers.
IwouldalsowanttoacknowledgethatthisrevisedEnglisheditionofthebookis
oneofthemostaccurateandup-to-datesourcesofinformationontheSTLcurrently
available. ItreflectstheISO/IECC++StandardwhichwaspublishedinSeptember
1998. Keep up with the language standard and learn how the STL will improve
yourprograms. Insum,Ienjoyedthebookandappreciateitasasoundandserious
referencetotheSTL.Ihopeyouwillalso.
AngelikaLanger
June1999
Preface
The Standard Template Library (STL)
OnereasonforthesuccessofC++isthattodayalargenumberoflibrariesisavailable
onthemarketwhichgreatlyfacilitatethedevelopmentofprograms,becausetheyof-
ferreliableandwell-provencomponents.Aparticularlycarefullyconstructedlibrary
istheStandardTemplateLibrary,whichhasbeendevelopedatHewlett-Packardby
Alexander Stepanov, Meng Lee, and their colleagues. It has been accepted by the
ANSI/ISOcommitteeaspartoftheC++Standard(ISO/IEC(1998)).
The emphasis of the STL is on data structures for containers, and the al-
gorithms that work with them. The technical reference document of the STL
(StepanovandLee(1995))haspractically,withsomemodifications,becomeapart
of the C++ Standard (ISO/IEC(1998)). Both are the basis for the first two parts
of this book. The document can be freely used, if the copyright conditions are
quoted. Theseconditionsplusreferencestosourcescanbefoundonpage273ofthe
Appendix.
The C++ Standard Library and the STL
The STL does not include the entire C++ Standard Library nor all its templates; it
represents,however,themostimportantandmostinterestingpart.TheC++Standard
Libraryincludesseveralareas:
• Genericdatastructuresandalgorithms
–containers
–algorithms
–iterators
–functionalobjects
• Internationalization
• Diagnosis(exceptions)
• Numericissues
–complexnumbers
–numericarraysandrelatedoperations
viii PREFACE
• Inputandoutputlibrary(streams)
• Miscellaneous
–memorymanagement(allocators)andaccess
–dateandtime
–strings
The area shaded in gray constitutes the subject of this book – in other words,
thebookdoesnotdealwiththehistoricSTL,butwiththatpartoftheC++Standard
LibrarythathasoriginatedfromtheSTL.Besidesanintroduction, theemphasisis
onsampleapplicationsandtheconstructionofnewcomponentsonthebasisofthe
STL.
Owing to several requirements by the ISO/ANSI standard committee, this part
of the C++ Standard Library no longer matches the original STL exactly. Thus, a
more precise – albeit too long – title for this book would be Generic algorithms
anddatastructuresoftheC++StandardLibrary–introduction,applications, and
constructionofnewcomponents. Thechangesaffectonlysomedetails,butnotthe
concept; therefore the name Standard Template Library and the abbreviation STL
havebeenretained.
The STL as a framework
TheSTLisanall-purposelibrarywithanemphasisondatastructuresandalgorithms.
Itmakesheavyuseofthetemplatemechanismforparameterizingcomponents. The
uniform design of the interfaces allows a flexible cooperation of components and
also the construction of new components in STL-conforming style. The STL is
thereforeauniversallyusableandextendableframework,whichoffersmanyadvan-
tages with respect to quality, efficiency, and productivity. The successful concept
hasalreadybeencopied,astheJavaGenericLibraryshows.
Aims of this book
Thebookhastwoaims. Asatechnicalreference,thereferencedocumentmentioned
earlierishardlysuitedtoexplaintheconceptsoftheSTL.Therefore,thefirstaimis
to present how the STL can be used in a sensible way. Internal details of the STL
aredescribedonlytotheextentneededtounderstandhowitworks.
However,thisbookismorethanasimpleintroduction. Withtheaidofcompre-
hensive examples, the STL is presented as a tool box for the construction of more
powerfulandsometimesevenfastercomponents. Thesecomponentsaremorecom-
plexdatastructuresandalgorithmswhichcanbeefficientlyimplementedbymeans
ofthemodules contained intheSTL.Thealgorithmsare evaluated withrespectto
their run time behavior relative to the amount of data to be processed (time com-
plexity). However, not only the modules themselves and their combination are of
interest,butalsotheprogrammingtechniquesemployedintheSTLandinthisbook.
PREFACE ix
Readership
ThisbookisintendedforallthoseinvolvedinthedevelopmentofsoftwareinC++,
betheysystemdesigner,projectmanager,studentofcomputerscience,orprogram-
mer. Tomakethesoftwareportable,maintainable,andreusable,itishighlyrecom-
mended that valid standards are adhered to and thoroughly exploited – otherwise,
they would not be needed. The use of prefabricated components such as those of
the STL increases both the reliability of the software and the productivity of the
developers. ThepreconditionforunderstandingthisbookisknowledgeoftheC++
programminglanguageanditstemplatemechanismswhichcanbegainedbyreading
goodtextbooksonthesubject,suchasLippmanandLajoie(1998).
Structure of the book
Thebookisdividedintothreeparts.PartIisanintroductiontotheSTLanddescribes
itsconceptsandelements, withtheemphasisoniteratorsandcontainers. Thecon-
ceptofiteratorsandcontainersisessentialfortheworkingofthealgorithms.
PartIIdiscussesthestandardalgorithms,wherealmosteveryalgorithmisillus-
trated with an example. Because of the large number of algorithms described, it
shouldbeviewedasacatalog.
PartIIIdescribesapplicationsandextensions. Extensiveexampleshelptoshow
howthecomponentssuppliedbytheSTLcanbeusedtodesignmorecomplexdata
structuresandalgorithmsandpowerfulabstractdatatypes.
Examples
NotonlyisthefunctioningofSTLelementsdescribed,butforalmosteveryelement
andalltheapplicationsofPartIIIanexecutableexampleispresentedthatcanberun
onthereader’scomputer. Thisgivesthereaderachancetoexperimentandachieve
adeeperunderstanding. TheexamplesareavailableviatheInternet,seesectionA.2
onpage273.
Remarks
TheoriginalpublicdomainimplementationoftheSTLbyHewlett-Packardisalit-
tle bit different to the C++ standard, since modifications and extensions have been
carriedoutsincetheintegrationoftheSTL.Inthemeantimealsootherimplemen-
tationsareavailable,e.g. fromSiliconGraphicsorRogueWave. Itcanbeexpected
thatsometimeafterthepublicationoftheC++standardinSeptember1998allcom-
pilerproducerswillsupplyanSTLimplementationconformingtothestandard, so
thatdifferencesinvariousimplementationswillplayonlyaverymarginalrole.
Inthetext,programmingissuessuchasvariables,keywords,andprogramexam-
plescanberecognizedbythis type style. Explanationsthatinterruptthetext
of a program are marked as indented comments /* ... */. Names of files are
x PREFACE
printedinitalicsandscreendisplaysinslantedcharacters. Atagatthepagemargin
tip indicatesanimportanthintortipforprogramming.
Suggestions and criticism
are more than welcome. If you want to point out errors or make suggestions or
criticalremarks,youcancontacttheauthoreitherthroughthepublisherordirectly
viae-mail([email protected]@informatik.hs-bremen.de).
Acknowledgements
I have received many suggestions from my colleagues Ulrich Eisenecker (Fach-
hochschuleHeidelberg), AndreasSpillner(HochschuleBremen), BerndOwsnicki-
Klewe(FachhochschuleHamburg)andAndreasScherer(RWTHAachen),andIam
verygratefultothemfortheircriticalandthoroughreviewofthemanuscriptandfor
theirhelpfulhintsandtips. Allweaknessesanderrorsrestsolelywiththeauthor.