Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
Modern C++ Programming Cookbook
Modern C++ Programming Cookbook

Modern C++ Programming Cookbook: Recipes to explore data structure, multithreading, and networking in C++17

eBook
AU$14.99 AU$60.99
Paperback
AU$75.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Modern C++ Programming Cookbook

Working with Numbers and Strings

The recipes included in this chapter are as follows:

  • Converting between numeric and string types
  • Limits and other properties of numeric types
  • Generating pseudo-random numbers
  • Initializing all bits of internal state of a pseudo-random number generator
  • Using raw string literals to avoid escaping characters
  • Creating cooked user-defined literals
  • Creating raw user-defined literals
  • Creating a library of string helpers
  • Verifying the format of a string using regular expressions
  • Parsing the content of a string using regular expressions
  • Replacing the content of a string using regular expressions
  • Using string_view instead of constant string references

Introduction

Numbers and strings are the fundamental types of any programming language; all other types are based or composed of these ones. Developers are confronted all the time with tasks, such as converting between numbers and strings, parsing strings, or generating random numbers. This chapter is focused on providing useful recipes for these common tasks using modern C++ language and library features.

Introduction


Numbers and strings are the fundamental types of any programming language; all other types are based or composed of these ones. Developers are confronted all the time with tasks, such as converting between numbers and strings, parsing strings, or generating random numbers. This chapter is focused on providing useful recipes for these common tasks using modern C++ language and library features.

Converting between numeric and string types


Converting between number and string types is a ubiquitous operation. Prior to C++11, there was little support for converting numbers to strings and back, and developers had to resort mostly to type-unsafe functions and usually wrote their own utility functions in order to avoid writing the same code over and over again. With C++11, the standard library provides utility functions for converting between numbers and strings. In this recipe, you will learn how to convert between numbers and strings and the other way around using modern C++ standard functions.

Getting ready

All the utility functions mentioned in this recipe are available in the <string> header.

How to do it...

Use the following standard conversion functions when you need to convert between numbers and strings:

  • To convert from an integer or floating point type to a string type, use std::to_string() or std::to_wstring() as shown in the following code snippet:
        auto si = std::to_string...

Limits and other properties of numeric types


Sometimes, it is necessary to know and use the minimum and maximum values representable with a numeric type, such as char, int, or double. Many developers are using standard C macros for this, such as CHAR_MIN/CHAR_MAX, INT_MIN/INT_MAX, or DBL_MIN/DBL_MAX. C++ provides a class template called numeric_limits with specializations for every numeric type that enables you to query the minimum and maximum value of a type, but is not limited to that and offers additional constants for type properties querying, such as whether a type is signed or not, how many bits it needs for representing its values, for floating point types whether it can represent infinity, and many others. Prior to C++11, the use of numeric_limits<T> was limited because it could not be used in places where constants were needed (examples can include the size of arrays and switch cases). Due to that, developers preferred to use the C macros throughout their code. In C++11, that...

Generating pseudo-random numbers


Generating random numbers is necessary for a large variety of applications, from games to cryptography, from sampling to forecasting. However, the term random numbers is not actually correct, as the generation of numbers through mathematical formulas is deterministic and does not produce true random numbers, but numbers that look random and are called pseudo-random. True randomness can only be achieved through hardware devices, based on physical processes, and even that can be challenged, as one may consider even the universe to be actually deterministic. Modern C++ provides support for generating pseudo-random numbers through a pseudo-random number library containing number generators and distributions. Theoretically, it can also produce true random numbers, but in practice, those could actually be only pseudo-random.

Getting ready

In this recipe, we discuss the standard support for generating pseudo-random numbers. Understanding the difference between random...

Initializing all bits of internal state of a pseudo-random number generator


In the previous recipe, we have looked at the pseudo-random number library with its components and how it can be used to produce numbers in different statistical distributions. One important factor that was overlooked in that recipe is the proper initialization of the pseudo-random number generators. In this recipe, you will learn how to initialize a generator in order to produce the best sequence of pseudo-random numbers.

Getting ready

You should read the previous recipe, Generating pseudo-random numbers, to get an overview of what the pseudo-random number library offers.

How to do it...

