C++17 is on the way, and I’m glad to see more books that stay on the bleeding edge of C++ adaptation. Today I’d like to present a book that focuses on the Standard Library.

Is this another great book?

TL; DR: Yes :) But read more to see why :)

Plus I have a bonus: Q&A with the author and a giveaway.

The Book

C++17 STL Cookbook by Jacek Galowicz

Github Repo with the samples

Currently @Amazon you can buy a printed copy, if you want a DRM-Free ebook go to Pack Publishing store: C++17 STL Cookbook.

See Jacek’s blog, and on Twitter: @jgalowicz

Also, it’s worth mentioning that Arne Mertz from Simplify C++ helped with the book, as he was the technical reviewer.

BTW: I noticed Jacek around like one year or more ago and was happy to see another Polish guy writing about C++. I was misled by his Polish sounding surname. As it turned out Jacek is German with roots in Poland, so my initial guess was not 100% correct. So, I still had to communicate in English :)

The Structure

The cookbook contains over 90 recipes, 500+ pages, full of STL content and samples.

It’s not aimed at beginners. It might be great as a second or third book after an introduction to C++.

Here’s a summary of chapters:

1: The New C++17 Features

A review of new features, with examples.

2: STL Containers

Basics of containers, erase-remove idiom, removing from a vector in O(1), accessing vector elements, keeping std::vector instances sorted, maps, implementing a simple RPN calculator with std::stack , Implementing a word frequency counter, Implementing a writing style helper tool for finding very long sentences in text with std::multimap , Implementing a personal to-do list using std::priority_queue .

3: Iterators

Introduction to iterators, Making your own iterators compatible with STL iterator categories, iterator adapters, Implementing algorithms in terms of iterators, checked iterators, zip iterator adapter

4: Lambda Expressions

Using lambdas, polymorphic lambdas with std::function , function concatenation, complex predicates with logical conjunction, transform_if using std::accumulate and lambdas, Cartesian product pairs of any input at compile time.

5: STL Algorithm Basics

Copying data between different containers, sorting, searching, removing elements, Locating patterns in strings with std::search and choosing the optimal implementation (like the Boyer-Moore searcher), sampling large vectors, Implementing a dictionary merging tool, generating permutations.

6: Advanced Use of STL Algorithms

A trie class using STL algorithms, a search input suggestion generator with tries, Fourier transform formula, ASCII Mandelbrot renderer, Building our own algorithm - split, Composing useful algorithms from standard algorithms - gather, Removing consecutive whitespace between words, compressing and decompressing strings.

7: Strings, Stream Classes, and Regular Expressions

Creating, concatenating, trimming, and transforming strings, using string_view , Reading values from user input, Counting all words in a file, I/O stream manipulators, std::istream iterators, std::ostream iterators, custom string classes by inheriting from std::char_traits , Tokenizing input with the regular expression library, Catching readable exceptions from std::iostream errors.

8: Utility Classes

Using std::ratio , chrono, optional, tuples, variant, any, smart pointers, random number engines.

9: Parallelism and Concurrency

Paralell STL, working with threads, Performing exception safe shared locking with std::unique_lock and std::shared_lock , avoiding deadlocks with std::scoped_lock , safely postponing initialization with std::call_once , using std::async , producer/consumer idiom, parallelizing the ASCII Mandelbrot renderer using std::async , Implementing a tiny automatic parallelization library with std::future .

10: Filesystem

Listing all files in directories, writing a grep-like text search tool, an automatic file renamer, disk usage counter, Calculating statistics about file types, Implementing a tool that reduces folder size by substituting duplicates with symlinks

My View

If you only skimmed the previous section, please go back and read what’s inside those ten chapters. I can wait :)

Impressed?

I am!

What’s clear is that most of the recipes are a solid, working examples/demos. Of course, there are many introduction sections to give you a background, but most of the time you just work on a small app, or tool. So those are not just tiny, theoretical, impractical code samples. If you finish a chapter, you can be sure to end with something useful.

Nor is this a reference book. You can find introductory explanations, but in general, it will teach you how to use STL efficiently by working on real problems.

Regarding the amount of experience needed to understand the chapters, it varies a lot. There is some basic stuff that everyone (after an intro to C++) should get. But there are also complicated examples where you’ll need to read the section several times (at least I had to! :)). That’s good. Having all recipes on the same level would be boring. With such mixture, everyone can find something for themselves and also have some challenge with more advanced problems.

Interesting recipes

A few of recipes that caught my attention:

Mandelbrot renderer

The example is maybe complicated; I had to read it several times to understand. Still, it shows how to compose the solution using smaller blocks. So you’ll be using functions that return lambdas, complex numbers, std::transform .

You have even two variations: a basic version and the parallelized one!

Other tools/utils/demos:

Grep-like tool - it shows how to iterate over a directory and then scan text files (with regex).

Reverse Polish Notation calculator.

Tries and working with text/dictionaries.

Writing style helper tool for finding very long sentences in text with std::multimap . The text is tokenized to get sentences stats. Then a user can see what parts of text should be improved.

. The text is tokenized to get sentences stats. Then a user can see what parts of text should be improved. …

STL tricks

Like deleting items from an unsorted std::vector in O(1) time. Copying elements from different containers. Synchronized stdout :

static void print_pcout ( int id ) { pcout {} << "pcout hello from " << id << '

' ; }

The object pcout makes sure the whole string is printed to stdout without any interruption as you could get with the standard cout .

Debugging iterators

Using _GLIBCXX_DEBUG, or ( /D_ITERATOR_DEBUG_LEVEL=1) in MSVC.

It’s great that the book brings up that topic. Iterators are powerful, but they can quickly become invalid when used in the wrong way. The recipe shows how different tools can help when debugging such cases.

Functional stuff

Zips, composing functions, lambdas. Functional programming gets more and more popular, so I like that Jacek shows a few ideas in the examples.

Implementing a tiny automatic parallelization library

The example shows how to distribute the sub-tasks of a problem as an automatically parallelizing asynchronous version. The lambdas returning lambdas are a bit hardcore, but it works :) The example uses this for strings operations, but you can adapt the tiny library for any domain.

Going back to a general overview:

Jacek also conveys a crucial message throughout the book. For example:

“At this point, we are using STL data structures so intuitively that we can nicely avoid pointers, raw arrays, and other crude legacy structures.”

Similar messages appear in several parts of the book. When you know STL you can build your apps much faster, and more safely, and compose code as if you were sticking Lego blocks together. It’s also a modern style of C++ - not using raw code structures or reinventing everything from scratch.

All in all, great stuff.

Plus, as always its cookbook style makes it easy to read, which I like.

But wait.

Before we go to the summary, I’d like to show you a little interview with the author:

Q&A with the author

Bartek: How did you come up with the idea for the book? Why did you want to write about STL?

Jacek: It was actually not my own idea to write a book at all and specifically about the STL. Nitin Dasan, a very nice Acquisition Editor at Packt Publishing, approached me and asked very directly if I was interested in writing a book for them. Back then, the title “C++17 STL Cookbook” was already fixed.

At that time I was unemployed because my former employer shut down the whole site I was associated to. Since I was seeking to become self-employed rather than just looking for jobs somewhere else, writing my own book looked like a great opportunity. The next step was compiling a list of ~90 recipes that I would write for the book, which Packt then accepted and sent me a contract.

While the book title and format (a cookbook with recipes) were fixed already, I still had a lot of freedom: What would the recipes be about and how would they use C++17 and the STL?

I tried to do as many things with the STL as possible. As you noticed in your review already, I did even avoid for-loops. My idea was to demonstrate that the STL is not only a library of neat little helpers but actually a foundation of building blocks whole applications can and should build on. Everyone who does not realize this tends to reinvent the wheel here and there. If you rewrite something that the STL already provides, you ditch the fact that all these algorithms and data structures are usually well designed, well tested, well performing, and keep your code well readable and maintainable. C++ programmers should perceive the STL as standard building blocks that are just linked differently in every C++ program (this perspective is now pointedly oversubscribed).

