77,99 €
Developing expert level application development skills with C++
C++ has come a long way and has now been adopted in several contexts. Its key strengths are its software infrastructure and resource-constrained applications. The C++ 17 release will change the way developers write code, and this course will help you master your developing skills with C++. With real-world, practical examples explaining each concept, the course is divided into three modules where will begin by introducing you to the latest features in C++ 17. It encourages clean code practices in C++ in general and demonstrates the GUI app-development options in C++. You’ll get tips on avoiding memory leaks using smart-pointers.
In the next module, you’ll see how multi-threaded programming can help you achieve concurrency in your applications. We start with a brief introduction to the fundamentals of multithreading and concurrency concepts. We then take an in-depth look at how these concepts work at the hardware-level as well as how both operating systems and frameworks use these low-level functions.
You will learn about the native multithreading and concurrency support available in C++ since the 2011 revision, synchronization and communication between threads, debugging concurrent C++ applications, and the best programming practices in C++.
Moving on, you’ll get an in-depth understanding of the C++ Standard Template Library. Where we show implementation-specific, problem-solution approach that will help you quickly overcome hurdles. You will learn the core STL concepts, such as containers, algorithms, utility classes, lambda expressions, iterators, and more while working on practical real-world recipes. These recipes will help you get the most from the STL and show you how to program in a better way.
Jeganathan Swaminathan : Mastering C++ Programming
Maya Posch : Mastering C++ Multithreading
Jacek Galowicz : C++17 STL Cookbook
This course is for intermediate to advanced level C++ developers who want to get the most out of C++ to build concurrent and scalable application.
Jeganathan Swaminathan, Jegan for short, is a freelance software consultant and founder of TekTutor, with over 17 years of IT industry experience. In the past, he has worked for AMD, Oracle, Siemens, Genisys Software, Global Edge Software Ltd, and PSI Data Systems. He has consulted for Samsung WTD (South Korea) and National Semiconductor (Bengaluru). He now works as a freelance external consultant for Amdocs (India). He works as freelance software consultant and freelance corporate trainer. He holds CSM, CSPO, CSD, and CSP certifications from Scrum Alliance. He is a polyglot software professional and his areas of interest include a wide range of C++, C#, Python, Ruby, AngularJS, Node.js, Kubernetes, Ansible, Puppet, Chef, and Java technologies. He is well known for JUnit, Mockito, PowerMock, gtest, gmock, CppUnit, Cucumber, SpecFlow, Qt, QML, POSIX – Pthreads, TDD, BDD, ATDD, NoSQL databases (MongoDB and Cassandra), Apache Spark, Apache Kafka, Apache Camel, Dockers, Continuous Integration (CI), Continuous Delivery (CD), Maven, Git, cloud computing, and DevOps. You can reach him for any C++, Java, Qt, QML, TDD, BDD, and DevOps-related training or consulting assignments. Jegan is a regular speaker at various technical conferences. Maya Posch is a software engineer by trade and a self-professed electronics, robotics, and AI nut, running her own software development company, Nyanko, with her good friend, Trevor Purdy, where she works on various game development projects and some non-game projects. Apart from this, she does various freelance jobs for companies around the globe. You can visit her LinkedIn profile for more work-related details. Aside from writing software, she likes to play with equations and write novels, such as her awesome reimagining of the story of the Nintendo classic, Legend of Zelda: Ocarina of Time, and the survival-horror novel she recently started, Viral Desire. You can check out her Scribd profile for a full listing of her writings. Maya is also interested in biochemistry, robotics, and reverse-engineering of the human body. To know more about her, visit her blog, Artificial Human. If there's anything she doesn't lack, it has to be sheer ambition, it seems. Jacek Galowicz obtained his master of science in electrical engineering/computer engineering at RWTH Aachen University, Germany. While at university, he enjoyed working as a student assistant in teaching and research, and he participated in several scientific publications. During and after his studies, he worked as a freelancer and implemented applications as well as kernel drivers in C and C++, touching various areas, including 3D graphics programming, databases, network communication, and physics simulation. In recent years, he has been programming performance- and security-sensitive microkernel operating systems for Intel x86 virtualization at Intel and FireEye in Braunschweig, Germany. He has a strong passion for modern C++ implementations of low-level software, and he tries hard to combine high performance with an elegant coding style. Learning purely functional programming and Haskell in recent years triggered his drive to implement generic code with the aid of meta programming.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1118
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this learning path may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this learning path to ensure the accuracy of the information presented. However, the information contained in this learning path is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this learning path.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this learning path by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Authors: Jeganathan Swaminathan, Maya Posch, Jacek GalowiczReviewer: Brandon James, Louis E. Mauget, Arne Mertz Content Development Editor: Priyanka SawantGraphics: Jisha ChirayalProduction Coordinator: Nilesh Mohite
Published on: April 2018
Production reference: 1060418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-139-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Title Page - Courses
Copyright and Credits - Courses
Expert C++ Programming
Packt Upsell - Courses
Why subscribe?
PacktPub.com
Preface
Who this learning path is for
What this learning path covers
To get the most out of this learning path
Download the example code files
Conventions used
Get in touch
Reviews
Mastering C++ Programming
Introduction to C++17 Standard Template Library
The Standard Template Library architecture
Algorithms
Iterators
Containers
Functors
Sequence containers
Array
Code walkthrough
Commonly used APIs in an array
Vector 
Code walkthrough
Commonly used vector APIs
Code walkthrough
Pitfalls of a vector
List 
Commonly used APIs in a list
Forward list
Code walkthrough
Commonly used APIs in a forward_list container
Deque
Commonly used APIs in a deque
Associative containers
Set
Code walkthrough
Commonly used APIs in a set
Map
Code walkthrough
Commonly used APIs in a map
Multiset
Multimap
Unordered sets
Unordered maps
Unordered multisets
Unordered multimaps
Container adapters
Stack
Commonly used APIs in a stack
Queue
Commonly used APIs in a queue
Priority queue
Commonly used APIs in a priority queue
Summary
Template Programming
Generic programming
Function templates
Code walkthrough
Overloading function templates
Code walkthrough
Class template
Code walkthrough
Explicit class specializations
Code walkthrough
Partial template specialization
Summary
Smart Pointers
Memory management
Issues with raw pointers
Smart pointers
auto_ptr
Code walkthrough - Part 1
Code walkthrough - Part 2
unique_ptr
Code walkthrough
shared_ptr
Code walkthrough
weak_ptr
Circular dependency
Summary
Developing GUI Applications in C++
Qt 
Installing Qt 5.7.0 in Ubuntu 16.04
Qt Core
Writing our first Qt console application
Qt Widgets
Writing our first Qt GUI application
Layouts
Writing a GUI application with a horizontal layout
Writing a GUI application with a vertical layout
Writing a GUI application with a box layout
Writing a GUI application with a grid layout
Signals and slots
Using stacked layout in Qt applications
Writing a simple math application combining multiple layouts
Summary
Test-Driven Development
TDD
Common myths and questions around TDD
Does it take more efforts for a developer to write a unit test? 
Is code coverage metrics good or bad?
Does TDD work for complex legacy projects? 
Is TDD even applicable for embedded or products that involve hardware?
Unit testing frameworks for C++
Google test framework
Installing Google test framework on Ubuntu
How to build google test and mock together as one single static library without installing?
Writing our first test case using the Google test framework
Using Google test framework in Visual Studio IDE
TDD in action
Testing a piece of legacy code that has dependency
Summary
Behavior-Driven Development
Behavior-driven development
TDD versus BDD
C++ BDD frameworks
The Gherkin language
Installing cucumber-cpp in Ubuntu
Installing the cucumber-cpp framework prerequisite software
Building and executing the test cases
Feature file
Spoken languages supported by Gherkin
The recommended cucumber-cpp project folder structure
Writing our first Cucumber test case
Integrating our project in cucumber-cpp CMakeLists.txt
Executing our test case
Dry running your cucumber test cases
BDD - a test-first development approach
Let's build and run our BDD test case
It's testing time!
Summary
Code Smells and Clean Code Practices
Code refactoring
Code smell
What is agile?
SOLID design principle
Single responsibility principle
Open closed principle
Liskov substitution principle
Interface segregation
Dependency inversion
Code smell
Comment smell
Long method
Long parameter list
Duplicate code
Conditional complexity
Large class
Dead code
Primitive obsession
Data class
Feature envy
Summary
Mastering C++ Multithreading
Revisiting Multithreading
Getting started
The multithreaded application
Makefile
Other applications
Summary
Multithreading Implementation on the Processor and OS
Introduction to POSIX pthreads
Creating threads with the pthreads library
How to compile and run
Does C++ support threads natively?
Defining processes and threads
Tasks in x86 (32-bit and 64-bit)
Process state in ARM
The stack
Defining multithreading
Flynn's taxonomy
Symmetric versus asymmetric multiprocessing
Loosely and tightly coupled multiprocessing
Combining multiprocessing with multithreading
Multithreading types
Temporal multithreading
Simultaneous multithreading (SMT)
Schedulers
Tracing the demo application
Mutual exclusion implementations
Hardware
Software
Concurrency
How to compile and run
Asynchronous message passing using the concurrency support library
How to compile and run
Concurrency tasks
How to compile and run
Using tasks with a thread support library
How to compile and run
Binding the thread procedure and its input to packaged_task 
How to compile and run
Exception handling with the concurrency library
How to compile and run
What did you learn?
Summary
C++ Multithreading APIs
API overview
POSIX threads
Windows support
PThreads thread management
Mutexes
Condition variables
Synchronization
Semaphores
Thread local storage (TLC)
Windows threads
Thread management
Advanced management
Synchronization
Condition variables
Thread local storage
Boost
Thread class
Thread pool
Thread local storage (TLS)
Synchronization
C++ threads
Putting it together
Summary
Thread Synchronization and Communication
Safety first
The scheduler
High-level view
Implementation
Request class
Worker class
Dispatcher
Makefile
Output
Sharing data
Using r/w-locks
Using shared pointers
Summary
Native C++ Threads and Primitives
The STL threading API
Boost.Thread API
The 2011 standard
C++14
Thread class
Basic use
Passing parameters
Return value
Moving threads
Thread ID
Sleeping
Yield
Detach
Swap
Mutex
Basic use
Non-blocking locking
Timed mutex
Lock guard
Unique lock
Scoped lock
Recursive mutex
Recursive timed mutex
Shared mutex
Shared timed mutex
Condition variable
Condition_variable_any
Notify all at thread exit
Future
Promise
Shared future
Packaged_task
Async
Launch policy
Atomics
Summary
Debugging Multithreaded Code
When to start debugging
The humble debugger
GDB
Debugging multithreaded code
Breakpoints
Back traces
Dynamic analysis tools
Limitations
Alternatives
Memcheck
Basic use
Error types
Illegal read / illegal write errors
Use of uninitialized values
Uninitialized or unaddressable system call values
Illegal frees
Mismatched deallocation
Overlapping source and destination
Fishy argument values
Memory leak detection
Helgrind
Basic use
Misuse of the pthreads API
Lock order problems
Data races
DRD
Basic use
Features
C++11 threads support
Summary
Best Practices
Proper multithreading
Wrongful expectations - deadlocks
Being careless - data races
Mutexes aren't magic
Locks are fancy mutexes
Threads versus the future
Static order of initialization
Summary
Atomic Operations - Working with the Hardware
Atomic operations
Visual C++
GCC
Memory order
Other compilers
C++11 atomics
Example
Non-class functions
Example
Atomic flag
Memory order
Relaxed ordering
Release-acquire ordering
Release-consume ordering
Sequentially-consistent ordering
Volatile keyword
Summary
Multithreading with Distributed Computing
Distributed computing, in a nutshell
MPI
Implementations
Using MPI
Compiling MPI applications
The cluster hardware
Installing Open MPI
Linux and BSDs
Windows
Distributing jobs across nodes
Setting up an MPI node
Creating the MPI host file
Running the job
Using a cluster scheduler
MPI communication
MPI data types
Custom types
Basic communication
Advanced communication
Broadcasting
Scattering and gathering
MPI versus threads
Potential issues
Summary
Multithreading with GPGPU
The GPGPU processing model
Implementations
OpenCL
Common OpenCL applications
OpenCL versions
OpenCL 1.0
OpenCL 1.1
OpenCL 1.2
OpenCL 2.0
OpenCL 2.1
OpenCL 2.2
Setting up a development environment
Linux
Windows
OS X/MacOS
A basic OpenCL application
GPU memory management
GPGPU and multithreading
Latency
Potential issues
Debugging GPGPU applications
Summary
C++17 STL Cookbook
The New C++17 Features
Introduction
Using structured bindings to unpack bundled return values
How to do it...
How it works...
There's more...
Limiting variable scopes to if and switch statements
How to do it...
How it works...
There's more...
Profiting from the new bracket initializer rules
How to do it...
How it works...
Letting the constructor automatically deduce the resulting template class type
How to do it...
How it works...
There's more...
Simplifying compile time decisions with constexpr-if
How to do it...
How it works...
There's more...
Enabling header-only libraries with inline variables
How it's done...
How it works...
There's more...
Implementing handy helper functions with fold expressions
How to do it...
How it works...
There's more...
Match ranges against individual items
Check if multiple insertions into a set are successful
Check if all the parameters are within a certain range
Pushing multiple items into a vector
STL Containers
Using the erase-remove idiom on std::vector
How to do it...
How it works...
There's more...
Deleting items from an unsorted std::vector in O(1) time
How to do it...
How it works...
Accessing std::vector instances the fast or the safe way
How to do it...
How it works...
There's more...
Keeping std::vector instances sorted
How to do it...
How it works...
There's more...
Inserting items efficiently and conditionally into std::map
How to do it...
How it works...
There's more...
Knowing the new insertion hint semantics of std::map::insert
How to do it...
How it works...
There's more...
Efficiently modifying the keys of std::map items
How to do it...
How it works...
There's more...
Using std::unordered_map with custom types
How to do it...
How it works...
Filtering duplicates from user input and printing them in alphabetical order with std::set
How to do it...
How it works...
std::istream_iterator
std::inserter
Putting it together
Implementing a simple RPN calculator with std::stack
How to do it...
How it works...
Stack handling
Distinguishing operands from operations from user input
Selecting and applying the right mathematical operation
There's more...
Implementing a word frequency counter with std::map
How to do it...
How it works...
Implement a writing style helper tool for finding very long sentences in text with std::multimap
How to do it...
How it works...
 There's more...
