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
All 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
Arrow up icon
GO TO TOP
The Modern C++ Challenge

You're reading from   The Modern C++ Challenge Become an expert programmer by solving real-world problems

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781788993869
Length 328 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (20) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. Math Problems FREE CHAPTER 2. Language Features 3. Strings and Regular Expressions 4. Streams and Filesystems 5. Date and Time 6. Algorithms and Data Structures 7. Concurrency 8. Design Patterns 9. Data Serialization 10. Archives, Images, and Databases 11. Cryptography 12. Networking and Services 1. Bibliography 2. Other Books You May Enjoy Index

Preface

C++ is a general-purpose programming language that combines different paradigms such as object-oriented, imperative, generic, and functional programming. C++ is designed for efficiency and is the primary choice in applications where performance is key. Over the last few decades, C++ has been one of the most widely used programming languages in industry, academia, and elsewhere. The language is standardized by the International Organization for Standardization (ISO), which is currently working on the next version of the standard, called C++20, due to be completed in 2020.

With the standard covering almost 1500 pages, C++ is not the simplest language to learn and master. Skills are not acquired only by reading about them or watching others exercising them, but by practicing them again and again. Programming is no different; we developers do not learn new languages or technologies just by reading books, articles, or watching video tutorials. Instead, we need practice to sediment and develop the new things we learn so that we can eventually master them. Many a times, however, finding good exercises to put our knowledge to test is a difficult task. Although there are many websites that feature problems for different programming languages, most of these are mathematical problems, algorithms, or problems for student competitions. These kinds of problems do not help you exercise a large variety of a programming language functionalities. That is where this book steps in.

This book is a collection of 100 real-world problems designed for you to practice a large variety of the C++ language and standard library features as well as many third-party, cross-platform libraries. Yet, a few of these problems are C++ specific and, in general, can be solved in many programming languages. Of course, the intention is to help you master C++ and therefore you are expected to solve them in C++. All the solutions provided in the book are in C++. However, you can use the book as a reference for its collection of proposed problems when you learn other programming languages, although in this case, you will not benefit from the solutions.

The problems in this book are grouped into 12 chapters. Each chapter contains problems on similar or related topics. The problems have different levels of difficulty; some of them are easy, some are moderate, and some are difficult. The book has a relatively equal number of problems for each difficulty level. Each chapter starts with the description of the proposed problems. The solutions to these problems ensue with recommendations, explanations, and source code. Although you can find the solutions in the book, it is recommended that you try to implement them by yourself first, and only afterward—or if you have difficulties completing them—look at the proposed solutions. There is only one thing that is missing in the source code presented in the book—the headers you have to include. This was left out on purpose so that you figure those out by yourself. On the other hand, the source code provided with the book is complete, and you can find all the required headers there.

At the time of writing this book, the C++20 version of the standard is in progress and will continue for the next couple of years. However, some features have already been voted in, and one of these features is the extension to the chrono library with calendars and time zones. There are several problems in the fifth chapter on this topic, and although no compiler supports these yet, you can solve them using the date library, based on which the new standard additions have been designed. Many other libraries are used for solving problems in the book. The list includes Asio, Crypto++, Curl, NLohmann/json, PDF-Writer, PNGWriter, pugixml, SQLite, and ZipLib. Also, as an alternative to the std::optional and the filesystem libraries used throughout the book, you can use Boost with compilers where these are not available. All these libraries are open source and cross-platform. They were chosen for reasons that include performance, good documentation, and wide use within the community. However, you are free to use any other libraries you would like to solve the problems.

Who this book is for

Are you trying to learn C++ and are looking for challenges to practice what you're learning? If so, this book is for you. The book is intended for people learning C++, regardless of their experience with other programming languages, as a valuable resource of practical exercises and real-world problems. This book does not teach you the features of the language or the standard library. You are expected to learn that from other resources, such as books, articles, or video tutorials. This book is a learning companion and challenges you to solve tasks of various difficulties, utilizing the skills you have previously learned from other resources. Nevertheless, many of the problems proposed in this book are language agnostic, and you can use them when learning other programming languages; however, in this case, you won't be benefiting from the solutions provided here.

