Home > Store

C++ Standard Library, The: A Tutorial and Reference

Register your product to gain access to bonus material or receive a coupon.

C++ Standard Library, The: A Tutorial and Reference

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 1999
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-37926-0
  • ISBN-13: 978-0-201-37926-6

The C++ standard library provides a set of common classes and interfaces that greatly extend the core C++ 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 that does far more than list the classes and their functions.

The C++ Standard Library not only provides comprehensive documentation of each library component, it also offers clearly written explanations of complex concepts, describes the practical programming details needed for effective use, and gives example after example of working code.

This thoroughly up-to-date book reflects the newest elements of the C++ standard library incorporated into the full ANSI/ISO C++ language standard. In particular, the text focuses on the Standard Template Library (STL), examining containers, iterators, function objects, and STL algorithms. You will also find detailed coverage of special containers, strings, numerical classes, internationalization, and the IOStream library. Each component is presented in depth, with an introduction to its purpose and design, examples, a detailed description, traps and pitfalls, and the exact signature and definition of its classes and their functions. An insightful introduction to fundamental concepts and an overview of the library will help bring newcomers quickly up to speed.

Comprehensive, detailed, readable, and practical, The C++ Standard Library is the C++ resource you will turn to again and again. An accompanying Web site, including source code, can be found at http://www.josuttis.com/.



0201379260B04062001

Downloads

Supplements

Click below for Supplements related to this title:
Supplements

Extras

Web Resources

Click below for Web Resources related to this title:
Support Site

Sample Content

Table of Contents



Preface.


Acknowledgments.


1. About this Book.

Why this Book.

What You Should Know Before Reading this Book.

Style and Structure of the Book.

How to Read this Book.

State of the Art.

Example Code and Additional Information.

Feedback.



2. Introduction to C++ and the Standard Library.

History.

New Language Features.

Templates. Nontype Template Parameters. Default Template Parameters. Keyword typename. Member Templates. Nested Template Classes. Explicit Initialization for Fundamental Types. Exception Handling. Namespaces. Type bool. Keyword explicit. New Operators for Type Conversion. Initialization of Constant Static Members. Definition of main().

Complexity and the Big-O Notation.



3. General Concepts.

Namespace std.

Header Files.

Error and Exception Handling.

Standard Exception Classes. Exception Classes for Language Support. Exception Classes for the Standard Library. Exception Classes for Errors Outside the Scope of a Program. Exceptions Thrown by the Standard Library. Header Files for Exception Classes. Members of Exception Classes. Throwing Standard Exceptions. Deriving Standard Exception Classes.

Allocators.



4. Utilities.

Pairs.

Pair Comparisons. Convenience Function make_pair(). Examples of Pair Usage.

Class auto_ptr.

Motivation of Class auto_ptr. Transfer of Ownership by auto_ptr. Source and Sink. Caveat. auto_ptrs as Members. Misusing auto_ptrs. auto_ptr Examples. Class auto_ptr in Detail. Type Definitions. Constructors, Assignments, and Destructors. Value Access. Value Manipulation. Conversions. Sample Implementation of Class auto_ptr.

Numeric Limits.

Class numeric_limits<>. Example of Using numeric_limits<>.

Auxiliary Functions.

Processing the Minimum and Maximum. Swapping Two Values.

Supplementary Comparison Operators.

Header Files <cstddef> and <cstdlib>.

Definitions in <cstddef>. Definitions in <cstdlib>.



5. The Standard Template Library.

STL Components.

Containers.

Sequence Containers. Vectors. Deques. Lists. Strings. Ordinary Arrays. Associative Containers. Container Adapters.

Iterators.

Examples of Using Associative Containers. Examples of Using Sets and Multisets. Examples of Using Maps and Multimaps. Maps as Associative Arrays. It

Preface

In 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 1999 you 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 so that all (or almost all) your programming questions are answered before you think of the question. Note, however, that this is not a complete description of all aspects of the C++ Standard Library. Instead, I present the most important topics necessary for learning and programming in C++by using its standard library.

Each topic is described based on the general concepts;this discussion then leads to the specific details needed to support everyday programming tasks. Specific code examples are provided to help you understand the concepts and the details.

That's it--in a nutshell. I hope you get as much pleasure from reading this book as I did from writing it. Enjoy!

Acknowledgments

This book presents ideas, concepts,solutions, and examples from many sources. In a way it does not seem fair that my name is the only name on the 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 Kuhl. 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 translated major 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 never have had without their input. (Because the list is extensive, please forgive me for any oversight.) The reviewers for the English version of this book included Chuck Allison, Greg Comeau, James A. Crotinger, Gabriel Dos Reis, Alan Ezust, Nathan Meyers, Werner Mossner, Todd Veldhuizen, Chichiang Wan, Judy Ward, and Thomas Wikehult. The German reviewers included Ralf Boecker, Dirk Herrmann, Dietmar Kuhl, Edda Lorke, Herbert Scheubner, Dominik Strasser, and Martin Weitzel. Additional input was provided by Matt Austern, Valentin Bonnard, Greg Colvin, Beman Dawes, Bill Gibbons, Lois Goldthwaite, Andrew Koenig, Steve Rumbsby, Bjarne Stroustrup, and David Vandevoorde.

Special thanks to Dave Abrahams, Janet Cocker, Catherine Ohala, and Maureen 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 John Spicer from EDG for their great compiler and their support. It was a big help 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. Many thanks to Andreas Hommel and Metrowerks for an evaluative version of their CodeWarrior Programming Environment. Many thanks to all the developers of the free GNU and egcs compilers. Many thanks to Microsoft for an evaluative version of Visual C++. Many thanks to Roland Hartinger from Siemens Nixdorf Informations Systems AG for a test version of their C++ compiler. Many thanks to Topjects GmbH for an evaluative version of the ObjectSpace library implementation.

