(This page has no text content)
(This page has no text content)
Recent Deitel Textbooks https://deitel.com/chtp9https://deitel.com/pycds https://deitel.com/jhtp11EOV https://deitel.com/jhtp11LOV
(This page has no text content)
Content Management: Tracy Johnson Content Production: Bob Engelhardt, Abhijeet Gope, K Madhusudhan Product Marketing: Krista Clark Rights and Permissions: Anjali Singh Cover Designer: Paul Deitel, Harvey Deitel, Chuti Prasertsith Cover Art: Paul Deitel (produced using Andreas Müller’s open-source Python library word_cloud—https:// github.com/amueller/word_cloud) Please contact https://support.pearson.com/getsupport/s/ with any queries on this content. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantabi- lity, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improve- ments and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. Copyright © 2024 by Pearson Education, Inc. or its affiliates, 221 River Street, Hoboken, NJ 07030. All Rights Reserved. Manufactured in the United States of America. This publication is protected by copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmis- sion in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions department, please visit www.pearsoned.com/permissions/. Acknowledgments of third-party content appear on the appropriate page within the text. PEARSON and REVEL are exclusive trademarks owned by Pearson Education, Inc. or its affiliates in the U.S. and/ or other countries. Unless otherwise indicated herein, any third-party trademarks, logos, or icons that may appear in this work are the property of their respective owners, and any references to third-party trademarks, logos, icons, or other trade dress are for demonstrative or descriptive purposes only. Such references are not intended to imply any sponsorship, endorse- ment, authorization, or promotion of Pearson’s products by the owners of such marks, or any relationship between the owner and Pearson Education, Inc., or its affiliates, authors, licensees, or distributors. Deitel and the double-thumbs-up bug are registered trademarks of Deitel and Associates, Inc. Library of Congress Cataloging-in-Publication Data On file uPDF ISBN-10: 0-13-809242-7 ISBN-13: 978-0-13809242-9 ePub ISBN-10: 0-13-809236-2 ISBN-13: 978-0-13809236-8
In memory of Gordon Moore, co-founder of Intel and father of Moore’s Law: For a career devoted to improving people’s lives through technology, innovation, industry, entrepreneurship and philanthropy. Paul and Harvey Deitel
Pearson’s Commitment to Diversity, Equity, and Inclusion Pearson is dedicated to creating bias-free content that reflects the diversity, depth, and breadth of all learners’ lived experiences. We embrace the many dimensions of diversity, including but not limited to race, ethnicity, gender, sex, sexual orientation, socioeconomic status, ability, age, and religious or political beliefs. Education is a powerful force for equity and change in our world. It has the potential to deliver opportu- nities that improve lives and enable economic mobility. As we work with authors to create content for every product and service, we acknowledge our responsibility to demonstrate inclusivity and incorporate diverse scholarship so that everyone can achieve their potential through learning. As the world’s leading learning company, we have a duty to help drive change and live up to our purpose to help more people create a better life for themselves and to create a better world. Our ambition is to purposefully contribute to a world where: • Everyone has an equitable and lifelong opportunity to succeed through learning. • Our educational products and services are inclusive and represent the rich diversity of learners. • Our educational content accurately reflects the histories and lived experiences of the learners we serve. • Our educational content prompts deeper discussions with students and motivates them to ex- pand their own learning (and worldview). We are also committed to providing products that are fully accessible to all learners. As per Pearson’s guidelines for accessible educational Web media, we test and retest the capabilities of our products against the highest standards for every release, following the WCAG guidelines in developing new products for copyright year 2022 and beyond. You can learn more about Pearson’s commitment to accessibility at https://www.pearson.com/us/accessibility.html. While we work hard to present unbiased, fully accessible content, we want to hear from you about any concerns or needs with this Pearson product so that we can investigate and address them. • Please contact us with concerns about any potential bias at https://www.pearson.com/report- bias.html. • For accessibility-related issues, such as using assistive technology with Pearson products, alter- native text requests, or accessibility documentation, email the Pearson Disability Support team at disability.support@pearson.com.
Preface xxiii Before You Begin liii 1 Intro to Computers and C++ 1 1.1 Introduction 2 1.2 Hardware 4 1.2.1 Computer Organization 4 1.2.2 Moore’s Law, Multi-Core Processors and Concurrent Programming 7 1.3 Data Hierarchies 10 1.4 Machine Languages, Assembly Languages and High-Level Languages 13 1.5 Operating Systems 14 1.6 C and C++ 18 1.7 C++ Standard Library and Open-Source Libraries 19 1.8 Other Popular Programming Languages 21 1.9 Introduction to Object Orientation 23 1.10 Simplified View of a C++ Development Environment 25 1.11 Test-Driving a C++20 Application Various Ways 28 1.11.1 Compiling and Running on Windows with Visual Studio Community Edition 29 1.11.2 Compiling and Running with GNU C++ on Linux 32 1.11.3 Compiling and Running with g++ in the GCC Docker Container 34 1.11.4 Compiling and Running with clang++ in a Docker Container 36 1.11.5 Compiling and Running with Xcode on macOS 37 1.12 Internet, World Wide Web, the Cloud and IoT 41 1.12.1 The Internet: A Network of Networks 41 1.12.2 The World Wide Web: Making the Internet User-Friendly 42 1.12.3 The Cloud 42 1.12.4 The Internet of Things (IoT) 42 1.12.5 Edge Computing 43 1.12.6 Mashups 43 1.13 Metaverse 44 1.13.1 Virtual Reality (VR) 44 1.13.2 Augmented Reality (AR) 45 1.13.3 Mixed Reality 46 1.13.4 Blockchain 46 1.13.5 Bitcoin and Cryptocurrency 46 Contents
viii Contents 1.13.6 Ethereum 47 1.13.7 Non-Fungible Tokens (NFTs) 47 1.13.8 Web3 47 1.14 Software Development Technologies 48 1.15 How Big Is Big Data? 49 1.15.1 Big-Data Analytics 52 1.15.2 Data Science and Big Data Are Making a Difference: Use Cases 53 1.16 AI—at the Intersection of Computer Science and Data Science 54 1.16.1 Artificial Intelligence (AI) 54 1.16.2 Artificial General Intelligence (AGI) 55 1.16.3 Artificial Intelligence Milestones 55 1.16.4 Machine Learning 56 1.16.5 Deep Learning 56 1.16.6 Reinforcement Learning 57 1.16.7 Generative AI—ChatGPT and Dall-E 2 57 1.17 Wrap-Up 59 2 Intro to C++20 Programming 65 2.1 Introduction 66 2.2 First Program in C++: Displaying a Line of Text 66 2.3 Modifying Our First C++ Program 70 2.4 Another C++ Program: Adding Integers 71 2.5 Memory Concepts 75 2.6 Arithmetic 76 2.7 Decision Making: Equality and Relational Operators 79 2.8 Objects Natural Case Study:Creating and Using Objects of Standard-Library Class string 83 2.9 Wrap-Up 86 3 Algorithm Development and Control Statements: Part 1 93 3.1 Introduction 94 3.2 Algorithms 95 3.3 Pseudocode 95 3.4 Control Structures 96 3.4.1 Sequence Structure 97 3.4.2 Selection Statements 98 3.4.3 Iteration Statements 98 3.4.4 Summary of Control Statements 99 3.5 if Single-Selection Statement 100 3.6 if…else Double-Selection Statement 101 3.6.1 Nested if…else Statements 102 3.6.2 Blocks 104 3.6.3 Conditional Operator (?:) 104 3.7 while Iteration Statement 105
Contents ix 3.8 Formulating Algorithms: Counter-Controlled Iteration 107 3.8.1 Pseudocode Algorithm with Counter-Controlled Iteration 107 3.8.2 Implementing Counter-Controlled Iteration 108 3.8.3 Integer Division and Truncation 110 3.8.4 Arithmetic Overflow 110 3.8.5 Input Validation 110 3.9 Formulating Algorithms: Sentinel-Controlled Iteration 111 3.9.1 Top-Down, Stepwise Refinement: The Top and First Refinement 112 3.9.2 Proceeding to the Second Refinement 112 3.9.3 Implementing Sentinel-Controlled Iteration 114 3.9.4 Mixed-Type Expressions and Implicit Type Promotions 116 3.9.5 Formatting Floating-Point Numbers 117 3.10 Formulating Algorithms: Nested Control Statements 118 3.10.1 Problem Statement 118 3.10.2 Top-Down, Stepwise Refinement: Pseudocode Representation of the Top 119 3.10.3 Top-Down, Stepwise Refinement: First Refinement 119 3.10.4 Top-Down, Stepwise Refinement: Second Refinement 120 3.10.5 Complete Second Refinement of the Pseudocode 120 3.10.6 Implementing the Program 121 3.10.7 Preventing Narrowing Conversions with Braced Initialization 123 3.11 Compound Assignment Operators 125 3.12 Increment and Decrement Operators 125 3.13 Fundamental Types Are Not Portable 128 3.14 Objects Natural Case Study: Super-Sized Integers 129 3.15 Wrap-Up 134 4 Control Statements, Part 2 145 4.1 Introduction 146 4.2 Essentials of Counter-Controlled Iteration 146 4.3 for Iteration Statement 148 4.4 Examples Using the for Statement 151 4.5 Application: Summing Even Integers; Introducing C++20 Text Formatting 152 4.6 Application: Compound-Interest Calculations; Introducing Format Specifiers 153 4.7 do…while Iteration Statement 158 4.8 switch Multiple-Selection Statement 159 4.9 Selection Statements with Initializers 165 4.10 break and continue Statements 167 4.11 Logical Operators 169 4.11.1 Logical AND (&&) Operator 169 4.11.2 Logical OR (||) Operator 170 4.11.3 Short-Circuit Evaluation 170 4.11.4 Logical Negation (!) Operator 171 4.11.5 Example: Producing Logical-Operator Truth Tables 171
x Contents 4.12 Confusing the Equality (==) and Assignment (=) Operators 173 4.13 Structured-Programming Summary 175 4.14 Objects Natural Case Study: Precise Monetary Calculations with the Boost Multiprecision Library 180 4.15 Wrap-Up 183 5 Functions and an Intro to Function Templates 189 5.1 Introduction 190 5.2 C++ Program Components 191 5.3 Math Library Functions 192 5.4 Function Definitions and Function Prototypes 194 5.5 Order of Evaluation of a Function’s Arguments 197 5.6 Function-Prototype and Argument-Coercion Notes 197 5.6.1 Function Signatures and Function Prototypes 198 5.6.2 Argument Coercion 198 5.6.3 Argument-Promotion Rules and Implicit Conversions 198 5.7 C++ Standard Library Headers 200 5.8 Case Study: Random-Number Generation 203 5.8.1 Rolling a Six-Sided Die 204 5.8.2 Rolling a Six-Sided Die 60,000,000 Times 205 5.8.3 Seeding the Random-Number Generator 207 5.8.4 Seeding the Random-Number Generator with random_device 208 5.9 Case Study: Game of Chance; Introducing Scoped enums 209 5.10 Function-Call Stack and Activation Records 214 5.11 Inline Functions 217 5.12 References and Reference Parameters 219 5.13 Default Arguments 222 5.14 Function Overloading 224 5.15 Function Templates 227 5.16 Recursion 229 5.16.1 Factorials 230 5.16.2 Recursive Factorial Example 230 5.16.3 Recursive Fibonacci Series Example 234 5.16.4 Recursion vs. Iteration 237 5.17 Scope Rules 239 5.18 Unary Scope Resolution Operator 244 5.19 Lnfylun Lhqtomh Wjtz Qarcv: Qjwazkrplm xzz Xndmwwqhlz 245 5.20 Wrap-Up 248 6 arrays, vectors, Ranges and Functional-Style Programming 259 6.1 Introduction 260 6.2 arrays 261 6.3 Declaring arrays 262 6.4 Initializing array Elements in a Loop 262
Contents xi 6.5 Initializing an array with an Initializer List 265 6.6 Range-Based for Statement 267 6.7 Calculating array Element Values and an Intro to constexpr 269 6.8 Totaling array Elements 271 6.9 Using a Primitive Bar Chart to Display array Data Graphically 272 6.10 Using array Elements as Counters 274 6.11 Using arrays to Summarize Survey Results 275 6.12 Sorting and Searching arrays 277 6.13 Multidimensional arrays 279 6.14 Intro to Functional-Style Programming 283 6.14.1 What vs. How 283 6.14.2 Passing Functions as Arguments to Other Functions: Introducing Lambda Expressions 284 6.14.3 Filter, Map and Reduce: Intro to C++20’s Ranges Library 286 6.15 Objects-Natural Case Study: C++ Standard Library Class Template vector 290 6.16 Wrap-Up 297 7 (Downplaying) Pointers in Modern C++ 309 7.1 Introduction 310 7.2 Pointer Variable Declarations and Initialization 312 7.2.1 Declaring Pointers 312 7.2.2 Initializing Pointers 312 7.2.3 Null Pointers 312 7.3 Pointer Operators 313 7.3.1 Address (&) Operator 313 7.3.2 Indirection (*) Operator 314 7.3.3 Using the Address (&) and Indirection (*) Operators 315 7.4 Pass-by-Reference with Pointers 316 7.5 Built-In Arrays 320 7.5.1 Declaring and Accessing a Built-In Array 320 7.5.2 Initializing Built-In Arrays 321 7.5.3 Passing Built-In Arrays to Functions 322 7.5.4 Declaring Built-In Array Parameters 322 7.5.5 Standard Library Functions begin and end 323 7.5.6 Built-In Array Limitations 323 7.6 Using C++20 to_array to Convert a Built-in Array to a std::array 324 7.7 Using const with Pointers and the Data Pointed To 325 7.7.1 Using a Nonconstant Pointer to Nonconstant Data 326 7.7.2 Using a Nonconstant Pointer to Constant Data 326 7.7.3 Using a Constant Pointer to Nonconstant Data 327 7.7.4 Using a Constant Pointer to Constant Data 327 7.8 sizeof Operator 329 7.9 Pointer Expressions and Pointer Arithmetic 331 7.9.1 Adding Integers to and Subtracting Integers from Pointers 332
xii Contents 7.9.2 Subtracting One Pointer from Another 333 7.9.3 Pointer Assignment 333 7.9.4 Cannot Dereference a void* Pointer 333 7.9.5 Comparing Pointers 334 7.10 Objects-Natural Case Study: C++20 spans—Views of Contiguous Container Elements 334 7.11 A Brief Intro to Pointer-Based Strings 340 7.11.1 Command-Line Arguments 341 7.11.2 Revisiting C++20’s to_array Function 342 7.12 Looking Ahead to Other Pointer Topics 344 7.13 Wrap-Up 344 8 strings, string_views, Text Files, CSV Files and Regex 357 8.1 Introduction 358 8.2 string Assignment and Concatenation 359 8.3 Comparing strings 361 8.4 Substrings 363 8.5 Swapping strings 364 8.6 string Characteristics 365 8.7 Finding Substrings and Characters in a string 367 8.8 Replacing and Erasing Characters in a string 370 8.9 Inserting Characters into a string 372 8.10 Numeric Conversions 373 8.11 string_view 374 8.12 Files and Streams 377 8.13 Creating a Sequential File 378 8.14 Reading Data from a Sequential File 381 8.15 Reading and Writing Quoted Text 384 8.16 Updating Sequential Files 385 8.17 String Stream Processing 386 8.18 Raw String Literals 389 8.19 Objects-Natural Data Science Case Study: Reading and Analyzing a CSV File Containing Titanic Disaster Data 390 8.19.1 Using rapidcsv to Read the Contents of a CSV File 390 8.19.2 Reading and Analyzing the Titanic Disaster Dataset 392 8.20 Objects-Natural Data Science Case Study: Intro to Regular Expressions 399 8.20.1 Matching Complete Strings to Patterns 400 8.20.2 Replacing Substrings 405 8.20.3 Searching for Matches 405 8.21 Wrap-Up 408 9 Custom Classes 431 9.1 Introduction 432
Contents xiii 9.2 Test-Driving an Account Object 433 9.3 Account Class with a Data Member and Set and Get Member Functions 435 9.3.1 Class Definition 435 9.3.2 Access Specifiers private and public 437 9.4 Account Class: Custom Constructors 438 9.5 Software Engineering with Set and Get Member Functions 442 9.6 Account Class with a Balance 444 9.7 Time Class Case Study: Separating Interface from Implementation 447 9.7.1 Interface of a Class 448 9.7.2 Separating the Interface from the Implementation 448 9.7.3 Class Definition 449 9.7.4 Member Functions 450 9.7.5 Including the Class Header in the Source-Code File 450 9.7.6 Scope Resolution Operator (::) 451 9.7.7 Member Function setTime and Throwing Exceptions 451 9.7.8 Member Functions to24HourString and to12HourString 451 9.7.9 Implicitly Inlining Member Functions 452 9.7.10 Member Functions vs. Global Functions 452 9.7.11 Using Class Time 452 9.7.12 Object Size 454 9.8 Compilation and Linking Process 454 9.9 Class Scope and Accessing Class Members 455 9.10 Access Functions and Utility Functions 456 9.11 Time Class Case Study: Constructors with Default Arguments 457 9.11.1 Class Time 457 9.11.2 Overloaded Constructors and Delegating Constructors 462 9.12 Destructors 463 9.13 When Constructors and Destructors Are Called 464 9.14 Time Class Case Study: A Subtle Trap — Returning a Reference or a Pointer to a private Data Member 468 9.15 Default Assignment Operator 470 9.16 const Objects and const Member Functions 472 9.17 Composition: Objects as Members of Classes 474 9.18 friend Functions and friend Classes 480 9.19 The this Pointer 482 9.19.1 Implicitly and Explicitly Using the this Pointer to Access an Object’s Data Members 482 9.19.2 Using the this Pointer to Enable Cascaded Function Calls 484 9.20 static Class Members: Classwide Data and Member Functions 487 9.21 Aggregates in C++20 492 9.21.1 Initializing an Aggregate 493 9.21.2 C++20 Designated Initializers 493 9.22 Concluding Our Objects Natural Case Study Track: Studying the Vigenère Secret-Key Cipher Implementation 494 9.23 Wrap-Up 507
xiv Contents 10 OOP: Inheritance and Runtime Polymorphism 529 10.1 Introduction 530 10.2 Base Classes and Derived Classes 532 10.2.1 CommunityMember Class Hierarchy 533 10.2.2 Shape Class Hierarchy and public Inheritance 534 10.3 Relationship Between Base and Derived Classes 535 10.3.1 Creating and Using a SalariedEmployee Class 535 10.3.2 Creating a SalariedEmployee–SalariedCommissionEmployee Inheritance Hierarchy 538 10.4 Constructors and Destructors in Derived Classes 544 10.5 Intro to Runtime Polymorphism: Polymorphic Video Game 545 10.6 Relationships Among Objects in an Inheritance Hierarchy 546 10.6.1 Invoking Base-Class Functions from Derived-Class Objects 547 10.6.2 Aiming Derived-Class Pointers at Base-Class Objects 549 10.6.3 Derived-Class Member-Function Calls via Base-Class Pointers 550 10.7 Virtual Functions and Virtual Destructors 551 10.7.1 Why virtual Functions Are Useful 551 10.7.2 Declaring virtual Functions 552 10.7.3 Invoking a virtual Function 553 10.7.4 virtual Functions in the SalariedEmployee Hierarchy 553 10.7.5 virtual Destructors 557 10.7.6 final Member Functions and Classes 557 10.8 Abstract Classes and Pure virtual Functions 558 10.8.1 Pure virtual Functions 559 10.8.2 Device Drivers: Polymorphism in Operating Systems 559 10.9 Case Study: Payroll System Using Runtime Polymorphism 560 10.9.1 Creating Abstract Base Class Employee 561 10.9.2 Creating Concrete Derived Class SalariedEmployee 563 10.9.3 Creating Concrete Derived Class CommissionEmployee 565 10.9.4 Demonstrating Runtime Polymorphic Processing 567 10.10 Runtime Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood” 570 10.11 Program to an Interface, Not an Implementation 573 10.11.1 Rethinking the Employee Hierarchy— CompensationModel Interface 575 10.11.2 Class Employee 575 10.11.3 CompensationModel Implementations 577 10.11.4 Testing the New Hierarchy 579 10.11.5 Dependency Injection Design Benefits 580 10.12 Wrap-Up 581 11 Operator Overloading, Copy/Move Semantics and Smart Pointers 587 11.1 Introduction 588 11.2 Using the Overloaded Operators of Standard Library Class string 590
Contents xv 11.3 Operator Overloading Fundamentals 596 11.3.1 Operator Overloading Is Not Automatic 596 11.3.2 Operators That Cannot Be Overloaded 596 11.3.3 Operators That You Do Not Have to Overload 596 11.3.4 Rules and Restrictions on Operator Overloading 597 11.4 (Downplaying) Dynamic Memory Management with new and delete 598 11.5 Modern C++ Dynamic Memory Management: RAII and Smart Pointers 600 11.5.1 Smart Pointers 601 11.5.2 Demonstrating unique_ptr 601 11.5.3 unique_ptr Ownership 603 11.5.4 unique_ptr to a Built-In Array 603 11.6 MyArray Case Study: Crafting a Valuable Class with Operator Overloading 604 11.6.1 Special Member Functions 605 11.6.2 Using Class MyArray 606 11.6.3 MyArray Class Definition 615 11.6.4 Constructor That Specifies a MyArray’s Size 617 11.6.5 Passing a Braced Initializer to a Constructor 618 11.6.6 Copy Constructor and Copy Assignment Operator 619 11.6.7 Move Constructor and Move Assignment Operator 622 11.6.8 Destructor 626 11.6.9 toString and size Functions 626 11.6.10 Overloading the Equality (==) and Inequality (!=) Operators 627 11.6.11 Overloading the Subscript ([]) Operator 629 11.6.12 Overloading the Unary bool Conversion Operator 630 11.6.13 Overloading the Preincrement Operator 631 11.6.14 Overloading the Postincrement Operator 632 11.6.15 Overloading the Addition Assignment Operator (+=) 633 11.6.16 Overloading the Binary Stream Extraction (>>) and Stream Insertion (<<) Operators 633 11.6.17 friend Function swap 636 11.7 C++20 Three-Way Comparison Operator (<=>) 636 11.8 Converting Between Types 640 11.9 explicit Constructors and Conversion Operators 641 11.10 Overloading the Function Call Operator () 644 11.11 Wrap-Up 644 12 Exceptions and a Look Forward to Contracts 653 12.1 Introduction 654 12.2 Exception-Handling Flow of Control 658 12.2.1 Defining a Custom Exception Class 658 12.2.2 Demonstrating Exception Handling 659 12.2.3 Enclosing Code in a try Block 660 12.2.4 Defining a catch Handler for DivideByZeroExceptions 661 12.2.5 Termination Model of Exception Handling 662 12.2.6 Flow of Control When the User Enters a Nonzero Denominator 663 12.2.7 Flow of Control When the User Enters a Zero Denominator 663
xvi Contents 12.3 Exception Safety Guarantees and noexcept 664 12.4 Rethrowing an Exception 665 12.5 Stack Unwinding and Uncaught Exceptions 667 12.6 When to Use Exception Handling 669 12.6.1 assert Macro 671 12.6.2 Failing Fast 671 12.7 Constructors, Destructors and Exception Handling 672 12.7.1 Throwing Exceptions from Constructors 672 12.7.2 Catching Exceptions in Constructors via Function try Blocks 673 12.7.3 Exceptions and Destructors: Revisiting noexcept(false) 675 12.8 Processing new Failures 676 12.8.1 new Throwing bad_alloc on Failure 677 12.8.2 new Returning nullptr on Failure 678 12.8.3 Handling new Failures Using Function set_new_handler 679 12.9 Standard Library Exception Hierarchy 680 12.10 C++’s Alternative to the finally Block: Resource Acquisition Is Initialization (RAII) 683 12.11 Some Libraries Support Both Exceptions and Error Codes 683 12.12 Logging 685 12.13 Looking Ahead to Contracts 685 12.14 Wrap-Up 694 13 Data Structures: Standard Library Containers and Iterators 697 13.1 Introduction 698 13.2 A Brief Intro to Big O 700 13.3 A Brief Intro to Hash Tables 703 13.4 Introduction to Containers 704 13.4.1 Common Nested Types in Sequence and Associative Containers 706 13.4.2 Common Container Member and Non-Member Functions 707 13.4.3 Requirements for Container Elements 710 13.5 Working with Iterators 710 13.5.1 Using istream_iterator for Input and ostream_iterator for Output 710 13.5.2 Iterator Categories 712 13.5.3 Container Support for Iterators 712 13.5.4 Predefined Iterator Type Names 713 13.5.5 Iterator Operators 713 13.6 A Brief Introduction to Algorithms 714 13.7 Sequence Containers 715 13.8 vector Sequence Container 715 13.8.1 Using vectors and Iterators 716 13.8.2 vector Element-Manipulation Functions 719 13.9 list Sequence Container 723 13.10 deque Sequence Container 728
Contents xvii 13.11 Associative Containers 730 13.11.1 multiset Associative Container 730 13.11.2 set Associative Container 734 13.11.3 multimap Associative Container 736 13.11.4 map Associative Container 738 13.12 Container Adaptors 739 13.12.1 stack Adaptor 740 13.12.2 queue Adaptor 742 13.12.3 priority_queue Adaptor 743 13.13 bitset Near Container 744 13.14 Wrap-Up 746 14 Standard Library Algorithms and C++20 Ranges & Views 773 14.1 Introduction 774 14.2 Algorithm Requirements: C++20 Concepts 776 14.3 Lambdas and Algorithms 778 14.4 Algorithms 781 14.4.1 fill, fill_n, generate and generate_n 781 14.4.2 equal, mismatch and lexicographical_compare 783 14.4.3 remove, remove_if, remove_copy and remove_copy_if 786 14.4.4 replace, replace_if, replace_copy and replace_copy_if 790 14.4.5 Shuffling, Counting, and Minimum and Maximum Element Algorithms 792 14.4.6 Searching and Sorting Algorithms 796 14.4.7 swap, iter_swap and swap_ranges 800 14.4.8 copy_backward, merge, unique, reverse, copy_if and copy_n 802 14.4.9 inplace_merge, unique_copy and reverse_copy 805 14.4.10 Set Operations 807 14.4.11 lower_bound, upper_bound and equal_range 810 14.4.12 min, max and minmax 812 14.4.13 Algorithms gcd, lcm, iota, reduce and partial_sum from Header <numeric> 813 14.4.14 Heapsort and Priority Queues 816 14.5 Function Objects (Functors) 821 14.6 Projections 825 14.7 C++20 Views and Functional-Style Programming 828 14.7.1 Range Adaptors 828 14.7.2 Working with Range Adaptors and Views 830 14.8 Intro to Parallel Algorithms 834 14.9 Standard Library Algorithm Summary 836 14.10 Future Ranges Enhancements 839 14.11 Wrap-Up 840
xviii Contents 15 Templates, C++20 Concepts and Metaprogramming 845 15.1 Introduction 846 15.2 Custom Class Templates and Compile-Time Polymorphism 849 15.3 C++20 Function Template Enhancements 854 15.3.1 C++20 Abbreviated Function Templates 854 15.3.2 C++20 Templated Lambdas 856 15.4 C++20 Concepts: A First Look 856 15.4.1 Unconstrained Function Template multiply 857 15.4.2 Constrained Function Template with a C++20 Concepts requires Clause 860 15.4.3 C++20 Predefined Concepts 862 15.5 Type Traits 864 15.6 C++20 Concepts: A Deeper Look 868 15.6.1 Creating a Custom Concept 868 15.6.2 Using a Concept 869 15.6.3 Using Concepts in Abbreviated Function Templates 870 15.6.4 Concept-Based Overloading 871 15.6.5 requires Expressions 874 15.6.6 C++20 Exposition-Only Concepts 877 15.6.7 Techniques Before C++20 Concepts: SFINAE and Tag Dispatch 878 15.7 Testing C++20 Concepts with static_assert 879 15.8 Creating a Custom Algorithm 881 15.9 Creating a Custom Container and Iterators 883 15.9.1 Class Template ConstIterator 885 15.9.2 Class Template Iterator 888 15.9.3 Class Template MyArray 890 15.9.4 MyArray Deduction Guide for Braced Initialization 893 15.9.5 Using MyArray with std::ranges Algorithms 894 15.10 Default Arguments for Template Type Parameters 898 15.11 Variable Templates 898 15.12 Variadic Templates and Fold Expressions 899 15.12.1 tuple Variadic Class Template 899 15.12.2 Variadic Function Templates and an Intro to Fold Expressions 902 15.12.3 Types of Fold Expressions 906 15.12.4 How Unary Fold Expressions Apply Their Operators 906 15.12.5 How Binary-Fold Expressions Apply Their Operators 909 15.12.6 Using the Comma Operator to Repeatedly Perform an Operation 910 15.12.7 Constraining Parameter Pack Elements to the Same Type 911 15.13 Template Metaprogramming 913 15.13.1 C++ Templates Are Turing Complete 914 15.13.2 Computing Values at Compile-Time 914 15.13.3 Conditional Compilation with Template Metaprogramming and constexpr if 919 15.13.4 Type Metafunctions 921 15.14 Wrap-Up 925
Contents xix 16 C++20 Modules: Large-Scale Development 933 16.1 Introduction 934 16.2 Compilation and Linking Before C++20 936 16.3 Advantages and Goals of Modules 937 16.4 Example: Transitioning to Modules—Header Units 938 16.5 Modules Can Reduce Translation Unit Sizes and Compilation Times 941 16.6 Example: Creating and Using a Module 942 16.6.1 module Declaration for a Module Interface Unit 943 16.6.2 Exporting a Declaration 945 16.6.3 Exporting a Group of Declarations 945 16.6.4 Exporting a namespace 945 16.6.5 Exporting a namespace Member 946 16.6.6 Importing a Module to Use Its Exported Declarations 946 16.6.7 Example: Attempting to Access Non-Exported Module Contents 948 16.7 Global Module Fragment 951 16.8 Separating Interface from Implementation 951 16.8.1 Example: Module Implementation Units 951 16.8.2 Example: Modularizing a Class 954 16.8.3 :private Module Fragment 958 16.9 Partitions 958 16.9.1 Example: Module Interface Partition Units 959 16.9.2 Module Implementation Partition Units 962 16.9.3 Example: “Submodules” vs. Partitions 962 16.10 Additional Modules Examples 967 16.10.1 Example: Importing the C++ Standard Library as Modules 967 16.10.2 Example: Cyclic Dependencies Are Not Allowed 969 16.10.3 Example: imports Are Not Transitive 970 16.10.4 Example: Visibility vs. Reachability 971 16.11 Migrating Code to Modules 972 16.12 Future of Modules and Modules Tooling 973 16.13 Wrap-Up 975 17 Parallel Algorithms and Concurrency: A High-Level View 987 17.1 Introduction 988 17.2 Standard Library Parallel Algorithms 991 17.2.1 Example: Profiling Sequential and Parallel Sorting Algorithms 991 17.2.2 When to Use Parallel Algorithms 994 17.2.3 Execution Policies 995 17.2.4 Example: Profiling Parallel and Vectorized Operations 996 17.2.5 Additional Parallel Algorithm Notes 998 17.3 Multithreaded Programming 999 17.3.1 Thread States and the Thread Life Cycle 999 17.3.2 Deadlock and Indefinite Postponement 1001
Comments 0
Loading comments...
Reply to Comment
Edit Comment