What this book covers

Chapter 1, Math Problems, contains a series of math exercises to warm you up for the more challenging problems in the next chapters.

Chapter 2, Language Features, proposes problems for you to practice operator overloading, move semantics, user-defined literals, and template metaprogramming aspects such as variadic functions, fold expressions, and type traits.

Chapter 3Strings and Regular Expressions, has several problems for string manipulation, such as converting between strings and other data types, splitting and joining strings, and also for working with regular expressions.

Chapter 4, Streams and Filesystems, covers output stream manipulation and working with files and directories using the C++17 filesystem library.

Chapter 5, Date and Time, prepares you for the upcoming C++20 extensions to the chrono library, with several calendar and time zone problems that you can solve with the date library, on which the new standard additions are based.

Chapter 6, Algorithms and Data Structures, is one of the largest chapters and contains a variety of problems where you need to utilize the existing standard algorithms; others are where you need to implement your own general-purpose algorithms or data structures, such as circular buffer and priority queue. The chapter ends with two rather fun problems, Dawkins' Weasel program and Conway's Game of Life program, where you can learn about evolutionary algorithms and cellular automata.

Chapter 7, Concurrency, is where we use threads and asynchronous functions to implement general-purpose parallel algorithms, but also solve some real-word problems involving concurrency.

Chapter 8Design Patterns, proposes a series of problems suited to be solved with design patterns such as decorator, composite, chain of responsibility, template method, and others.

Chapter 9, Data Serialization, covers most common formats of serialized data, JSON, and XML, with several problems; but it also challenges you to create PDF files, all with the use of third-party, open-source, and cross-platform libraries.

Chapter 10, Archives, Images, and Databases, teaches you to solve problems for working with zip archives, creating PNG files for real-world problems, such as Captcha-like systems and barcodes, and embedding and utilizing SQLite databases in your applications.

Chapter 11, Cryptography, mostly covers the user of the Crypto++ library for data encryption and signing. It also challenges you to implement your own Base64 encoding and decoding utilities.

Chapter 12Networking and Services, is where you have to implement your own client-server application communicating on TCP/IP, and also consume various REST services such as bitcoin exchange rates or text translation APIs.

To get the most out of this book

As previously mentioned, you need a basic familiarity with the C++ language and the standard library in order to be able to utilize this book, or you can learn that along the way. In any case, this book will teach you how to solve problems, but it will not teach you about the language and features utilized in the solutions. You will need a compiler with C++17 support; a complete list of required libraries as well as possible compilers you can use can be found in the Software Hardware List available in the code bundle. In the following sections, you will find detailed instructions for downloading and building the code from this book.

Download the example code files

You can download the code files with the solutions to the problems in this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/The-Modern-Cpp-Challenge. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Building the code

Although a large number of 3rd party libraries are used throughout the book, all these libraries, as well as all the solutions provided in the book are cross-platform and run on all platforms. However, the code has been developed and tested with Visual Studio 2017 v15.6/7 on Windows 10 and Xcode 9.3 on Mac OS 10.13.x.

If you are using Xcode on a Mac, there are two features used in the book that are not available with the LLVM toolset included in Xcode; these are the filesystem library and std::optional. However, these have been designed based on the Boost.Filesystem and Boost.Optional libraries and the use of the mentioned standard libraries in the proposed solutions is easily interchangeable with the Boost libraries. In fact, the accompanying code is written so that it works with either of the two; controlling which one to use is done with several macros. Instructions for building either with one or another are provided below, although the same information is also available in the source archive.