And, of course many thanks for those who invented, designed, or implemented C++ or parts of the library. Among others are Bjarne Stroustrup, Alexander Stepanov, Meng Lee, Matt Austern, Boris P. Fomichev, and all the other guys who wrote the SGI STL and the STLport.

Many thanks to everyone from Addison Wesley Longman who worked with me. Among others this includes Janet Cocker, Mike Hendrickson, Debbie Lafferty, Marina Lang, Chanda Leary, Catherine Ohala, Marty Rabinowitz, Susanne Spitzer,and Maureen Willard. It was fun.

In addition, I'd like to thank the people at BREDEX GmbH and all the people in the C++ community, particularly those involved with the standardization process, for their support and patience (sometimes I ask really 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 to the writing of this book.

Have fun and be human!

About this Book

Soon after its introduction, C++ became a de facto standard in object-oriented programming. This led to the goal of standardization. Only by having a standard, could programs be written that would run on different platforms--from PCs to mainframes. Furthermore, a standard C++ library would enable programmers to use general components and a higher level of abstraction without losing portability, rather than having to develop all code from scratch.

The standardization process was started in 1989 by an international ANSI/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 ISO and ANSI standard in 1998. The standardization process included the development of a C++ Standard Library. The library extends the core language to provide some general components. By using C++'s ability to program new abstract and generic types, the library provides a set of common 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, and binary trees), different algorithms (such as different sorting algorithms), numeric classes, input/output (I/O) classes, and classes for internationalization support.

All of these are supported by a fairly simple programming interface. These components are very important for many programs. These days, data processing often means inputting, computing, processing, and outputting large amounts of data, which are often strings.

The library is not self-explanatory. To use these components and to benefit from their power,you need a good introduction that explains the concepts and the important details instead of simply listing the classes and their functions. This book is written exactly for that purpose. First, it introduces 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++ library for both the beginner and the practical programmer. Armed with the data provided 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 and pitfalls,which I point out when we encounter them and suggest ways of avoiding them.

What You Should Know Before Reading this Book

To get the most from this book you should already know C++. (The book describes 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 of the minor details about the language. The important details are described in the book (the minor details about the language are more important 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.

The section on newlang features provides a brief overview and introduction of the latest language features that are important for using the library. You should read this section if you are not sure whether you know all the new features of C++ (such as the keyword {\tt typename} and the concept of namespaces).

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 easy way 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 best way 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 the components, trying to find an order that had a minimum of cross-references to other sections. My solution was to use a mixture of all three approaches.

I start with a brief introduction of the general concepts and the utilities that are used by the library. Then, I describe all the components, each in one or more chapters. The first component is the standard template library (STL). There is no doubt that the STL is the most powerful, most complex, and most exciting part of the library. Its design influences other components heavily. Then I describe the more self-explanatory components, such as special containers, strings,and numeric classes. The next component discussed is one you probably know and use already: the iostreamlib{}. It is followed by a discussion of internationalization, which had some influence on the iostreamlib{}.

Each component description begins with the component's purpose, design, and some examples. Next, a detailed description follows that begins with different ways to use the component, as well as any traps and pitfalls associated with it. The description usually ends with a reference section, in which you can find the exact signature and definition of a component's classes and its functions.

How to Read this Book

This book is a mix of introductory user's guide and structured reference manual regarding the C++ Standard Library. The individual components of the C++ Standard Library are independent of each other, to some extent, so after reading Chapters 2 through 4 you could read the chapters that discuss the individual components in any order. Bear in mind,that Chapters 5 through 9 all describe the same component. To understand the other STL chapters, you should start with the introduction to the STL in chapter 5.

If you are a C++ programmer who wants to know, in general, the concepts and all parts of the library, you could simply read the book from the beginning to the end. However, you should skip the reference sections (which usually are named something like "...{} in detail}"). To program with certain components of the C++ Standard Library, the best way to find something is to use the index. I have tried to make the index very comprehensive to save you time when you are looking for something.

I can't explain all aspects at the same time, so you will find many cross references. It is always a problem to decide whether to follow them. If the cross reference refers to a section that will follow soon, take it as hint that I return to an aspect later. You should follow the cross reference only if you are searching for certain aspects or details and the cross reference seems to lead to details concerning your problem or its solution.

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's first comment line. You can find the files on the Internet at my Web site http://www.josuttis.com/libbook/.

State of the Art

While I was writing this book,the C++ standard was completed. Please bear in mind that some compilers might not yet confirm to it. This will most likely change in the near future. As a consequence, you might discover that not all things covered in this book work as described on your system,and you may have to change example programs to fit your specific environment. I can compile almost all example programs with version 2.8 or higher of the EGCS compiler, which is free for almost all platforms and available on the Internet (see http://egcs.cygnus.com/) and on several software CDs.

Example Code and Additional Information

You can access all example programs and acquire more informations about this book and the C++ Standard Library from my Web site at http://www.josuttis.com/libbook/. Please read the {\tt README} file for further details. Also, you can find a lot of additional information about this topic on the Internet. See Internet Resources on page 743 for details.

Feedback

I welcome your feedback (good and bad) on this book. I tried to prepare it carefully; however, I'm human, and at some time I have to stop writing and tweaking. So, you may find some errors, inconsistencies, or subjects that could be described better. Your feedback will give me the chance to improve later

editions. The best way to reach me is by Email: libbook@josuttis.

You can also reach me by phone, fax, or "snail" mail:
Nicolai M. Josuttis
Berggarten 9
D--38108
Braunschweig
Germany
Phone: +49 5309 5747
Fax: +49 5309 5774

Many thanks.



0201379260P04062001

Updates

Errata

Click below for Errata related to this title:
Errata

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020