To properly initialize a pseudo-random number generator to produce the best sequence of pseudo-random numbers, perform the following steps:

  1. Use an std::random_device to produce random numbers to be used as seeding values:
        std::random_device rd;
  1. Generate random data for all internal bits of the engine:
        std::array<int,...

Creating cooked user-defined literals


Literals are constants of built-in types (numerical, boolean, character, character string, and pointer) that cannot be altered in a program. The language defines a series of prefixes and suffixes to specify literals (and the prefix/suffix is actually part of the literal). C++11 allows creating user-defined literals by defining functions called literal operators that introduce suffixes for specifying literals. These work only with numerical character and character string types. This opens the possibility of defining both standard literals in future versions and allows developers to create their own literals. In this recipe, we will see how we can create our own cooked literals.

Getting ready

User-defined literals can have two forms: raw and cooked. Raw literals are not processed by the compiler, whereas cooked literals are values processed by the compiler (examples can include handling escape sequences in a character string or identifying numerical values...

Creating raw user-defined literals


In the previous recipe, we have looked at the way C++11 allows library implementers and developers to create user-defined literals and the user-defined literals available in the C++14 standard. However, user-defined literals have two forms, a cooked form, where the literal value is processed by the compiler before being supplied to the literal operator, and a raw form, in which the literal is not parsed by the compiler. The latter is only available for integral and floating-point types. In this recipe, we will look at creating raw user-defined literals.

Getting ready

Before continuing with this recipe, it is strongly recommended that you go through the previous one, Creating cooked user-defined literals, as general details about user-defined literals will not be reiterated here.

To exemplify the way raw user-defined literals can be created, we will define binary literals. These binary literals can be of 8-bit, 16-bit, and 32-bit (unsigned) types. These types...

Using raw string literals to avoid escaping characters


Strings may contain special characters, such as non-printable characters (newline, horizontal and vertical tab, and so on), string and character delimiters (double and single quotes) or arbitrary octal, hexadecimal, or Unicode values. These special characters are introduced with an escape sequence that starts with a backslash, followed by either the character (examples include ' and "), its designated letter (examples include n for a new line, t for a horizontal tab), or its value (examples include octal 050, hexadecimal XF7, or Unicode U16F0). As a result, the backslash character itself has to be escaped with another backslash character. This leads to more complicated literal strings that can be hard to read.

To avoid escaping characters, C++11 introduced raw string literals that do not process escape sequences. In this recipe, you will learn how to use the various forms of raw string literals.

Getting ready

In this recipe, and throughout...

Creating a library of string helpers


The string types from the standard library are a general purpose implementation that lacks many helpful methods, such as changing the case, trimming, splitting, and others that may address different developer needs. Third-party libraries that provide rich sets of string functionalities exist. However, in this recipe, we will look at implementing several simple, yet helpful, methods you may often need in practice. The purpose is rather to see how string methods and standard general algorithms can be used for manipulating strings, but also to have a reference to reusable code that can be used in your applications.

In this recipe, we will implement a small library of string utilities that will provide functions for the following:

  • Changing a string to lowercase or uppercase.
  • Reversing a string.
  • Trimming white spaces from the beginning and/or the end of the string.
  • Trimming a specific set of characters from the beginning and/or the end of the string.
  • Removing occurrences...

Verifying the format of a string using regular expressions


Regular expressions are a language intended for performing pattern matching and replacements in texts. C++11 provides support for regular expressions within the standard library through a set of classes, algorithms, and iterators available in the header <regex>. In this recipe, we will see how regular expressions can be used to verify that a string matches a pattern (examples can include verifying an e-mail or IP address formats).

Getting ready

Throughout this recipe, we will explain whenever necessary the details of the regular expressions that we use. However, you should have at least some basic knowledge of regular expressions in order to use the C++ standard library for regular expressions. A description of regular expressions syntax and standards is beyond the purpose of this book; if you are not familiar with regular expressions, it is recommended that you read more about them before continuing with the recipes that focus...

Parsing the content of a string using regular expressions


In the previous recipe, we have looked at how to use std::regex_match() to verify that the content of a string matches a particular format. The library provides another algorithm called std::regex_search() that matches a regular expression against any part of a string, and not only the entire string as regex_match() does. This function, however, does not allow searching through all the occurrences of a regular expression in an input string. For this purpose, we need to use one of the iterator classes available in the library.

In this recipe, you will learn how to parse the content of a string using regular expressions. For this purpose, we will consider the problem of parsing a text file containing name-value pairs. Each such pair is defined on a different line having the format name = value, but lines starting with a # represent comments and must be ignored. The following is an example:

    #remove # to uncomment the following lines...

Replacing the content of a string using regular expressions


In the last two recipes, we have looked at how to match a regular expression on a string or a part of a string and iterate through matches and submatches. The regular expression library also supports text replacement based on regular expressions. In this recipe, we will see how to use std::regex_replace() to perform such text transformations.

Getting ready

For general information about regular expressions support in C++11, refer to the Verifying the format of a string using regular expressions recipe.

How to do it...

In order to perform text transformations using regular expressions, you should perform the following:

  1. Include the <regex> and <string> and the namespace std::string_literals for C++14 standard user defined literals for strings:
        #include <regex> 
        #include <string> 
        using namespace std::string_literals;
  1. Use the std::regex_replace() algorithm with a replacement string as the third...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the most important language and library features of C++17, including containers, algorithms, regular expressions, threads, and more,
  • Get going with unit testing frameworks Boost.Test, Google Test and Catch,
  • Extend your C++ knowledge and take your development skills to new heights by making your applications fast, robust, and scalable.

Description

C++ is one of the most widely used programming languages. Fast, efficient, and flexible, it is used to solve many problems. The latest versions of C++ have seen programmers change the way they code, giving up on the old-fashioned C-style programming and adopting modern C++ instead. Beginning with the modern language features, each recipe addresses a specific problem, with a discussion that explains the solution and offers insight into how it works. You will learn major concepts about the core programming language as well as common tasks faced while building a wide variety of software. You will learn about concepts such as concurrency, performance, meta-programming, lambda expressions, regular expressions, testing, and many more in the form of recipes. These recipes will ensure you can make your applications robust and fast. By the end of the book, you will understand the newer aspects of C++11/14/17 and will be able to overcome tasks that are time-consuming or would break your stride while developing.

Who is this book for?

If you want to overcome difficult phases of development with C++ and leverage its features using modern programming practices, then this book is for you. The book is designed for both experienced C++ programmers as well as people with strong knowledge of OOP concepts.

What you will learn

  • Get to know about the new core language features and the problems they were intended to solve
  • Understand the standard support for threading and concurrency and know how to put them on work for daily basic tasks
  • Leverage C++'s features to get increased robustness and performance
  • Explore the widely-used testing frameworks for C++ and implement various useful patterns and idioms
  • Work with various types of strings and look at the various aspects of compilation
  • Explore functions and callable objects with a focus on modern features
  • Leverage the standard library and work with containers, algorithms, and iterators
  • Use regular expressions for find and replace string operations
  • Take advantage of the new filesystem library to work with files and directories
  • Use the new utility additions to the standard library to solve common problems developers encounter including string_view, any , optional and variant types

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 15, 2017
Length: 590 pages
Edition : 1st
Language : English
ISBN-13 : 9781786464736
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 15, 2017
Length: 590 pages
Edition : 1st
Language : English
ISBN-13 : 9781786464736
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.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
AU$249.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 AU$5 each
Feature tick icon Exclusive print discounts
AU$349.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 AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 219.97
Modern C++ Programming Cookbook
AU$75.99
Mastering C++ Multithreading
AU$67.99
Mastering C++ Programming
AU$75.99
Total AU$ 219.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Learning Modern Core Language Features Chevron down icon Chevron up icon
Working with Numbers and Strings Chevron down icon Chevron up icon
Exploring Functions Chevron down icon Chevron up icon
Preprocessor and Compilation Chevron down icon Chevron up icon
Standard Library Containers, Algorithms, and Iterators Chevron down icon Chevron up icon
General Purpose Utilities Chevron down icon Chevron up icon
Working with Files and Streams Chevron down icon Chevron up icon
Leveraging Threading and Concurrency Chevron down icon Chevron up icon
Robustness and Performance Chevron down icon Chevron up icon
Implementing Patterns and Idioms Chevron down icon Chevron up icon
Exploring Testing Frameworks Chevron down icon Chevron up icon
Bibliography Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(7 Ratings)
5 star 42.9%
4 star 42.9%
3 star 0%
2 star 0%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




John Dubchak Jan 31, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am enjoying this book very much. The recipes are succinct, well-written, to the point and tell you what you need to know, why and without any extra fluff.Highly recommended for those “C++ Programmers” still writing C++98 code - time to modernize.
Amazon Verified review Amazon
Plotnus Dec 07, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book. This is a readable book. It's not as dry and boring as alternatives. It is not about memorizing 'trivia'. For these reasons, this is my favorite C++ book and one I recommend to my friends.-------------I bought this book for interview prep. It's now my favorite book on modern C++.My Background: I am a game programmer who has come to greatly dislike C++.I feel that C++ is a 'trivia' language. By this, I mean to be a good C++ programmer you need to understand and know loads of trivia. It is a language for pedants. Most C++ books cater to this approach. One example is Scott Myers books which introduce 90 'tips'. You can also find this in the workplace when coders quote the standard. I really dislike the 'trivia' aspect of being a good C++ programmer and see it as a failing of the language. C++ makes things complicated.This book helps boil them down. It's not about trivia. It's about examples and explaining what is going on with C++ and being able to use it. It's back to base principles.Each chapter has the sections: "Getting Ready", "How to do it", "How it Works", and "There's more...""Getting Ready" - this gives you about a paragraph of background and primes your mind for the topic."How to do it" - shows you examples of using or doing the thing being discussed. Prepares you for using the topic on your own. This also gives you examples you can play with on your own computer."How it works" - goes into a few pages of detail about the implementation. This is great because by understanding the implementation you can avoid many of the pitfalls."There's more" - gives additional detail.So, why is this my favorite C++ book?I feel it frees me from the 'trivia' prevalent in many C++ books. By showing examples and talking about the implementation it prepares me to reason about what is going on instead of relying on "Item 35" or some other hard to remember fact about proper C++ usage.
Amazon Verified review Amazon
Miaw May 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am really happy that I own this book and have read it through. Before reading this book I also had some exposure to modern C++ standard/techniques, but it just seemed very intimidating with the enormous amount of new information and philosophy. Also the standard has changed rapidly from one version to another, I was just frustrated about the fast upgrade and felt it is really hard to keep up while attempting to absorb the new ideas. With this book it all started to change, I am really surprised it covers pretty much all the stuff you need to know, or at least gives you enough hints about how to further explore into this new world. After reading this book I feel a lot more confident on new C++ and I have to say it helps me a lot on my work too(I just transitioned from an environment of C++98 to a new place where everything is C++11/14/17 with heavy use of metaprogramming/templates). It even shows you some really cool design patterns and testing framework which really comes in handy, at least for me.I am also surprised it explains well on some really hard/new subjects with fairly limited paragraphs such as memory models used in atomic library and enable_if where both deserve to have their own books. If anything I'd say it probably fails a bit short on move semantics and the use of decltype/declval which in my opinion are also very important stuff in the new standard.Overall I am really satisfied and I feel happy and a lot more knowledgeable when I finished reading it. Highly recommended to all of you who want to catch up on this new wave of C++.
Amazon Verified review Amazon
S. Ghiassy Dec 18, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Very good book , helps you with new C++ Standards and coding style. Would highly recommend it to all C++ Programmers, from novice to experienced.
Amazon Verified review Amazon
Bartek F. Jun 15, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Disclaimer: I got a free copy from Packt Publishing.Pros: * Clear structure * Cookbook style, so read what you need * Chapters usually starts with some basic recipes and then increase the level of complexity. * Concise examples and details how it works, so not just functions headers. * Modern coding standard, even with C++17 stuff! * C++11, C++14 and C++17 - with clear distinction, an explanation what have changed, etc. * It doesn't have much of 'intro to C++', so you can just jump into intermediate topics! It's not another basic beginner's book. * There are useful 'tips' here and thereCons:* A few typos, repetitions* Chapter about unit testing frameworks could be shorter, but maybe other devs find it useful.* Some recipes are questionable: but that depends on the view/experience. For example: using bitsets. I'd like to see more about performance in the performance chapter.Overall, I like the book. With its clear structure and well-written recipes, it's a great addition to any C++ bookshelf. It's well suited for the target audience: even if you're an expert you'll get a chance to refresh your knowledge and update it with C++14/C++17 content. And If you've just finished some beginner book, you'll find here topics that will move you forward.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.