1. Trang chủ
  2. » Công Nghệ Thông Tin

Addison wesley c plus plus standard library the a tutorial and reference aug 1999 ISBN 0201824701

974 129 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 974
Dung lượng 3,96 MB

Nội dung

C++ Standard Library: A Tutorial and Reference, The By Nicolai M Josuttis Publisher : Addison Wesley Pub Date : August 06, 1999 ISBN : 0-201-37926-0 Pages : 832 C++ Standard Library provides a set of common classes and interfaces that greatly extend the core C++ language The library, however, is not selfexplanatory 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 Table of particular, the text focuses on the Standard Template • Contents 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 EEn 777 Copyright Preface Acknowledgments Chapter 1 About this Book 1.1 Why this Book 1.2 What You Should Know Before Reading this Book 1.3 Style and Structure of the Book 1.4 How to Read this Book 1.5 State of the Art 1.6 Example Code and Additional Information 1.7 Feedback Chapter 2 Introduction to C++ and the Standard Library 2.1 History 2.2 New Language Features 2.3 Complexity and the Big-O Notation Chapter 3 General Concepts 3.1 Namespace 3.2 Header Files 3.3 Error and Exception Handling 3.4 Allocators Chapter 4 Utilities 4.1 Pairs 4.1.1 Convenience Function 4.1.2 Examples of Pair Usage 4.2 Class 4.3 Numeric Limits 4.4 Auxiliary Functions 4.5 Supplementary Comparison Operators 4.6 Header Files Chapter 5 The Standard Template Library 5.1 STL Components 5.2 Containers 5.3 Iterators 5.4 Algorithms 5.5 Iterator Adapters 5.6 Manipulating Algorithms 5.7 User-Defined Generic Functions 5.8 Functions as Algorithm Arguments 5.9 Function Objects 5.10 Container Elements 5.11 Errors and Exceptions Inside the STL 5.12 Extending the STL Chapter 6 STL Containers 6.1 Common Container Abilities and Operations 6.2 Vectors 6.3 Deques 6.4 Lists 6.5 Sets and Multisets 6.6 Maps and Multimaps 6.7 Other STL Containers 6.8 Implementing Reference Semantics 6.9 When to Use which Container 6.10 Container Types and Members in Detail Chapter 7 STL Iterators 7.1 Header Files for Iterators 7.2 Iterator Categories 7.3 Auxiliary Iterator Functions 7.4 Iterator Adapters 7.5 Iterator Traits Chapter 8 STL Function Objects 8.1 The Concept of Function Objects 8.2 Predefined Function Objects 8.3 Supplementary Composing Function Objects Chapter 9 STL Algorithms 9.1 Algorithm Header Files 9.2 Algorithm Overview 9.3 Auxiliary Functions 9.4 The 9.5 Nonmodifying Algorithms 9.6 Modifying Algorithms 9.7 Removing Algorithms 9.8 Mutating Algorithms 9.9 Sorting Algorithms 9.10 Sorted Range Algorithms 9.11 Numeric Algorithms Chapter 10 Special Containers 10.1 Stacks 10.2 Queues 10.3 Priority Queues 10.4 Bitsets Chapter 11 Strings 11.1 Motivation 11.2 Description of the String Classes 11.3 String Class in Detail Chapter 12 Numerics 12.1 Complex Numbers 12.2 Valarrays 12.3 Global Numeric Functions Chapter 13 Input/Output Using Stream Classes 13.1 Common Background of I/O Streams 13.2 Fundamental Stream Classes and Objects 13.3 Standard Stream Operators > 13.4 State of Streams 13.5 Standard Input/Output Functions 13.6 Manipulators 13.7 Formatting 13.8 Internationalization 13.9 File Access 13.10 Connecting Input and Output Streams 13.11 Stream Classes for Strings 13.12 Input/Output Operators for User-Defined Types 13.13 The Stream Buffer Classes 13.14 Performance Issues Chapter 14 Internationalization 14.1 Different Character Encodings 14.2 The Concept of Locales 14.3 Locales in Detail 14.4 Facets in Detail Chapter 15 Allocators 15.1 Using Allocators as an Application Programmer 15.2 Using Allocators as a Library Programmer 15.3 The Default Allocator 15.4 A User-Defined Allocator 15.5 Allocators in Detail 15.6 Utilities for Uninitialized Memory in Detail Internet Resources Bibliography Copyright Many 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., was aware of a trademark claim, the designations have been printed in initial caps 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 assumed for 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 for special sales For more information, please contact: AWL Direct Sales Addison Wesley Longman, Inc One Jacob Way Reading, Massachusetts 01867 (781) 944-3700 Visit AW on the Web: www.awl.com/cseng/ Library of Congress Cataloging-in-Publication Data Josuttis, Nicolai M The C++ standard library: a tutorial and reference / Nicolai M Josuttis p cm Includes bibliographical references and index C++ (Computer program language) I Title QA76.73.C153J69 1999 005.13'3 dc21 99-24977 CIP Copyright © 1999 by Addison Wesley Longman, Inc All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher Printed in the United States of America Published simultaneously in Canada 1 2 3 4 5 6 7 8 9 -CRW- 0302010099 First printing, July 1999 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 every-day 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 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 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 fogive 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 Kühl, Edda Lörke, 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 Code Warrior 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 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! //return maximum number of elements that can size_type max_size () const throw() { //for numeric_limits see Section 4.3, pa return numeric_limits::max() / s } //allocate but don't initialize num elements pointer allocate (size_type num, allocator::const_poi //allocate memory with global new return (pointer) (::operator new(num*siz } //initialize elements of allocated storage void construct (pointer p, const T& value) { //initialize memory with placement new((void*)p)T(value); } //destroy elements of initialized storage void destroy (pointer p) { // destroy objects by calling their dest p->~T(); } //deallocate storage p of deleted elements void deallocate (pointer p, size_type num) { //deallocate memory with global delete ::operator delete((void*)p)); } }; //return that all specializations of this allocat template bool operator== (const allocator&, const allocator&) throw() { return true; } template bool operator!= (const allocator&, const allocator&) throw() { return false; } } Using this base implementation you should find it no problem to implement your own allocator Typically, the only things that differ from this implementation are max_size(), allocate(), and deallocate() In these three functions, you program your own policy of memory allocation, such as reusing memory instead of freeing it immediately, using shared memory, or mapping the memory to a segment of an object-oriented database 15.5 Allocators in Detail According to the specified requirements, allocators have to provide the following types and operations There are special requirements for allocators that can be used by the standard containers Allocators that are not provided for the standard containers may have less requirements 15.5.1 Type Definitions allocator::value_type The type of the elements It is equivalent to T for allocator allocator::size_type The type for unsigned integral values that can represent the size of the largest object in the allocation model To be usable by the standard containers, this type must be equivalent to size_t allocator::difference_type The type for signed integral values that can represent the difference between any two pointers in the allocation model To be usable by the standard containers, this type must be equivalent to ptrdiff_t allocator::pointer The type of a pointer to the element type To be usable by the standard containers, this type must be equivalent to T* for allocator allocator::const_pointer The type of a constant pointer to the element type To be usable by the standard containers, this type must be equivalent to const T* for allocator allocator::reference The type of a reference to the element type It is equivalent to T& for allocator allocator::const_reference The type of a constant reference to the element type It is equivalent to const T& for allocator allocator::rebind A template structure that provides the ability that any allocator may allocate storage of another type indirectly It has to be declared as follows: template class allocator { public: template struct rebind { typedef allocator other; }; } See page 734 for an explanation of the purpose of rebind 15.5.2 Operations allocator::allocator () The default constructor Creates an allocator object allocator::allocator (const allocator& a) The copy constructor Copies an allocator object so that storage allocated from the original and from the copy can be deallocated via the other allocator::~allocator () The destructor Destroys an allocator object pointer allocator::address (reference value) const_pointer allocator::address (const_reference value) The first form returns a nonconstant pointer to the nonconstant value The second form returns a constant pointer to the constant value size_type allocator::max_size () Returns the largest value that can be passed meaningfully to allocate() to allocate storage pointer allocator::allocate (size_type num) pointer allocator::allocate (size_type num, allocator::const_pointer hint) Both forms return storage for num elements of type T The elements are not constructed/initialized (no constructors are called) The optional second argument has an implementation-specific meaning For example, it may be used by an implementation to help improve performance void allocator::deallocate (pointer p, size_type num) Frees the storage to which p refers The storage of p has to be allocated by allocate() of the same or an equal allocator p must not be NULL or 0 The elements have to have been destroyed already void allocator::construct (pointer p, const T& value) Initializes the storage of one element to which p refers with value It is equivalent to new((void*)p)T(value) void allocator::destroy (pointer p) Destroys the object to which p refers without deallocating the storage Simply calls the destructor for the object It is equivalent to ((T*)p)->T() bool operator == (const allocator& a1, const allocator& a2) Returns true if allocators a1 and a2 are interchangeable Two allocators are interchangeable if storage allocated from each can be deallocated via the other To be usable by the standard containers, allocators of the same type are required to be interchangeable So, this function should always return true bool operator != (const allocator& a1, const allocator& a2) Returns true if two allocators are not interchangeable It is equivalent to ! (a1 == a2) To be usable by the standard containers, allocators of the same type are required to be interchangeable So, this function should always return false 15.6 Utilities for Uninitialized Memory in Detail This section describes the auxiliary functions for uninitialized memory in detail The exemplary exception safe implementation of these functions is based with permission on code by Greg Colvin void uninitialized_fill (ForwardIterator beg, ForwardIt const T& value) Initializes the elements in the range [beg,end) with value This function either succeeds or has no effect This function usually is implemented as follows: namespace std { template void uninitialized_fill(ForwIter beg, ForwIter const T& value) { typedef typename iterator_traits: ForwIter save(beg); try { for (; beg!=end; ++beg) { new (static_cast(&*beg))VT(val } } catch ( ) { for (; save!=beg; ++save) { save->~VT(); } throw; } } } void uninitialized_fill_n (ForwardIterator beg, Size num, const T& value) initializes num elements starting from beg with value This function either succeeds or has no effect This function usually is implemented as follows: namespace std { template void uninitialized_fill_n (ForwIter beg, Size num, const T& value) { typedef typename iterator_traits::value_type VT; ForwIter save(beg); try { for (; num ; ++beg) { new (static_cast(&*beg))VT(value); } } catch ( ) { for (; save!=beg; ++save) { save->~VT(); } throw; } } } See page 730 for an example of the use of uninitialized_fill_n() ForwardIterator uninitialized_copy (InputIterator InputIterator ForwardIterator Initializes the memory starting at destBeg with the elements in the range [sourceBeg,sourceEnd) The function either succeeds or has no effect The function usually is implemented as follows: namespace std { template ForwIter uninitialized_copy(lnputIter beg, InputIter end, ForwIter dest) { typedef typename iterator_traits::value_type VT; ForwIter save(dest); try { for (; beg!=end; ++beg,++dest) { new (static_cast(&*dest))VT(*beg); } return dest; } catch ( ) { for (; save!=dest; ++save) { save->~VT(); } throw; } } } See page 730 for an example of the use of uninitialized_copy() CONTENTS CONTENTS Internet Resources The Internet is a huge source of information regarding the topic of this book Here is a list of my recommendations of sites where you could find additional, relevant information Where You Can Get the Standard The American National Standards Institute (ANSI) sells the C++ standard in the United States At the time this book was written, you could get the C++ standard at the Electronics Standard Store of ANSI for $18 (US) at the following site: http://www.ansi.org/ Newsgroups The following newsgroups discuss C++, the standard, and the C++ standard library: General aspects of C++ (unmoderated) comp.lang.c++ General aspects of C++ (moderated) comp.lang.c++.moderated Aspects of the C++ standard (moderated) comp.std.c++ For more information about this newsgroup see http://reality.sgi.com/austern/std-c++/faq.html Internet Addresses/URLs This section lists links that provide additional related informations regarding the C++ standard library and the STL However, books might have a longer life than Internet sites, and the links listed here may be not valid in the future Therefore, I will provide the actual list of links for this book at the following site (and I expect my site to be stable): http://www.josuttis.com/1ibbook/ The following links refer to issues of the whole C++ standard library: FAQs (frequently asked questions) about the standardization of C++: http://reality.sgi.com/austern/std-c++/faq.html The official home page of ISO working group for the standardization of C++ http://www.dkuug.dk/jtc1/sc22/wg21/ The Dinkum C++ Library Reference http://www.dinkumware.com/refxcpp.html The C++ standard library implementation for the EGCS C++ compiler http://sourceware.cygnus.com/1ibstdc++/ The EGCS C++ compiler http://egcs.cygnus.com/ The Boost repository for free, peer-reviewed C++ libraries http://www.boost.org/ Blitz++, a C++ class library for scientific computing http://www.oonumerics.org/blitz/ The following links refer to issues of the STL: The freely available STL implementation by SGI http://www.sgi.com/Technology/STL/ STLport for several platforms http://www.stlport.org/ Mumit's STL Newbie Guide http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html David Musser's STL site http://www.cs.rpi.edu/~musser/stl.html STL FAQs ftp://butler.hpl.hp.com/stl/stl.faq Safe STL by Cay Horstmann http://www.horstmann.com/safestl.html Warren Young's STL Resource List http://www.cyberport.com/~tangent/programming/stl/resources.html CONTENTS CONTENTS Bibliography The following bibliography lists the books and sources that were mentioned, adopted, or cited in this book and lists books that give additional details Note that this is not a comprehensive list of books It is my personal list of books regarding this topic Matthew H Austern Generic Programming and the STL Using and Extending the C++ Standard Template Library Addison-Wesley, Reading, MA, 1998 Ulrich Breymann Komponenten entwerfen mit der STL Addison-Wesley, Bonn, Germany, 1999 Bernd Eggink Die C++ iostreams–Library Hanser Verlag, München, Germany, 1995 Margaret A Ellis, Bjarne Stroustrup The Annotated C++ Reference Manual (ARM) Addison-Wesley, Reading, MA, 1990 Graham Glass, Brett Schuchert The STL Prentice-Hall, Englewood Cliffs, NJ, 1996 ISO Information Technology — Programming Languages — C++ Document Number ISO/IEC 14882-1998 ISO/IEC, 1998 Scott Meyers More Effective C++ 35 New Ways to Improve Your Programs and Designs Addison-Wesley, Reading, MA, 1996 David R Musser, Atul Saini STL Tutorial and Reference Guide C++ Programming with the Standard Template Library Addison-Wesley, Reading, MA, 1996 Mark Nelson C++ Programmer's Guide to the Standard Template Library IDG Books Worldwide, Foster City, CA, 1995 ObjectSpace Systems UNIX Reference Manual ObjectSpace, 1995 P.J Plauger The Draft Standard C++ Library Prentice Hall, Englewood Cliffs, NJ, 1995 Bjarne Stroustrup The C++ Programming Language, 3rd edition AddisonWesley, Reading, MA, 1997 Bjarne Stroustrup The Design and Evolution of C++ Addison-Wesley, Reading, MA, 1994 Steve Teale C++ IOStreams Handbook Addison-Wesley, Reading, MA, 1993 CONTENTS ... Chapters 10 through 12 describe "simple" individual standard classes: Chapter 10: Special Containers This chapter describes the different special container classes of the C+ + standard library It covers the container adapters for queues and stacks, as well as the class bitset, which manages a bitfield with... subject 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 for... platforms and available on the Internet (see http://egcs.cygnus.com/) and on several software CDs 1.6 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

Ngày đăng: 26/03/2019, 17:07

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN