Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering the C++17 STL
Mastering the C++17 STL

Mastering the C++17 STL: Make full use of the standard library components in C++17

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mastering the C++17 STL

Iterators and Ranges

In the previous chapter, we implemented several generic algorithms that operated on containers, but in an inefficient manner. In this chapter, you'll learn:

  • How and why C++ generalizes the idea of pointers to create the iterator concept
  • The importance of ranges in C++, and the standard way to express a half-open range as a pair of iterators
  • How to write your own rock-solid, const-correct iterator types
  • How to write generic algorithms that operate on iterator pairs
  • The standard iterator hierarchy and its algorithmic importance

The problem with integer indices

In the previous chapter, we implemented several generic algorithms that operated on containers. Consider one of those algorithms again:

    template<typename Container>
void double_each_element(Container& arr)
{
for (int i=0; i < arr.size(); ++i) {
arr.at(i) *= 2;
}
}

This algorithm is defined in terms of the lower-level operations .size() and .at(). This works reasonably well for a container type such as array_of_ints or std::vector, but it doesn't work nearly so well for, say, a linked list such as the previous chapter's list_of_ints:

    class list_of_ints {
struct node {
int data;
node *next;
};
node *head_ = nullptr;
node *tail_ = nullptr;
int size_ = 0;
public:
int size() const { return size_; }
int& at(int i) {
if (i >= size_...

On beyond pointers

In the absence of any abstraction, how does one normally identify an element of an array, an element of a linked list, or an element of a tree? The most straightforward way would be to use a pointer to the element's address in memory. Here are some examples of pointers to elements of various data structures:

To iterate over an array, all we need is that pointer; we can handle all the elements in the array by starting with a pointer to the first element and simply incrementing that pointer until it reaches the last element. In C:

    for (node *p = lst.head_; p != nullptr; p = p->next) {
if (pred(p->data)) {
sum += 1;
}
}

But in order to efficiently iterate over a linked list, we need more than just a raw pointer; incrementing a pointer of type node* is highly unlikely to produce a pointer to the next node in the list! In that case...

Const iterators

There's just one more complication to consider, before we abandon this list iterator example. Notice that I quietly changed our count_if function template so that it takes Container& instead of const Container&! That's because the begin() and end() member functions we provided are non-const member functions; and that's because they return iterators whose operator* returns non-const references to the elements of the list. We'd like to make our list type (and its iterators) completely const-correct--that is, we'd like you to be able to define and use variables of type const list_of_ints, but prevent you from modifying the elements of a const list.

The standard library generally deals with this issue by giving each standard container two different kinds of iterator: bag::iterator and bag::const_iterator. The non-const member function...

A pair of iterators defines a range

Now that we understand the fundamental concept of an iterator, let's put it to some practical use. We've already seen that if you have a pair of iterators as returned from begin() and end(), you can use a for-loop to iterate over all the elements of the underlying container. But more powerfully, you can use some pair of iterators to iterate over any sub-range of the container's elements! Let's say you only wanted to view the first half of a vector:

    template<class Iterator>
void double_each_element(Iterator begin, Iterator end)
{
for (auto it = begin; it != end; ++it) {
*it *= 2;
}
}

int main()
{
std::vector<int> v {1, 2, 3, 4, 5, 6};
double_each_element(v.begin(), v.end());
// double each element in the entire vector
double_each_element(v.begin(), v...

Iterator categories

Let's revisit the count and count_if functions that we introduced in
Chapter 1, Classical Polymorphism and Generic Programming. Compare the function template definition in this next example to the similar code from that chapter; you'll see that it's identical except for the substitution of a pair of Iterators (that is, an implicitly defined range) for the Container& parameter--and except that I've changed the name of the first function from count to distance. That's because you can find this function, almost exactly as described here, in the Standard Template Library under the name std::distance and you can find the second function under the name std::count_if:

    template<typename Iterator>
int distance(Iterator begin, Iterator end)
{
int sum = 0;
for (auto it = begin; it != end; ++it) {
sum += 1...

Input and output iterators

We can imagine even weaker concepts than ForwardIterator! For example, one useful thing you can do with a ForwardIterator is to make a copy of it, save the copy, and use it to iterate twice over the same data. Manipulating the iterator (or copies of it) doesn't affect the underlying range of data at all. But we could invent an iterator like the one in the following snippet, where there is no underlying data at all, and it's not even meaningful to make a copy of the iterator:

    class getc_iterator {
char ch;
public:
getc_iterator() : ch(getc(stdin)) {}
char operator*() const { return ch; }
auto& operator++() { ch = getc(stdin); return *this; }
auto operator++(int) { auto result(*this); ++*this; return result; }
bool operator==(const getc_iterator&) const { return false; }
bool operator!=(const...

Putting it all together

Putting together everything we've learned in this chapter, we can now write code like the following example. In this example, we're implementing our own list_of_ints with our own iterator class (including a const-correct const_iterator version); and we're enabling it to work with the standard library by providing the five all-important member typedefs.

    struct list_node {
int data;
list_node *next;
};

template<bool Const>
class list_of_ints_iterator {
friend class list_of_ints;
friend class list_of_ints_iterator<!Const>;

using node_pointer = std::conditional_t<Const, const list_node*,
list_node*>;
node_pointer ptr_;

explicit list_of_ints_iterator(node_pointer p) : ptr_(p) {}
public:
// Member typedefs required by std::iterator_traits
using difference_type...

The deprecated std::iterator

You might be wondering: "Every iterator class I implement needs to provide the same five member typedefs. That's a lot of boilerplate--a lot of typing that I'd like to factor out, if I could." Is there no way to eliminate all that boilerplate?

Well, in C++98, and up until C++17, the standard library included a helper class template to do exactly that. Its name was std::iterator, and it took five template type parameters that corresponded to the five member typedefs required by std::iterator_traits. Three of these parameters had "sensible defaults," meaning that the simplest use-case was pretty well covered:

    namespace std {
template<
class Category,
class T,
class Distance = std::ptrdiff_t,
class Pointer = T*,
class Reference = T&
> struct iterator {
using...

Summary

In this chapter, we've learned that traversal is one of the most fundamental things you can do with a data structure. However, raw pointers alone are insufficient for traversing complicated structures: applying ++ to a raw pointer often doesn't "go on to the next item" in the intended way.

The C++ Standard Template Library provides the concept of iterator as a generalization of raw pointers. Two iterators define a range of data. That range might be only part of the contents of a container; or it might be unbacked by any memory at all, as we saw with getc_iterator and putc_iterator. Some of the properties of an iterator type are encoded in its iterator category--input, output, forward, bidirectional, or random-access--for the benefit of function templates that can use faster algorithms on certain categories of iterators.

If you're defining your...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Boost your productivity as a C++ developer with the latest features of C++17
  • Develop high-quality, fast, and portable applications with the varied features of the STL
  • Migrate from older versions (C++11, C++14) to C++17

Description

Modern C++ has come a long way since 2011. The latest update, C++17, has just been ratified and several implementations are on the way. This book is your guide to the C++ standard library, including the very latest C++17 features. The book starts by exploring the C++ Standard Template Library in depth. You will learn the key differences between classical polymorphism and generic programming, the foundation of the STL. You will also learn how to use the various algorithms and containers in the STL to suit your programming needs. The next module delves into the tools of modern C++. Here you will learn about algebraic types such as std::optional, vocabulary types such as std::function, smart pointers, and synchronization primitives such as std::atomic and std::mutex. In the final module, you will learn about C++'s support for regular expressions and file I/O. By the end of the book you will be proficient in using the C++17 standard library to implement real programs, and you'll have gained a solid understanding of the library's own internals.

Who is this book for?

This book is for developers who would like to master the C++ STL and make full use of its components. Prior C++ knowledge is assumed.

What you will learn

  • - Make your own iterator types, allocators, and thread pools.
  • - Master every standard container and every standard algorithm.
  • - Improve your code by replacing new/delete with smart pointers.
  • - Understand the difference between monomorphic algorithms, polymorphic algorithms, and generic algorithms.
  • - Learn the meaning and applications of vocabulary type, product type and sum type.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 28, 2017
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126824
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 28, 2017
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126824
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
C++17 STL Cookbook
€41.99
Mastering C++ Multithreading
€36.99
Mastering the C++17 STL
€36.99
Total 115.97 Stars icon

Table of Contents

12 Chapters
Classical Polymorphism and Generic Programming Chevron down icon Chevron up icon
Iterators and Ranges Chevron down icon Chevron up icon
The Iterator-Pair Algorithms Chevron down icon Chevron up icon
The Container Zoo Chevron down icon Chevron up icon
Vocabulary Types Chevron down icon Chevron up icon
Smart Pointers Chevron down icon Chevron up icon
Concurrency Chevron down icon Chevron up icon
Allocators Chevron down icon Chevron up icon
Iostreams Chevron down icon Chevron up icon
Regular Expressions Chevron down icon Chevron up icon
Random Numbers Chevron down icon Chevron up icon
Filesystem Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(11 Ratings)
5 star 63.6%
4 star 27.3%
3 star 9.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




AlGrenadine May 23, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If like me you need your c++ knowledge to be boosted from c++11 to c++17 this book is perfect.Quite clear and exhaustive, i'll definitely recommend it to my coworkers
Amazon Verified review Amazon
user65486731 Apr 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book! I really enjoyed reading it, I was even a bit sad when I finished the last chapter. The writing is clear, concise and even entertaining. When appropriate, explanations are accompanied by example implementations, which I found to be very instructive. The amount of information is limited in a useful way, it doesn't discourage you to dive into a chapter, neither is it too superficial. Code snippets and explanation are well equilibrated.I obviously won't remember all the details, but the concepts and ideas behind the library facilities should stick. Also, remembering how certain problem statements might be solved with the STL building blocks and where to dive back into a particular topic is quite a valuable outcome. I wouldn't want to digest what specific things I learned from the book. The real question is whether it was enjoyable, thought-provoking and comprehensive with regard to the reasoning about code. And that's exactly the case.
Amazon Verified review Amazon
Guneet Lamba May 03, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Easy to understand, in depth topics
Amazon Verified review Amazon
Yesudeep Mangalapilly Jul 03, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Steal this book if you see one around! It is chock full of great explanation, excellent code, and very well thought-out practices. The C++ STL was a mystery to me, and I think Mr. Arthur O'Dwyer has cleared a lot of cobwebs a budding C++ programmer may have in their understanding of C++! Give copies to your colleagues!
Amazon Verified review Amazon
Jon Kalb Oct 29, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are two things that we want in a technical book. One is for it to be understandable. We want to learn and we need a book that can teach. Arthur's style is conversational and very approachable and this book builds from simple concepts to cover complicated issues, by taking us step by step. You can see this yourself by reading a few sample pages and looking at the table of contents.The other thing we need from a technical book is authority. It doesn't help us to read a book that does us a good job of teaching us the wrong information or gives questionable advise on how to write code. This is a real problem for anyone that wants to learn because, how can you know that the author is an authority on material we've not learned yet. If we already knew the truth, we wouldn't be shopping for a book.Many tech books are written by experts, who know their material very well, but many are written by individuals that know how to sound like experts by writing with confidence about things they don't completely understand. You can't tell them apart unless you are already a expert in the area of the book that you are looking for.This is where reviews like this can help. I make my living teach people how to write modern C++ and recruiting people to speak at C++ conferences like C++Now and CppCon. It is my job to be able to spot people that are real experts in C++ and have the ability to explain it well. I'm happy to endorse Arthur as having the knowledge we expect of experts and the ability to explain that we hope to find in the best teachers.This book is just out, so I'm only a quarter of the way through it, but it is clear that Arthur have found the right voice and level of detail to cover the latest iteration of the STL without getting bogged down in minutia. This book will be essential for those learning to use the STL for the first time and also valuable to old-timers that appreciate a refresher that includes an update to the latest standard.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.