The C++ Standard Library not only provides comprehensive documentation of each librarycomponent, it also offers clearly written explanations of complex concepts, describes the practicalp
Trang 1Contents
C++ Standard Library: A Tutorial and Reference, The
By Nicolai M Josuttis
Publisher : Addison WesleyPub Date : August 06, 1999ISBN : 0-201-37926-0Pages : 832
C++ Standard Library provides a set of common
classes and interfaces that greatly extend the coreC++ language The library, however, is not self-explanatory To make full use of its components-and
to benefit from their power-you need a resource thatdoes far more than list the classes and their functions
The C++ Standard Library not only provides
comprehensive documentation of each librarycomponent, it also offers clearly written explanations
of complex concepts, describes the practicalprogramming details needed for effective use, andgives example after example of working code
This thoroughly up-to-date book reflects the newestelements of the C++ standard library incorporated intothe full ANSI/ISO C++ language standard In
particular, the text focuses on the Standard TemplateLibrary (STL), examining containers, iterators,
function objects, and STL algorithms You will alsofind detailed coverage of special containers, strings,numerical classes, internationalization, and theIOStream library Each component is presented indepth, with an introduction to its purpose and design,examples, a detailed description, traps and pitfalls,and the exact signature and definition of its classesand their functions An insightful introduction tofundamental concepts and an overview of the librarywill help bring newcomers quickly up to speed
Trang 2The C++ Standard Library is the C++ resource you
will turn to again and again
EEn777
1.4 How to Read this Book1.5 State of the Art
1.6 Example Code and Additional Information1.7 Feedback
Chapter 2 Introduction to C++ and the Standard Library
2.1 History2.2 New Language Features2.3 Complexity and the Big-O NotationChapter 3 General Concepts
3.1 Namespace3.2 Header Files3.3 Error and Exception Handling3.4 Allocators
Chapter 4 Utilities
4.1 Pairs4.1.1 Convenience Function4.1.2 Examples of Pair Usage
Trang 48.1 The Concept of Function Objects
8.2 Predefined Function Objects
8.3 Supplementary Composing Function ObjectsChapter 9 STL Algorithms
13.2 Fundamental Stream Classes and Objects13.3 Standard Stream Operators << and >>13.4 State of Streams
Trang 515.4 A User-Defined Allocator
15.5 Allocators in Detail
15.6 Utilities for Uninitialized Memory in DetailInternet Resources
Bibliography
Trang 6Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks Where those
designations appear in this book and Addison Wesley Longman Inc., wasaware of a trademark claim, the designations have been printed in initialcaps or all caps
The authors and publisher have taken care in the preparation of this
book, but make no expressed or implied warranty of any kind and
assume no responsibility for errors or omissions No liability is assumedfor incidental or consequential damages in connection with or arising out
of the use of the information or programs contained herein
The publisher offers discounts on this book when ordered in quantity forspecial sales For more information, please contact:
Trang 7First printing, July 1999
Trang 8In the beginning, I only planned to write a small German book (400 pages
or so) about the C++ standard library That was in 1993 Now, in 1999you see the result — an English book with more than 800 pages of facts,figures, and examples My goal is to describe the C++ standard library sothat all (or almost all) your programming questions are answered beforeyou think of the question Note, however, that this is not a complete
description of all aspects of the C++ standard library Instead, I presentthe most important topics necessary for learning and programming inC++ by using its standard library
Each topic is described based on the general concepts; this discussionthen leads to the specific details needed to support every-day
programming tasks Specific code examples are provided to help youunderstand the concepts and the details
That's it — in a nutshell I hope you get as much pleasure from readingthis book as I did from writing it Enjoy!
Acknowledgments
This book presents ideas, concepts, solutions, and examples from manysources In a way it does not seem fair that my name is the only name onthe cover Thus, I'd like to thank all the people and companies who
helped and supported me during the past few years
First, I'd like to thank Dietmar Kühl Dietmar is an expert on C++,
especially on input/output streams and internationalization (he
implemented an I/O stream library just for fun) He not only translatedmajor parts of this book from German to English, he also wrote sections
of this book using his expertise In addition, he provided me with
invaluable feedback over the years
Second, I'd like to thank all the reviewers and everyone else who gave
me their opinion These people endow the book with a quality it would
Trang 9Veldhuizen, Chichiang Wan, Judy Ward, and Thomas Wikehult TheGerman reviewers included Ralf Boecker, Dirk Herrmann, Dietmar Kühl,Edda Lörke, Herbert Scheubner, Dominik Strasser, and Martin Weitzel.Additional input was provided by Matt Austern, Valentin Bonnard, GregColvin, Beman Dawes, Bill Gibbons, Lois Goldthwaite, Andrew Koenig,Steve Rumbsby, Bjarne Stroustrup, and David Vandevoorde
Special thanks to Dave Abrahams, Janet Cocker, Catherine Ohala, andMaureen Willard who reviewed and edited the whole book very carefully.Their feedback was an incredible contribution to the quality of this book
A special thanks goes to my "personal living dictionary" — Herb Sutter —the author of the famous "Guru of the Week" (a regular series of C++programming problems that is published on the
comp.std.C++.moderated Internet newsgroup)
I'd also like to thank all the people and companies who gave me the
opportunity to test my examples on different platforms with different
compilers Many thanks to Steve Adamczyk, Mike Anderson, and JohnSpicer from EDG for their great compiler and their support It was a bighelp during the standardization process and the writing of this book
Many thanks to P J Plauger and Dinkumware, Ltd, for their early
standard-conforming implementation of the C++ standard library Manythanks to Andreas Hommel and Metrowerks for an evaluative version oftheir Code Warrior Programming Environment Many thanks to all thedevelopers of the free GNU and egcs compilers Many thanks to
Microsoft for an evaluative version of Visual C++ Many thanks to RolandHartinger from Siemens Nixdorf Informations Systems AG for a test
version of their C++ compiler Many thanks to Topjects GmbH for anevaluative version of the ObjectSpace library implementation
Many thanks to everyone from Addison Wesley Longman who workedwith me Among others this includes Janet Cocker, Mike Hendrickson,Debbie Lafferty, Marina Lang, Chanda Leary, Catherine Ohala, MartyRabinowitz, Susanne Spitzer, and Maureen Willard It was fun
Trang 10standardization process, for their support and patience (sometimes I askreally silly questions)
Last but not least, many thanks and kisses for my family: Ulli, Lucas,Anica, and Frederic I definitely did not have enough time for them due tothe writing of this book
Have fun and be human!
Trang 11CONTENTS
Trang 12would enable programmers to use general components and a higherlevel of abstraction without losing portability, rather than having to
develop all code from scratch
The standardization process was started in 1989 by an internationalANSI/ISO committee It developed the standard based on Bjarne
Stroustrup's books The C++ Programming Language and The Annotated
C++ Reference Manual After the standard was completed in 1997,
several formal motions by different countries made it an international ISOand ANSI standard in 1998 The standardization process included thedevelopment of a C++ standard library The library extends the core
language to provide some general components By using C++'s ability toprogram new abstract and generic types, the library provides a set ofcommon classes and interfaces This gives programmers a higher level
of abstraction The library provides the ability to use
String types
Different data structures (such as dynamic arrays, linked lists, andbinary trees)
Trang 13The library is not self-explanatory To use these components and to
benefit from their power, you need a good introduction that explains theconcepts and the important details instead of simply listing the classesand their functions This book is written exactly for that purpose First, itintroduces the library and all of its components from a conceptional point
of view Next, it describes the details needed for practical programming.Examples are included to demonstrate the exact usage of the
components Thus, this book is a detailed introduction to the C++ libraryfor both the beginner and the practical programmer Armed with the dataprovided herein, you should be able to take full advantage of the C++standard library
Caveat: I don't promise that everything described is easy and self-explanatory The library provides a lot of flexibility, but flexibility for
nontrivial purposes has a price Beware that the library has traps andpitfalls, which I point out when we encounter them and suggest ways ofavoiding them
1.2 What You Should Know Before Reading this Book
To get the most from this book you should already know C++ (The bookdescribes the standard components of C++, but not the language itself.)You should be familiar with the concepts of classes, inheritance,
templates, and exception handling However, you don't have to know all
Trang 14described in the book (the minor details about the language are moreimportant for people who want to implement the library rather than use it).Note that the language has changed during the standardization process,
so your knowledge might not be up to date Section 2.2, provides a briefoverview and introduction of the latest language features that are
important for using the library You should read this section if you are notsure whether you know all the new features of C++ (such as the keyword
typename and the concept of namespaces)
1.3 Style and Structure of the Book
The C++ standard library provides different components that are
somewhat but not totally independent of each other, so there is no easyway to describe each part without mentioning others I considered
several different approaches for presenting the contents of this book.One was on the order of the C++ standard However, this is not the bestway to explain the components of the C++ standard library from scratch.Another was to start with an overview of all components followed by
chapters that provided more details Alternatively, I could have sorted thecomponents, trying to find an order that had a minimum of cross-
references to other sections My solution was to use a mixture of all threeapproaches I start with a brief introduction of the general concepts andthe utilities that are used by the library Then, I describe all the
components, each in one or more chapters The first component is thestandard template library (STL) There is no doubt that the STL is themost powerful, most complex, and most exciting part of the library Itsdesign influences other components heavily Then I describe the moreself-explanatory components, such as special containers, strings, andnumeric classes The next component discussed is one you probablyknow and use already: the IOStream library It is followed by a discussion
of internationalization, which had some influence on the IOStream library
Each component description begins with the component's purpose,
design, and some examples Next, a detailed description follows thatbegins with different ways to use the component, as well as any trapsand pitfalls associated with it The description usually ends with a
reference section, in which you can find the exact signature and definition
Trang 15The following is a description of the book's contents The first four
chapters introduce this book and the C++ standard library in general:Chapter 1: About this Book
This chapter (which you are reading right now) introduces the book'ssubject and describes its contents
Chapter 2: Introduction to C++ and the Standard Library
This chapter provides a brief overview of the history of the C++
standard library and the context of its standardization It also
contains some general hints regarding the technical background forthis book and the library, such as new language features and theconcept of complexity
Chapter 3: General Concepts
This chapter describes the fundamental concepts of the library thatyou need to understand to work with all the components In
particular, it introduces the namespace std, the format of headerfiles, and the general support of error and exception handling
Chapter 4: Utilities
This chapter describes several small utilities provided for the user ofthe library and for the library itself In particular, it describes auxiliaryfunctions such as max(), min(), and swap(), types pair
and auto_ptr, as well as numeric_limits, which providemore information about implementation-specific details of numericdata types
Chapters 5 through 9 describe all aspects of the STL:
Chapter 5: The Standard Template Library
This chapter presents a detailed introduction to the concept of the
Trang 16to process collections of data It explains step-by-step the concept,the problems, and the special programming techniques of the STL,
as well as the roles of its parts
Chapter 6: STL Containers
This chapter explains the concepts and describes the abilities of theSTL's container classes First it describes the differences betweenvectors, deques, lists, sets, and maps, then their common abilities,and all with typical examples Lastly it lists and describes all
container functions in form of a handy reference
Chapter 7: STL Iterators
This chapter deals in detail with the STL's iterator classes In
particular, it explains the different iterator categories, the auxiliaryfunctions for iterators, and the iterator adapters, such as stream
Chapters 10 through 12 describe "simple" individual standard classes:Chapter 10: Special Containers
This chapter describes the different special container classes of theC++ standard library It covers the container adapters for queues andstacks, as well as the class bitset, which manages a bitfield with
an arbitrary number of bits or flags
Chapter 11: Strings
Trang 17Chapter 12: Numerics
This chapter describes the numeric components of the C++ standardlibrary In particular, it covers types for complex numbers and classesfor the processing of arrays of numeric values (the latter may beused for matrices, vectors, and equations)
Chapters 13 and 14 deal with I/O and internationalization (two closelyrelated subjects):
Chapter 13: Input/Output Using Stream Classes
This chapter covers the I/O component of C++ This component isthe standardized form of the commonly known IOStream library Thechapter also describes details that may be important to programmersbut are typically not so well known For example, it describes thecorrect way to define and integrate special I/O channels, which areoften implemented incorrectly in practice
Chapter 14: Internationalization
This chapter covers the concepts and classes for the
internationalization of programs In particular, it describes the
handling of different character sets, as well as the use of differentformats for such values as floating-point numbers and dates
The rest of the book contains:
Chapter 15: Allocators
This chapter describes the concept of different memory models inthe C++ standard library
An appendix with
Trang 18sections To program with certain components of the C++ standard
library, the best way to find something is to use the index I have tried tomake the index very comprehensive to save you time when you are
looking for something
In my experience, the best way to learn something new is to look at
examples Therefore, you'll find a lot of examples throughout the book.They may be a few lines of code or complete programs In the latter
case, you'll find the name of the file containing the program as the firstcomment line You can find the files on the Internet at my Web site athttp://www.josuttis.com/libbook/
1.5 State of the Art
While I was writing this book, the C++ standard was completed Pleasebear in mind that some compilers might not yet confirm to it This willmost likely change in the near future As a consequence, you might
Trang 19on several software CDs
1.6 Example Code and Additional Information
You can access all example programs and acquire more informationsabout this book and the C++ standard library from my Web site at
http://www.josuttis.com/libbook/ Also, you can find a lot of additionalinformation about this topic on the Internet See Internet Resources fordetails
1.7 Feedback
I welcome your feedback (good and bad) on this book I tried to prepare itcarefully; however, I'm human, and at some time I have to stop writingand tweaking So, you may find some errors, inconsistencies, or subjectsthat could be described better Your feedback will give me the chance toimprove later editions The best way to reach me is by Email:
Trang 20Many thanks
CONTENTS
Trang 21CONTENTS
Trang 22The standard has the title "Information Technology — Programming
Languages — C++." Its document number is ISO/IEC 14882-1998, and it
is distributed by the national bodies of the ISO, such as the ANSI in theUnited States.[1]
The standard was an important milestone for C++ Because it defines theexact contents and behavior of C++, it makes it easier to teach C++, touse C++ in applications, and to port C++ programs to different platforms
It also gives users greater freedom of choice regarding different C++implementations Its stability and portability help library providers and toolproviders as well as implementers Thus, the standard helps C++
application developers build better applications faster, and maintain themwith less cost and effort
Part of the standard is a standard library This library provides core
components for I/O, strings, containers (data structures), algorithms
(such as sort, search, and merge), support for numeric computation, and(as could be expected from an international standard) support for
internationalization (such as different character sets)
You may wonder why the standardization process took almost 10 years,and if you know some details about the standard you might wonder why
Trang 23standardization process, a lot was accomplished The result is usable inpractice, but it is not perfect (nothing ever is)
The standard is not the result of a company with a big budget and a lot oftime Standards organizations pay nothing or almost nothing to the
people who work on developing standards So, if a participant doesn'twork for a company that has a special interest in the standard, the work
is done for fun Thank goodness there were a lot of dedicated peoplewho had the time and the money to do just that
The C++ standard was not developed from scratch It was based on thelanguage as described by Bjarne Stroustrup, the creator of C++ Thestandard library, however, was not based on a book or on an existinglibrary Instead, different, existing classes were integrated.[2] Thus, theresult is not very homogeneous You will find different design principlesfor different components A good example is the difference between thestring class and the STL, which is a framework for data structures andalgorithms:
String classes are designed as a safe and convenient component.Thus, they provide an almost self-explanatory interface and checkfor many errors in the interface
The STL was designed to combine different data structures withdifferent algorithms while achieving the best performance Thus, theSTL is not very convenient and it is not required to check for manylogical errors To benefit from the powerful framework and greatperformance of the STL, you must know the concepts and applythem carefully
Both of these components are part of the same library They were
harmonized a bit, but they still follow their individual, fundamental designphilosophies
One component of the library existed as a de facto standard before
standardization began: the IOStream library Developed in 1984, it wasreimplemented and partially redesigned in 1989 Because many
Trang 24In general, the whole standard (language and library) is the result of a lot
of discussions and influence from hundreds of people all over the world.For example, the Japanese came up with important support for
internationalization Of course, mistakes were made, minds were
changed, and people had different opinions Then, in 1994, when peoplethought the standard was close to being finished, the STL was
incorporated, which changed the whole library radically However, to getfinished, the thinking about major extensions was eventually stopped,regardless of how useful the extension would be Thus, hash tables arenot part of the standard, although they should be a part of the STL as acommon data structure
The current standard is not the end of the road There will be fixes ofbugs and inconsistencies, and there likely will be a next version of thestandard in five years or so However for the next few years, C++
implementation In fact, during the standardization process the libraryoften used special language features that were not yet available
C++ is not the same language it was five years ago If you didn't follow itsevolution, you may be surprised with the new language features used bythe library This section gives you a brief overview of those new features.For details, refer to books on the language in question
While I was writing this book (in 1998), not all compilers were able toprovide all of the new language features I hope (and expect) that this willchange very soon (most compiler vendors were part of the
standardization process) Thus, you may be restricted in your use of the
Trang 25some test programs to check which language features are present, andthen set preprocessor directives according to the result of the check) I'llmention any restrictions that are typical and important throughout thebook by using footnotes
The following subsections describe the most important new languagefeatures that are relevant for the C++ standard library
2.2.1 Templates
Almost all parts of the library are written as templates Without templatesupport, you can't use the standard library Moreover, the library needednew special template features, which I introduce after a short overview oftemplates
Templates are functions or classes that are written for one or more typesnot yet specified When you use a template, you pass the types as
arguments, explicitly or implicitly The following is a typical example — afunction that returns the maximum of two values:
template <class T>
inline const T& max (const T& a, const T& b) {
// if a <b then use b else use a
return a < b ? b : a;
}
Here, the first line defines T as an arbitrary data type that is specified bythe caller when the caller calls the function You can use any identifier as
a parameter name, but using T is very common, if not a de facto
convention The type is classified by class, although it does not have
to be a class You can use any data type as long as it provides the
operations that the template uses.[3]
Trang 26available when you call it, so that you can compile the function for your
specific type Therefore, the only portable way of using templates at themoment is to implement them in header files by using inline functions.[4]
introduced in Section 10.4,) you can pass the number of bits as the
template argument The following statements define two bitfields, one
with 32 bits and one with 50 bits:
bitset<32> fIags32; // bitset with 32 bits bitset<50> flags50; // bitset with 50 bits
These bitsets have different types because they use different template
arguments Thus, you can't assign or compare them (except if a
corresponding type conversion is provided)
Trang 27Thus, ptr is a pointer to the type T::SubType. Without
typename, SubType would be considered a static member Thus
T::SubType * ptr
Trang 28According to the qualification of SubType being a type, any type that isused in place of T must provide an inner type SubType. For example,the use of type Q as a template argument
typename.
Apart from this, typename can also be used instead of class in atemplate declaration:
template <typename T> class MyClass;
Trang 32int i2 = int(); // initialized with zero
This feature is provided to enable you to write template code that ensuresthat values of any type have a certain default value For example, in thefollowing function the initialization guarantees that x is initialized withzero for fundamental types:
Trang 33any block or function is left as if there was a return statement
However, the program does not jump anywhere For all local objects that
are declared in the blocks that the program leaves due to the exception
their destructors are called Stack unwinding continues until main() is
left, which ends the program, or until a catch clause "catches" and
handles the exception:
Trang 34two are not necessarily the same For example, in many circumstancesbad user input is not an exception; it typically happens So it is often agood idea to handle wrong user input locally using the usual error-
Trang 35A violation of an exception specification causes special behavior to occur.See the description of the exception class bad_exception on page
26 for details
The C++ standard library provides some general features for exceptionhandling, such as the standard exception classes and class auto_ptr
Trang 37different behavior than the one expected because you included or usedyour code in another module In fact, using directives in header files isreally bad design
The C++ standard library defines all identifiers in namespace std. SeeSection 3.1, for details
2.2.5 Type bool
To provide better support for Boolean values, type bool was introduced.Using bool increases readability and allows you to overload behaviorfor Boolean values The literals true and false were introduced asBoolean values Automatic type conversions to and from integral valuesare provided The value 0 is equivalent to false. Any other value isequivalent to true.
2.2.6 Keyword explicit
By using the keyword explicit, you can prohibit a single argumentconstructor from defining an automatic type conversion A typical
example of the need for this feature is in a collection class in which youcan pass the initial size as constructor argument For example, you coulddeclare a constructor that has an argument for the initial size of a stack:
Trang 38explicit Stack(int size); // create stack with initial size
.
};
Here, the use of explicit is rather important Without explicit
this constructor would define an automatic type conversion from int to
Stack. If this happens, you could assign an int to a Stack:
Trang 39from type X, whereas the latter creates a new object of type Y by using
Trang 40and the type conversion fails, dynamic_cast throws a bad_cast
exception (bad_cast is described on page 26) Note that from a
design point of view, it it always better to avoid such type-dependent
statements when you program with polymorphic types
const_cast
This operator adds or removes the constness of a type In addition,
you can remove a volatile qualification Any other change of the