In order to support most of the development environments and build systems you could use on various platforms, the code is provided with CMake scripts. These are used to generate projects or build scripts for your preferred toolset. If you do not have CMake installed on your machine, you can get it from https://cmake.org/. Below, you can find instructions for using CMake to generate Visual Studio and Xcode scripts. For other tools, please refer to the CMake documentation, if necessary.

How to generate projects for Visual Studio 2017

Do the following in order to generate Visual Studio 2017 projects to target the x86 platform:

  1. Open a command prompt and go to the build directory in the source code root folder.
  2. Execute the following CMake command:cmake -G "Visual Studio 15 2017" .. -DCMAKE_USE_WINSSL=ON -DCURL_WINDOWS_SSPI=ON -DCURL_LIBRARY=libcurl -DCURL_INCLUDE_DIR=..\libs\curl\include -DBUILD_TESTING=OFF -DBUILD_CURL_EXE=OFF -DUSE_MANUAL=OFF
  1. After completion, the Visual Studio solution can be found at build/cppchallenger.sln.

If you want to target the x64 platform instead, use the generator called "Visual Studio 15 2017 Win64". Visual Studio 2017 15.4 supports both filesystem (as an experimental library) and std::optional. If you use a previous version, or just want to use the Boost libraries instead, you can generate the projects using the following command, after you properly install Boost:

cmake -G "Visual Studio 15 2017" .. -DCMAKE_USE_WINSSL=ON -DCURL_WINDOWS_SSPI=ON -DCURL_LIBRARY=libcurl -DCURL_INCLUDE_DIR=..\libs\curl\include -DBUILD_TESTING=OFF -DBUILD_CURL_EXE=OFF -DUSE_MANUAL=OFF -DBOOST_FILESYSTEM=ON -DBOOST_OPTIONAL=ON -DBOOST_INCLUDE_DIR=<path_to_headers> -DBOOST_LIB_DIR=<path_to_libs>

Make sure that the paths to the headers and static library files do not include trailing backslashes (i.e. \).

How to generate projects for Xcode

Several solutions in the last chapter utilize the libcurl library. For SSL support, this library needs to be linked with the OpenSSL library. Do the following to install OpenSSL:

  1. Download the library from https://www.openssl.org/.
  2. Unzip the archive and, in a terminal, go to its root directory.
  3. Build and install the library with the following commands (executed in this order):./Configure darwin64-x86_64-cc shared enable-ec_nistp_64_gcc_128 no-ssl2 no-ssl3 no-comp --openssldir=/usr/local/ssl/macos-x86_64make dependsudo make install

Until std::optional and the filesystem library will be available with Xcode's Clang, you need to use Boost. Do the following to install and build the Boost libraries:

  1. Install Homebrew from https://brew.sh/.
  2. Run the following command to download and install Boost automatically.brew install boost
  3. After installation, the Boost library will be available at /usr/local/Cellar/boost/1.65.0.

In order to generate projects for Xcode from the sources you have to:

  1. Open a terminal and go to the build directory in the source code root directory.
  2. Execute the following CMake command:cmake -G Xcode .. -DOPENSSL_ROOT_DIR=/usr/local/bin -DOPENSSL_INCLUDE_DIR=/usr/local/include/ -DBUILD_TESTING=OFF -DBUILD_CURL_EXE=OFF -DUSE_MANUAL=OFF -DBOOST_FILESYSTEM=ON -DBOOST_OPTIONAL=ON -DBOOST_INCLUDE_DIR=/usr/local/Cellar/boost/1.65.0 -DBOOST_LIB_DIR=/usr/local/Cellar/boost/1.65.0/lib
  3. After completion, the Xcode project can be found at build/cppchallenger.xcodeproj.

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

int main()
{
   std::cout << "Hello, World!\n";
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

template<typename C, typename... Args>
void push_back(C& c, Args&&... args)
{
   (c.push_back(args), ...);
}

Any command-line input or output is written as follows:

$ mkdir build
$ cd build

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."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

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 would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

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 authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images