Implementing a personal to-do list using std::priority_queue
How to do it...
How it works...
Iterators
Introduction
Iterator categories
Input iterator
Forward iterator
Bidirectional iterator
Random access iterator
Contiguous iterator
Output iterator
Mutable iterator
Building your own iterable range
How to do it...
How it works...
Making your own iterators compatible with STL iterator categories
How to do it...
How it works...
There's more...
Using iterator adapters to fill generic data structures
How to do it...
How it works...
std::back_insert_iterator
std::front_insert_iterator
std::insert_iterator
std::istream_iterator
std::ostream_iterator
Implementing algorithms in terms of iterators
How to do it...
There's more...
Iterating the other way around using reverse iterator adapters
How to do it...
How it works...
Terminating iterations over ranges with iterator sentinels
How to do it...
Automatically checking iterator code with checked iterators
How to do it...
How it works...
There's more...
Building your own zip iterator adapter
How to do it...
There's more...
Ranges library
Lambda Expressions
Introduction
Defining functions on the run using lambda expressions
How to do it...
How it works...
Capture list
mutable (optional)
constexpr (optional)
exception attr (optional)
return type (optional)
Adding polymorphy by wrapping lambdas into std::function
How to do it...
How it works...
Composing functions by concatenation
How to do it...
How it works...
Creating complex predicates with logical conjunction
How to do it...
There's more...
Calling multiple functions with the same input
How to do it...
How it works...
Implementing transform_if using std::accumulate and lambdas
How to do it...
How it works...
Generating cartesian product pairs of any input at compile time
How to do it...
How it works...
STL Algorithm Basics
Introduction
Copying items from containers to other containers
How to do it...
How it works...
Sorting containers
How to do it...
How it works...
Removing specific items from containers
How to do it...
How it works...
Transforming the contents of containers
How to do it...
How it works...
Finding items in ordered and unordered vectors
How to do it...
How it works...
Limiting the values of a vector to a specific numeric range with std::clamp
How to do it...
How it works...
Locating patterns in strings with std::search and choosing the optimal implementation
How to do it...
How it works...
Sampling large vectors
How to do it...
How it works...
Generating permutations of input sequences
How to do it...
How it works...
Implementing a dictionary merging tool
How to do it...
How it works...
Advanced Use of STL Algorithms
Introduction
Implementing a trie class using STL algorithms
How to do it...
How it works...
Implementing a search input suggestion generator with tries
How to do it...
How it works...
There's more...
Implementing the Fourier transform formula with STL numeric algorithms
How to do it...
How it works...
Calculating the error sum of two vectors
How to do it...
How it works...
Implementing an ASCII Mandelbrot renderer
How to do it...
How it works...
Building our own algorithm - split
How to do it...
How it works...
There's more...
Composing useful algorithms from standard algorithms - gather
How to do it...
How it works...
Removing consecutive whitespace between words
How to do it...
How it works...
Compressing and decompressing strings
How to do it...
How it works...
There's more...
Strings, Stream Classes, and Regular Expressions
Introduction
Creating, concatenating, and transforming strings
How to do it...
How it works...
Trimming whitespace from the beginning and end of strings
How to do it...
How it works...
Getting the comfort of std::string without the cost of constructing std::string objects
How to do it...
How it works...
Reading values from user input
How to do it...
How it works...
Counting all words in a file
How to do it...
How it works...
Formatting your output with I/O stream manipulators
How to do it...
How it works...
Initializing complex objects from file input
How to do it...
How it works...
Filling containers from std::istream iterators
How to do it...
How it works...
Generic printing with std::ostream iterators
How to do it...
How it works...
Redirecting output to files for specific code sections
How to do it...
How it works...
Creating custom string classes by inheriting from std::char_traits
How to do it...
How it works...
Tokenizing input with the regular expression library
How to do it...
How it works...
Comfortably pretty printing numbers differently per context on the fly
How to do it...
Catching readable exceptions from std::iostream errors
How to do it...
How it works...
Utility Classes
Introduction
Converting between different time units using std::ratio
How to do it...
How it works...
There's more...
Converting between absolute and relative times with std::chrono
How to do it...
How it works...
Safely signalizing failure with std::optional
How to do it...
How it works...
Applying functions on tuples
How to do it...
How it works...
Quickly composing data structures with std::tuple
How to do it...
How it works...
operator<< for tuples
The zip function for tuples
Replacing void* with std::any for more type safety
How to do it...
How it works...
Storing different types with std::variant
How to do it...
How it works...
Automatically handling resources with std::unique_ptr
How to do it...
How it works...
Automatically handling shared heap memory with std::shared_ptr
How to do it...
How it works...
There's more...
Dealing with weak pointers to shared objects
How to do it...
How it works...
Simplifying resource handling of legacy APIs with smart pointers
How to do it...
How it works...
Sharing different member values of the same object
How to do it...
How it works...
Generating random numbers and choosing the right random number engine
How to do it...
How it works...
Generating random numbers and letting the STL shape specific distributions
How to do it...
How it works...
Parallelism and Concurrency
Introduction
Automatically parallelizing code that uses standard algorithms
How to do it...
How it works...
Which STL algorithms can we parallelize this way?
How do those execution policies work?
What does vectorization mean?
Putting a program to sleep for specific amounts of time
How to do it...
How it works...
Starting and stopping threads
How to do it...
How it works...
Performing exception safe shared locking with std::unique_lock and std::shared_lock
How to do it...
How it works...
Mutex classes
Lock classes
Avoiding deadlocks with std::scoped_lock
How to do it...
How it works...
Synchronizing concurrent std::cout use
How to do it...
How it works...
Safely postponing initialization with std::call_once
How to do it...
How it works...
Pushing the execution of tasks into the background using std::async
How to do it...
How it works...
There's more...
Implementing the producer/consumer idiom with std::condition_variable
How to do it...
How it works...
Implementing the multiple producers/consumers idiom with std::condition_variable
How to do it...
How it works...
Parallelizing the ASCII Mandelbrot renderer using std::async
How to do it...
How it works...
Implementing a tiny automatic parallelization library with std::future
How to do it...
How it works...
Filesystem
Introduction
Implementing a path normalizer
How to do it...
How it works...
There's more...
Getting canonical file paths from relative paths
How to do it...
How it works...
Listing all files in directories
How to do it...
How it works...
Implementing a grep-like text search tool
How to do it...
How it works...
There's more...
Implementing an automatic file renamer
How to do it...
Implementing a disk usage counter
How to do it...
How it works...
Calculating statistics about file types
How to do it...
Implementing a tool that reduces folder size by substituting duplicates with symlinks
How to do it...
How it works...
There's more...
Bibliography
Introduction to the learning path and the technology.
This learning path is for Java developers who are looking to move a level up and learn how to build robust applications in the latest version of Java.
Section 1, Mastering C++ Programming, introducing you to the latest features in C++ 17 and STL. It encourages clean code practices in C++ in general and demonstrates the GUI app-development options in C++. You’ll get tips on avoiding memory leaks using smart-pointers. Section 2, Mastering C++ Multithreading, you’ll see how multi-threaded programming can help you achieve concurrency in your applications. We start with a brief introduction to the fundamentals of multithreading and concurrency concepts. We then take an in-depth look at how these concepts work at the hardware-level as well as how both operating systems and frameworks use these low-level functions. You will learn about the native multithreading and concurrency support available in C++ since the 2011 revision, synchronization and communication between threads, debugging concurrent C++ applications, and the best programming practices in C++. Section 3, C++17 STL Cookbook, you’ll get an in-depth understanding of the C++ Standard Template Library; we show implementation-specific, problem-solution approaches that will help you quickly overcome hurdles. You will learn the core STL concepts, such as containers, algorithms, utility classes, lambda expressions, iterators, and more while working on practical real-world recipes. These recipes will help you get the most from the STL and show you how to program in a better way.
A strong understanding of C++ language is highly recommended as the book is for the experienced developers.
You will need any OS (Windows, Linux, or macOS) and any C++ compiler installed on your systems in order to get started.
You can download the example code files for this learning path from your account at www.packtpub.com. If you purchased this learning path 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:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the
learning path
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 learning path is also hosted on GitHub athttps://github.com/PacktPublishing/Learning-Path-Name. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in 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:
html, body, #map { height: 100%; margin: 0; padding: 0}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
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."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the learning path title in the subject of your message. If you have questions about any aspect of this learning path, 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 learning path, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your learning path, 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.
Please leave a review. Once you have read and used this learning path, 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.
As you know, the C++ language is the brain child of Bjarne Stroustrup, who developed C++ in 1979. The C++ programming language is standardized by International Organization for Standardization (ISO). The initial standardization was published in 1998, commonly referred to as C++98, and the next standardization C++03 was published in 2003, which was primarily a bug fix release with just one language feature for value initialization. In August 2011, the C++11 standard was published with several additions to the core language, including several significant interesting changes to the Standard Template Library (STL); C++11 basically replaced the C++03 standard. C++14 was published in December, 2014 with some new features, and later, the C++17 standard was published on July 31, 2017. At the time of writing this book, C++17 is the latest revision of the ISO/IEC standard for the C++ programming language.
This chapter requires a compiler that supports C++17 features: gcc version 7 or later. As gcc version 7 is the latest version at the time of writing this book, I'll be using gcc version 7.1.0 in this chapter.
This chapter will cover the following topics:
STL overview
STL architecture
Containers
Iterators
Algorithms
Functors
STL containers
Sequence
Associative
Unordered
Adaptors
Let's look into the STL topics one by one in the following sections.
The C++ Standard Template Library (STL) offers ready-made generic containers, algorithms that can be applied to the containers, and iterators to navigate the containers. The STL is implemented with C++ templates, and templates allow generic programming in C++.
The STL encourages a C++ developer to focus on the task at hand by freeing up the developer from writing low-level data structures and algorithms. The STL is a time-tested library that allows rapid application development.
The STL is an interesting piece of work and architecture. Its secret formula is compile-time polymorphism. To get better performance, the STL avoids dynamic polymorphism, saying goodbye to virtual functions. Broadly, the STL has the following four components:
Algorithms
Functors
Iterators
Containers
The STL architecture stitches all the aforementioned four components together. It has many commonly used algorithms with performance guarantees. The interesting part about STL algorithms is that they work seamlessly without any knowledge about the containers that hold the data. This is made possible due to the iterators that offer high-level traversal APIs, which completely abstracts the underlying data structure used within a container. The STL makes use of operator overloading quite extensively. Let's understand the major components of STL one by one to get a good grasp of the STL conceptually.
The STL algorithms are powered by C++ templates; hence, the same algorithm works irrespective of what data type it deals with or independently of how the data is organized by a container. Interestingly, the STL algorithms are generic enough to support built-in and user-defined data types using templates. As a matter of fact, the algorithms interact with the containers via iterators. Hence, what matters to the algorithms is the iterator supported by the container. Having said that, the performance of an algorithm depends on the underlying data structure used within a container. Hence, certain algorithms work only on selective containers, as each algorithm supported by the STL expects a certain type of iterator.
STL containers are objects that typically grow and shrink dynamically. Containers use complex data structures to store the data under the hood and offer high-level functions to access the data without us delving into the complex internal implementation details of the data structure. STL containers are highly efficient and time-tested.
Every container uses different types of data structures to store, organize, and manipulate data in an efficient way. Though many containers may seem similar, they behave differently under the hood. Hence, the wrong choice of containers leads to application performance issues and unnecessary complexities.
Containers come in the following flavors:
Sequential
Associative
Container adapters
The objects stored in the containers are copied or moved, and not referenced. We will explore every type of container in the upcoming sections with simple yet interesting examples.
The STL supports quite an interesting variety of sequence containers. Sequence containers store homogeneous data types in a linear fashion, which can be accessed sequentially. The STL supports the following sequence containers:
Arrays
Vectors
Lists
forward_list
deque
As the objects stored in an STL container are nothing but copies of the values, the STL expects certain basic requirements from the user-defined data types in order to hold those objects inside a container. Every object stored in an STL container must provide the following as a minimum requirement:
A default constructor
A copy constructor
An assignment operator
Let's explore the sequence containers one by one in the following subsections.
The following table shows some commonly used vector APIs:
API
Description
at ( int index )
This returns the value stored at the indexed position. It throws the std::out_of_range exception if the index is invalid.
operator [ int index ]
This returns the value stored at the indexed position. It is faster than at( int index ), since no bounds checking is performed by this function.
front()
This returns the first value stored in the vector.
back()
This returns the last value stored in the vector.
empty()
This returns true if the vector is empty, and false otherwise.
size()
This returns the number of values stored in the vector.
reserve( int size )
This reserves the initial size of the vector. When the vector size has reached its capacity, an attempt to insert new values requires vector resizing. This makes the insertion consume O(N) runtime complexity. The reserve() method is a workaround for the issue described.
capacity()
This returns the total capacity of the vector, while the size is the actual value stored in the vector.
clear()
This clears all the values.
push_back<data_type>( value )
This adds a new value at the end of the vector.
It would be really fun and convenient to read and print to/from the vector using istream_iterator and ostream_iterator. The following code demonstrates the use of a vector:
#include <iostream>#include <vector>#include <algorithm>#include <iterator>using namespace std;int main () { vector<int> v; cout << "nType empty string to end the input once you are done feeding the vector" << endl; cout << "nEnter some numbers to feed the vector ..." << endl; istream_iterator<int> start_input(cin); istream_iterator<int> end_input; copy ( start_input, end_input, back_inserter( v ) ); cout << "nPrint the vector ..." << endl; copy ( v.begin(), v.end(), ostream_iterator<int>(cout, "t") ); cout << endl; return 0;}
Basically, the copy algorithm accepts a range of iterators, where the first two arguments represent the source and the third argument represents the destination, which happens to be the vector:
istream_iterator<int> start_input(cin);
istream_iterator<int> end_input;
copy ( start_input, end_input, back_inserter( v ) );
The start_input iterator instance defines an istream_iterator iterator that receives input from istream and cin, and the end_input iterator instance defines an end-of-file delimiter, which is an empty string by default (""). Hence, the input can be terminated by typing "" in the command-line input terminal.
Similarly, let's understand the following code snippet:
cout << "nPrint the vector ..." << endl;
copy ( v.begin(), v.end(), ostream_iterator<int>(cout, "t") );
cout << endl;
The copy algorithm is used to copy the values from a vector, one element at a time, to ostream, separating the output with a tab character (t).
Every STL container has its own advantages and disadvantages. There is no single STL container that works better in all the scenarios. A vector internally uses an array data structure, and arrays are fixed in size in C/C++. Hence, when you attempt to add new values to the vector at the time the vector size has already reached its maximum capacity, then the vector will allocate new consecutive locations that can accommodate the old values and the new value in a contiguous location. It then starts copying the old values into the new locations. Once all the data elements are copied, the vector will invalidate the old location.
Whenever this happens, the vector insertion will take O(N) runtime complexity. As the size of the vector grows over time, on demand, the O(N) runtime complexity will show up a pretty bad performance. If you know the maximum size required, you could reserve so much initial size upfront in order to overcome this issue. However, not in all scenarios do you need to use a vector. Of course, a vector supports dynamic size and random access, which has performance benefits in some scenarios, but it is possible that the feature you are working on may not really need random access, in which case a list, deque, or some other container may work better for you.
The following table shows the most commonly used APIs of an STL list:
API
Description
front()
This returns the first value stored in the list
back()
This returns the last value stored in the list
size()
This returns the count of values stored in the list
empty()
This returns true when the list is empty, and false otherwise
clear()
This clears all the values stored in the list
push_back<data_type>( value )
This adds a value at the end of the list
push_front<data_type>( value )
This adds a value at the front of the list
merge( list )
This merges two sorted lists with values of the same type
reverse()
This reverses the list
unique()
This removes duplicate values from the list
sort()
This sorts the values stored in a list
The following table shows the commonly used deque APIs:
API
Description
at ( int index )
This returns the value stored at the indexed position. It throws the std::out_of_range exception if the index is invalid.
operator [ int index ]
This returns the value stored at the indexed position. It is faster than at( int index ) since no bounds checking is performed by this function.
front()
This returns the first value stored in the deque.
back()
This returns the last value stored in the deque.
empty()
This returns true if the deque is empty and false, otherwise.
size()
This returns the number of values stored in the deque.
capacity()
This returns the total capacity of the deque, while size() returns the actual number of values stored in the deque.
clear()
This clears all the values.
push_back<data_type>( value )
This adds a new value at the end of the deque.
