Share E-Book

C++23 STL Cookbook Master the latest C++ STL features with practical recipes for modern C++ development (Bill Weinman)(Z-Library)

Author

Rating 4.0 AI initial rating

Log in to rate

C++
Language English

No Description

Format PDF
Size 2.7 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
C++ STL Cookbook Second Edition Master the latest STL features in C++23 and 26 with practical recipes for modern C++ development Bill Weinman
Page 3
C++ STL Cookbook Second Edition Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Kunal Chaudhari Relationship Lead: Denim Pinto Project Manager: K. Loganathan Content Engineer: Deepayan Bhattacharjee Technical Editor: Aditya Bharadwaj Copy Editor: Deepayan Bhattacharjee Indexer: Pratik Shirodkar Production Designer: Ajay Patule Growth Lead: Vinishka Kalra First published: May 2022 Second edition: May 2026 Production reference: 1260526 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-83620-425-1 www.packtpub.com
Page 4
Contributors About the author Bill Weinman built his first computer in 1972, using a 4-bit Intel microprocessor and parts from a local radio store. Over a 45+ year career, he has consulted for major corporations and government organizations, including NASA, IBM, Bank of America, the US Navy, and KWHY- TV, where he designed the world's first broadcast lower-third stock ticker. An early contributor to the original HTTP specification and the Apache web server project, since the late 1990s Mr. Weinman has written popular books and courseware on C, C++, Perl, Python, SQL, and more. His courses have consistently been ranked in the top 10 on lynda.com and LinkedIn Learning's training sites. This book represents the hard work of many talented people. Deep appreciation goes to Deepayan Bhattacharjee, K. Loganathan, Denim Pinto, and the wonderful staff at Packt. I am grateful for the support of my assistants, RiKi and Kurstin, who keep my life running smoothly as I focus on research and writing, and my family and friends, without whom none of this would make any sense at all.
Page 5
About the reviewer Desislav Andreev is experienced software engineer, lecturer, and a book author with a PhD in artificial intelligence systems and quantum machine learning. He has a demonstrated history of working in the automotive software engineering sector, virtualization, and in the area of the higher education. Desislav is also skilled in creating complex system and software architectures, designing core infrastructural solutions, and building systems for autonomous driving. He's interested in computer graphics, operating systems, supercomputers, systems engineering, and even simple software tools for everyday tasks. Being a strong professional he's currently working as a lead core infrastructure developer. He is an author of several publications in IEEE, respected journals and international scientific conferences. He's also an author of Packt's C++ Programming for Linux Systems. First, I'd like to thank Packt and Bill Weinman for this opportunity – it was an amazing experience, and it was quite thrilling for me to wait for each chapter! I also want to thank my great family for putting up with me and giving me enough time to do my side quests! My love goes to my wonderful wife – Svetla, my precious daughters – Kalina and Maria, and my sweet dog - Robyn.
Page 6
Table of Contents Preface xiii About this book ................................................................................................. xiii Prerequisite knowledge • xiii The STL's power is derived from templates (a brief primer) • xiv This book uses the C++23 standard • xv Hiding the std:: namespace • xv Type aliases with using • xvi Abbreviated function templates • xvi Use the STL to solve real-world problems • xvii Free benefits with your book ............................................................................. xxii Chapter 1: Introduction to New C++23 Features 1 Simplify your code with the std module ................................................................ 1 Format text with the new print() and println() functions ...................................... 4 Use synchronous generators ................................................................................. 5 Use mdspan as a multidimensional array .............................................................. 8 Initialize containers from ranges ......................................................................... 14 Find content in strings and ranges with contains() ............................................... 16 Subscribe to Deep Engineering ............................................................................ 21 Chapter 2: Best Practices 23 Use braced initialization ..................................................................................... 23 Use span to make C-arrays safer .......................................................................... 28 Use structured binding to return multiple values ................................................. 31 Initialize variables within if and switch conditionals ........................................... 35 Use template argument deduction for simplicity and clarity ................................ 38
Page 7
Use RAII to preserve memory integrity ................................................................ 42 Chapter 3: STL Containers 47 A quick overview of the STL container types ........................................................ 48 Sequential containers • 48 Associative containers • 48 Container adapters • 49 Use uniform erase functions to delete elements from a container ......................... 50 Delete items from an unsorted vector .................................................................. 55 Access vector elements safely .............................................................................. 58 Keep vector elements sorted ................................................................................ 61 Efficiently insert elements into a map ................................................................. 64 Efficiently modify keys in a map .......................................................................... 70 Use unordered_map with custom keys ................................................................ 74 Sort and filter user input with set ....................................................................... 77 Create a simple RPN calculator with deque ......................................................... 80 Count word frequency with map ......................................................................... 87 Find long sentences with a vector of vectors ........................................................ 92 Create an efficient ToDo list using multimap ....................................................... 95 Subscribe to Deep Engineering ........................................................................... 98 Chapter 4: STL Compatible Iterators 99 Iterators are fundamental ................................................................................... 99 Iterator categories • 102 Iterator concepts • 102 Create an iterable range ..................................................................................... 105 Use traits with your iterators for STL compatibility ........................................... 109 Use iterator adaptors to populate STL containers ................................................ 112 Iterate backward with a reverse adaptor ............................................................ 116 Iterate objects of unknown length with a sentinel ............................................. 120 Create a generator with iterators ....................................................................... 123 Create a generator with coroutines .................................................................... 128 Table of Contents vi
Page 8
Build a zip iterator adaptor ................................................................................ 136 Create a random-access iterator ......................................................................... 143 Operator overloads • 145 Validation code • 146 Chapter 5: Lambda Expressions 151 Lambda expressions .......................................................................................... 151 Closures • 152 Use lambdas for scoped, reusable code ............................................................... 153 Capture list • 157 Parameters • 158 The mutable modifier (optional) • 158 The constexpr specifier (optional) • 159 The noexcept attribute (optional) • 159 The trailing return type (optional) • 159 Use lambdas as predicates with algorithms ....................................................... 160 Create a polymorphic wrapper with std::function .............................................. 164 Concatenate lambdas with recursion ................................................................ 168 Combine predicates with logical conjunction ..................................................... 170 Pass common parameters to multiple lambdas ................................................... 171 Create a simple jump table with mapped lambdas .............................................. 173 Subscribe to Deep Engineering .......................................................................... 177 Chapter 6: STL Algorithms 179 Copy from one iterator to another ..................................................................... 180 Join container elements into a string ................................................................. 184 Sort containers with std::sort ........................................................................... 188 Modify containers with std::transform ............................................................... 194 Search containers with std::find ........................................................................ 197 The new contains() method • 201 Limit container values with std::clamp ............................................................. 202 Sample data sets with std::sample .................................................................... 205 vii Table of Contents
Page 9
Use ranges for more powerful algorithms .......................................................... 208 Generate permutations of data sequences .......................................................... 214 Merge sorted containers .................................................................................... 217 Chapter 7: Strings and Formatting 221 Use string_view as a lightweight string object ................................................... 223 Format text with the format library .................................................................. 228 Print strings with std::print and std::println ..................................................... 234 Concatenate strings .......................................................................................... 238 Benchmarks • 240 Why the performance discrepancy? • 243 Why would I choose one over another? • 244 Transform strings ............................................................................................. 244 Trim whitespace from strings ........................................................................... 248 Read strings from user input ............................................................................. 250 Count words in a file ......................................................................................... 254 Initialize complex structures from file input ....................................................... 255 Customize a string class with char_traits .......................................................... 259 Parse strings with regular expressions .............................................................. 263 Subscribe to Deep Engineering ......................................................................... 266 Chapter 8: Utility Classes 267 Manage optional values with std::optional ........................................................ 267 Use std::any for type safety ............................................................................... 272 Store different types with std::variant ............................................................... 276 Differences from the union primitive • 276 Time events with std::chrono ............................................................................ 282 The clock classes • 287 std::duration class • 287 Use fold expressions for generic tuples .............................................................. 288 Fold expressions • 288 Manage allocated memory with std::unique_ptr ............................................... 292 Table of Contents viii
Page 10
Share objects with std::shared_ptr .................................................................... 299 Use weak pointers with shared objects .............................................................. 303 Share object members with aliased smart pointers ............................................ 308 Compare random number engines ..................................................................... 310 Comparison of random number distribution generators ..................................... 314 Chapter 9: Concurrency and Parallelism 319 Sleep a process for a specific amount of time ..................................................... 320 There's more… • 321 Use std::thread for concurrency ......................................................................... 321 There's more… • 326 Use std::async for concurrency .......................................................................... 328 Simplify promise and future with std::async() • 333 Run STL algorithms in parallel with execution policies ...................................... 334 Use mutex and lock to safely share data .............................................................. 337 There's more… • 345 Share flags and values with std::atomic ............................................................. 345 Specializations • 348 Pointers and smart pointers • 348 Floating-point types • 349 Integral types • 349 Standard aliases • 349 Lock-free variations • 350 There's more… • 351 Initialize threads with std::call_once ................................................................. 352 Resolve the producer-consumer problem with std::condition_variable .............. 354 Implement multiple producers and consumers ................................................. 358 Suspend and resume execution with coroutines ................................................ 363 Use coroutines for a producer-consumer solution ............................................. 370 Subscribe to Deep Engineering .......................................................................... 375 ix Table of Contents
Page 11
Chapter 10: Using the File System 377 Specialize std::formatter for the path class ........................................................ 378 Use manipulation functions with path .............................................................. 382 List files in a directory ...................................................................................... 386 Search directories and files with a grep utility ................................................... 397 Rename files with regex and directory_iterator ................................................. 403 Create a disk usage counter ............................................................................... 408 Chapter 11: More Practical Ideas 415 Create a trie class for search suggestions ............................................................ 415 Calculate the error sum of two vectors .............................................................. 423 There's more… • 427 Build your own algorithm: split ........................................................................ 427 There's more… • 432 Leverage existing algorithms: gather ................................................................ 433 Remove consecutive whitespace ....................................................................... 436 Convert numbers to words ................................................................................ 438 There's more… • 446 Subscribe to Deep Engineering ......................................................................... 447 Chapter 12: C++26 and the Future 449 Static reflection ................................................................................................ 449 Contracts .......................................................................................................... 451 Structural pattern matching ............................................................................. 452 Other C++26 improvements .............................................................................. 453 Chapter 13: Unlock Your Exclusive Benefits 455 Unlock this Book's Free Benefits in 3 Easy Steps ................................................. 456 Table of Contents x
Page 12
Other Books You May Enjoy 461 Index 465 xi Table of Contents
Page 13
(This page has no text content)
Page 14
Preface About this book The C++ STL Cookbook provides recipes to help you get the most out of the C++ STL (Standard Template Library), including new features introduced with C++23. C++ is a rich and powerful language. Built upon C, with extensions for type safety, generic and object-oriented programming, C++ is essentially a low-level language. The STL provides a broad set of higher-level classes, functions, and algorithms to make your programming job easier, more effective, and less prone to error. I view C++ as five languages cobbled together. The formal specification includes 1) the entire C language, 2) C's cryptic-yet-powerful macro preprocessor, 3) a feature-rich class/object model, 4) a generic programming model called Templates, and finally, built upon C++ classes and templates, 5) the Standard Template Library (STL). Prerequisite knowledge This book presumes that you have a basic understanding of C++, including syntax, structure, data types, classes and objects, templates, and the STL. The recipes and examples in this book presume that you understand the need to #include certain headers to use library functions. The recipes don't usually list all the necessary headers, preferring to focus on the techniques at hand. You're encouraged to download the example code, which has all the necessary #include directives and other relevant front matter. You may download the example code from GitHub: https://github.com/PacktPublishing/ CPP-STL-Cookbook-Second-Edition. These assumptions mean that when you see a piece of code like this: println("hello, world"); You should already know that you'll need to put this code in a main() function, you'll need to #include the <print> header, and print is a function in the std:: namespace: #include <print> int main() {
Page 15
std::println("hello, world"); } The STL's power is derived from templates (a brief primer) Templates are how C++ does generic programming, code that's independent of type while retaining type safety. C++ templates allow you to use tokens as placeholders for types and classes, like this: template<typename T> T add_em_up(T& lhs, T& rhs) { return lhs + rhs; } A template may be used for both classes and functions. In this template function, T represents a generic type, which allows the function to be used in the context of any compatible class or type: int a {72}; // see braced initialization below int b {47}; print("{}\n" , add_em_up<int>(a, b)); // see print() below This invokes the template function with an int type. This same code can be used with any type or class that supports the + operator. When the compiler sees a template invocation, like add_em_up<int>(a, b), it creates a specialization. This is what makes the code type safe. When you invoke add_em_up() with an int type, the specialization will look something like this: int add_em_up(int& lhs, int& rhs) { return lhs + rhs; } The specialization takes the template and replaces all instances of the T placeholder with the type from the invocation, in this case, int. The compiler creates a separate specialization of the template each time it's invoked with a different type. The specialization happens at compile time and is otherwise invisible to the author of the code. STL containers, like vector, stack, or map, along with their iterators and other supporting functions and algorithms, are built with templates so they may be used generically while maintaining type safety. This is what makes the STL so flexible. Templates are the T in STL. Preface xiv
Page 16
This book uses the C++23 standard The C++ language is standardized by the International Organization for Standardization (ISO) on a roughly three-year cycle. The current standard is called C++23 (which was preceded by C+ +20, C++17, C++14, and C++11). The ISO C++23 formal standard (ISO/IEC 14882:2024) was published in October 2024. C++23 builds upon C++20 with many refinements and some new features. While not as large an update as C++20, the refinements in C++23 are significant. Improvements include the new print() and println() functions, which are built upon the format library, an all-inclusive std module, updates to the ranges and views libraries, a generator class, and more. The most visible updates are the print() and println() functions and the new std module. Hiding the std:: namespace In most instances, the exercises in this book will hide the std:: namespace. This is for page space and readability considerations. We know that most STL identifiers are in the std:: namespace. I will normally use some form of the using declaration to avoid cluttering the examples with repetitive prefixes. For example, when using println() you can presume I've included a using declaration like this: using std::println; // println is now available sans prefix println("Hello, Jimi!"); I usually will not show the using declaration in the recipe listings. This allows us to focus on the purpose of the example. It is poor practice to import the entire std:: namespace in your code. You should avoid a using namespace declaration like this: using namespace std; // bad. don't do this. println("Hello, Jimi!"); The std:: namespace includes thousands of identifiers and there's no good reason to clutter your namespace with them. The potential for collisions is not trivial and can be hard to track down. When you want to use a name or names without the std:: prefix, the preferred method is to import the name(s) explicitly, one at a time, as above. To further avoid namespace collisions, I often use a separate namespace for classes that will be re-used. I tend to use namespace bw for my personal namespace. You may use a name that works for you. xv Preface
Page 17
Type aliases with using This book uses the using directive for type aliases instead of typedef. STL classes and types can be verbose at times. A templated iterator class, for example, may look like this: vector<pair<int, string>>::iterator Long type names are not just hard to type; they are prone to errors. One common technique is to abbreviate long type names with typedef: typedef vector<pair<int, string>>::iterator vecit_t This declares an alias for our unwieldy iterator type. typedef is inherited from C and its syntax reflects that. Beginning with C++11, the using keyword may be used to create a type alias: using vecit_t = vector<pair<int, string>>::iterator; In most circumstances, a using alias is equivalent to typedef. The most significant difference is that a using alias may be templated: template<typename T> using vec = vector<T>; vec<int> x {}; For these reasons, and for the sake of clarity, this book prefers the using directive for type aliases. Abbreviated function templates Beginning with C++20, an abbreviated function template may be specified without the template header. For example: void printc(const auto& c) { for (auto i : c) { println("{}", i); } } Preface xvi
Page 18
The auto type in a parameter list works like an anonymous template typename. It is equivalent to: template<typename T> void printc(const T& c) { for (auto i : c) { println("{}", i); } } Though formally introduced with C++20, abbreviated function templates had already been supported by the major compilers for some time. This book uses abbreviated function templates in many of the examples. Use the STL to solve real-world problems The recipes in this book use the STL to provide real-world solutions to real-world problems. They have been designed to rely exclusively on the STL and C++ standard libraries, with no non-standard libraries. This should make it easy for you to experiment and learn without the distractions of installing and configuring third-party code. Now, let's go have some fun with the STL. Happy learning! Who this book is for This book is for intermediate to advanced C++ programmers who want to get more out of the C+ +23 Standard Template Library. Basic knowledge of C++ and related concepts is necessary to get the most out of this book. What this book covers Chapter 1, Introduction to New C++23 Features, introduces the new STL features in C++23. It aims to familiarize you with the new language features so you may use them with the STL. Chapter 2, Best Practices, discusses modern STL features added in recent C++ versions. Chapter 3, STL Containers, covers the STL's comprehensive library of containers. Chapter 4, STL Compatible Iterators, shows how to use and create STL-compatible iterators. Chapter 5, Lambda Expressions, covers the use of lambdas with STL functions and algorithms. Chapter 6, STL Algorithms, provides recipes for using and creating STL-compatible algorithms. Chapter 7, Strings and Formatting, describes the STL string and formatter classes. xvii Preface
Page 19
Chapter 8, Utility Classes, covers STL utilities for date and time, smart pointers, optionals, and more. Chapter 9, Concurrency and Parallelism, describes support for concurrency, including threads, async, atomic types, and more. Chapter 10, Using the File System, covers the std::filesystem classes and how to put them to use with the latest advancements from C++23. Chapter 11, More Practical Ideas, provides a few more solutions, including a trie class, string split, and more. This provides advanced examples of how to put the STL to use for real-world problems. Chapter 12, C++26 and the Future, examines features proposed for the upcoming C++26 update. The recipes in this book use the GCC compiler Unless otherwise noted, most of the recipes in this book have been developed and tested using the GCC compiler, version 17.2, the latest stable version as of this writing. As of mid 2026, C++23 is not yet fully implemented on any available compiler. Of the three major compilers, GCC (GNU), MSVC (Microsoft), and Clang (Apple), the MSVC compiler is generally furthest along in implementing the new standard. Occasionally, we may run into a feature that is implemented on MSVC or another compiler, but not on GCC, in which case I will note which compiler I used. If a feature is not yet implemented on any available compiler, I will explain that I was unable to test it. Where possible, code has been tested on one or more of these compilers GCC 15.2 Debian Linux 6.17 LLVM/Clang 17.0 macOS 15.7 Microsoft C++ 19.44 Windows 11 I strongly recommend that you install GCC to follow along with the recipes in this book. GCC is freely available under the GNU General Public License (GPL). The easiest way to get the latest version of GCC is to install Debian Linux (also GPL) and use apt with the testing repository. If you are using the digital version of this book, we suggest you type the code yourself or download the code from the GitHub repository (link in the next section). This will avoid errors due to copying and pasting formatted code from the e-book. Preface xviii
Page 20
Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/CPP-STL-Cookbook-Second-Edition. In the event of updates and errata, code will be updated in the GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out! Download the color images We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781836204251. Conventions used There are several text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, file names, file extensions, path names, dummy URLs, user input, and social media handles. Here is an example: "The insert() method takes an initializer_list and calls the private function _insert()". A block of code is set as follows: int main() { Frac f {5, 3}; println("Frac: {}", f); } Any command-line input or output is written as follows: $ ./producer-consumer Got 0 from the queue Got 1 from the queue Got 2 from the queue finished! Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel." xix Preface
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay

Every 10 yuan is 1 year of VIP; the remainder counts as months (5 yuan is 5 months, 100 yuan is 10 years). Signed-in users are enabled immediately and both you and the admin get an email. Guests receive an ID and are sent to register.

← Back to List