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 ) .
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:
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() { std::println("hello, world"); } 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 S T L.
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.
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.
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.
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); } } 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.
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!
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.
Chap t er 1 , Introduction to New C++2 3 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.
, Best Practices , discusses modern STL features added in recent C++ versions.
, STL Containers , covers the STL's comprehensive library of containers.
, STL C ompatible Iterators , shows how to use and create STL-compatible iterators.
, Lambda Expressions , covers the use of lambdas with STL functions and algorithms.
, STL Algorithms , provides recipes for using and creating STL-compatible algorithms.
, Strings and Formatting , describes the STL string and formatter classes.
, Utility Classes , covers STL utilities for date and time, smart pointers, optionals, and more.
, Concurrency and Parallelism , describes support for concurrency, including threads, async, atomic types, and more.
, Using the File System , covers the std::filesystem classes and how to put them to use with the latest advancements from C++23.
, 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.
, C++26 and the Future , examines features proposed for the upcoming C++26 update.
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.
You can download the example code files for this book from GitHub at . 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 Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:
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."
Warnings or important notes appear like this.
Tips and tricks appear like this.
In this book, you will find several headings that appear frequently ( How to do it... , How it works... , There's more... , and See also… ).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information about the recipe.
Feedback from our readers is always welcome.
General feedback : If you have questions about any aspect of this book or have any general feedback, please email us at [email protected] and mention the book's title in the subject of your message.
Errata : Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit click Submit Errata , and fill in the form.
Piracy : If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author : If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit
Read this book alongside other users, developers, experts, and the author himself.
Ask questions, provide solutions to other readers, chat with the authors via Ask Me Anything sessions, and much more. Scan the QR or visit the link to join the community.
This book comes with free benefits to support your learning. Activate them now for instant access (see the " How to Unlock " section for instructions).
Here's a quick overview of what you can instantly unlock with your purchase:
Scan the QR code (or go to ). Search for this book by name, confirm the edition, and then follow the steps on the page.
Note: Keep your invoice handy. Purchases made directly from Packt don't require an invoice.
Once you've read C++ STL Cookbook , we'd love to hear your thoughts! Scan the QR code below to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.