The reader might find that sometimes extreme. But then, he/she is completely free to pick what he/she liked and leave the rest. My hope is that this books really shows the audience something new and that it is inspiring.

Bartek: What was the hardest part of writing the book?

Jacek: The recipes in the book are all about C++17 and the STL. This means that they should only require a C++17 capable compiler and the STL. It was hard to find about 90 meaningful and interesting example problems and applications that are short but self-contained enough, as they need fit into the typical 4-8 pages recipe format. It would have been easier to find nice real life examples if the STL was already including features like networking and so on. Including external libraries would have missed the point of the book and might have made it harder for users of different operating systems to follow them, so I strictly avoided that.

Bartek: What’s your favourite feature of C++17 (a language or STD library feature)?

Jacek: My favorite little list of new features is: Lambda expressions: These are not new to C++17, but I love them as I recently also learned Haskell and got pretty fascinated by functional programming style. Lambda expressions in C++ enable for adapting many beautiful concepts from there and using them to make the low-level code more generic and maintainable.

Parallel algorithms: It blew me away when I heard about this for the first time! Parallelizing code portably just by prepending another parameter in existing STL algorithm calls - this is fantastic.

Iterator sentinels: I do often implement my own iterators for all kinds of low-level things. This became even easier and more flexible since the end-iterator does not have to be of the same type as the begin-iterator any longer.

Structured bindings: I use tuples a lot and structured bindings are really helping with keeping code readable.

Automatic template type deduction: Finally I do not always have to implement make_xxx(…) helper functions any longer for determining the template types of classes that shall only depend on from what kind of type I construct them!

Inline member variables: Some libraries are best implemented as header-only and this new feature is quite an enabler in that regard.

Bartek: What other C++17 books would you like to see?

Jacek: In general, I love books that make me change my thinking and shake me out of developing in old patterns I was always used to.

I would especially love to see more books from 2 groups of developers: Library developers: Libraries are what really empowers the application programmer, it’s not just the rising amount of language features. In general, what makes a library great is when it is easy to use correctly, hard to use incorrectly, and when it is fast for as many different use cases as possible. More C++ specific books on that topic would be great.

Embedded developers: Using C++ in the embedded area seems to come more and more into fashion. Being an embedded/OS developer myself, I often feel that I need to pioneer a lot of things (although there are also a lot of great libraries for different situations already!). More literature that expands horizons in that area would be great.

Summary

Final mark: 5/5

Pros:

Practical, full of examples, demos, little utilities

Details of the approach, even with pictures and diagrams! :)

Cookbook style, read what you want

Shows how to make code compact

Shows how to use STL as building block for an app/problem

Focuses on modern C++, avoids using raw code style: pointers, C-style arrays, even raw loops

Introduces functional concepts

Cons:

I’d like to see more :)

Nitpicking: some samples might not work yet if your compiler is not in the C++ latest mode, or even experimental (will change soon).

Another solid book about C++17 just before the C++17 Standard is announced!

Not aimed at beginners, but if you have some experience with C++, you’ll find something for yourself. The chapters are structured to be as clear as possible, with introductions and even pictures and diagrams.

Some time ago I had reviewed C++ Modern Programming Cookbook. These two books don’t compete much with each other, and I’d suggest reading them both. “C++ Modern Programming” is focused on all levels of experience (also for ‘almost’ beginners), while “C++17 STL Cookbook” is for an intermediate/expert level. You’ll find some good introduction in the first book, and then you can continue forward and gain more from the second book.

What’s you favorite C++17 feature?

Do you use STL library or something else?

What recipes for modern C++ would you like to read more?

What other books you’d suggest for modern C++?

Giveaway

The Giveaway has ended!

Here are the winners:

Lucien Cartier-Tilet

Faizan Alam

Dustin Kirksey

Congratulations!