C Standard Library Quick Reference 1st Edition
Van Weert Peter pdf download
https://textbookfull.com/product/c-standard-library-quick-reference-1st-edition-van-weert-peter/
★★★★★ 4.7/5.0 (40 reviews) ✓ 215 downloads ■ TOP RATED
"Great resource, downloaded instantly. Thank you!" - Lisa K.
DOWNLOAD EBOOK
C Standard Library Quick Reference 1st Edition Van Weert
Peter pdf download
TEXTBOOK EBOOK TEXTBOOK FULL
Available Formats
■ PDF eBook Study Guide TextBook
EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME
INSTANT DOWNLOAD VIEW LIBRARY
Collection Highlights
C# 7 Quick Syntax Reference: A Pocket Guide to the
Language, APIs, and Library Mikael Olsson
C++17 quick syntax reference: apocket guide to the
language, apis and library 2 edition Edition Olsson
C++17 quick syntax reference: a pocket guide to the
language, APIs and library Third Edition Olsson
Python Standard Library A Quickstudy Laminated Reference
Guide 1st Edition Berajah Jayne
C# 7 Quick Syntax Reference: A Pocket Guide to the
Language, APIs, and Library 2nd Edition Mikael Olsson
C++20 Quick Syntax Reference : a pocket guide to the
language, APIs, and library 4th Edition Mikael Olsson
C++20 Quick Syntax Reference A Pocket Guide to the
Language, APIs, and Library. 4th Edition Mikael Olsson
Haskell Quick Syntax Reference: A Pocket Guide to the
Language, APIs, and Library 1st Edition Stefania Loredana
Nita
Go Standard Library Cookbook 1st Edition Radomir Sohlich
T HE E X P ER T ’S VOIC E® I N C+ +
C++ Standard
Library Quick
Reference
—
Peter Van Weert
Marc Gregoire
C++
Standard Library
Quick Reference
Peter Van Weert
Marc Gregoire
C++ Standard Library Quick Reference
Peter Van Weert Marc Gregoire
Kessel-Lo, Belgium Meldert, Belgium
ISBN-13 (pbk): 978-1-4842-1875-4 ISBN-13 (electronic): 978-1-4842-1876-1
DOI 10.1007/978-1-4842-1876-1
Library of Congress Control Number: 2016941348
Copyright © 2016 by Peter Van Weert and Marc Gregoire
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part
of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission
or information storage and retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are
brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for
the purpose of being entered and executed on a computer system, for exclusive use by the purchaser
of the work. Duplication of this publication or parts thereof is permitted only under the provisions
of the Copyright Law of the Publisher’s location, in its current version, and permission for use must
always be obtained from Springer. Permissions for use may be obtained through RightsLink at the
Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and
images only in an editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they
are not identified as such, is not to be taken as an expression of opinion as to whether or not they are
subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility
for any errors or omissions that may be made. The publisher makes no warranty, express or implied,
with respect to the material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Steve Anglin
Technical Reviewer: Bart Vandewoestyne
Editorial Board: Steve Anglin, Pramila Balan, Louise Corrigan, Jonathan Gennick, Robert
Hutchinson, Celestin Suresh John, Michelle Lowman, James Markham, Susan McDermott,
Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing
Coordinating Editor: Mark Powers
Copy Editor: Tiffany Taylor
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM
Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional
use. eBook versions and licenses are also available for most titles. For more information, reference
our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text is available
to readers at www.apress.com/9781484218754. For detailed information about how to locate your
book’s source code, go to www.apress.com/source-code/. Readers can also access source code at
SpringerLink in the Supplementary Material section for each chapter.
Printed on acid-free paper
To my parents and my brother and his wife.
Their support and patience helped me in finishing this book.
—Marc Gregoire
In loving memory of Jeroen. Your enthusiasm and courage
will forever remain an inspiration to us all.
—Peter Van Weert
Contents at a Glance
About the Authors............................................................................ xv
About the Technical Reviewer ....................................................... xvii
Introduction .................................................................................... xix
■Chapter 1: Numerics and Math ....................................................... 1
■Chapter 2: General Utilities ........................................................... 23
■Chapter 3: Containers ................................................................... 51
■Chapter 4: Algorithms .................................................................. 81
■Chapter 5: Stream I/O ................................................................. 101
■Chapter 6: Characters and Strings ............................................. 125
■Chapter 7: Concurrency .............................................................. 161
■Chapter 8: Diagnostics ............................................................... 183
■Appendix A: Standard Library Headers ...................................... 195
Index .............................................................................................. 201
v
Contents
About the Authors............................................................................ xv
About the Technical Reviewer ....................................................... xvii
Introduction .................................................................................... xix
■Chapter 1: Numerics and Math ....................................................... 1
Common Mathematical Functions.............................................. <cmath> 1
Basic Functions ........................................................................................................ 1
Exponential and Logarithmic Functions ................................................................... 2
Power Functions ....................................................................................................... 2
Trigonometric and Hyperbolic Functions .................................................................. 2
Error and Gamma Functions ..................................................................................... 3
Integral Rounding of Floating-Point Numbers .......................................................... 3
Floating-Point Manipulation Functions ..................................................................... 3
Classification and Comparison Functions................................................................. 4
Error Handling........................................................................................................... 5
Fixed-Width Integer Types .......................................................<cstdint> 5
Arithmetic Type Properties ...................................................... <limits> 5
Complex Numbers ..................................................................<complex> 8
Compile-Time Rational Numbers .............................................. <ratio> 9
Random Numbers................................................................... <random> 10
Random Number Generators .................................................................................. 10
Random Number Distributions ............................................................................... 13
vii
■ CONTENTS
Numeric Arrays.................................................................... <valarray> 17
std::slice ........................................................................................................... 19
std::gslice......................................................................................................... 20
std::mask_array ................................................................................................ 21
std::indirect_array ........................................................................................ 21
■Chapter 2: General Utilities ........................................................... 23
Moving, Forwarding, Swapping .............................................<utility> 23
Moving .................................................................................................................... 23
Forwarding ............................................................................................................. 25
Swapping ................................................................................................................ 26
Pairs and Tuples .................................................................................... 26
Pairs.................................................................................................... <utility> 26
Tuples ..................................................................................................... <tuple> 27
Relational Operators ..............................................................<utility> 28
Smart Pointers ....................................................................... <memory> 28
Exclusive-Ownership Pointers ................................................................................ 29
Shared-Ownership Pointers.................................................................................... 31
Function Objects ............................................................. <functional> 33
Reference Wrappers ............................................................................................... 34
Predefined Functors ............................................................................................... 34
Generic Function Wrappers .................................................................................... 35
Binding Function Arguments .................................................................................. 36
Functors for Class Members................................................................................... 37
Initializer Lists ....................................................... <initializer_list> 39
Date and Time Utilities ........................................................... <chrono> 39
Durations ................................................................................................................ 40
Time Points ............................................................................................................. 41
Clocks ..................................................................................................................... 41
C-style Date and Time Utilities ............................................................... <ctime> 42
viii
■ CONTENTS
C-Style File Utilities ................................................................ <cstdio> 45
Type Utilities .......................................................................................... 45
Runtime Type Identification ..................................... <typeinfo>, <typeindex> 45
Type Traits ...................................................................................<type_traits> 46
■Chapter 3: Containers ................................................................... 51
Iterators ............................................................................... <iterator> 51
Iterator Tags ............................................................................................................ 52
Non-Member Functions to Get Iterators ................................................................. 53
Non-Member Operations on Iterators ..................................................................... 54
Sequential Containers ........................................................................... 54
std::vector....................................................................................... <vector> 54
std::deque ........................................................................................... <deque> 60
std::array ........................................................................................... <array> 60
std::list and std::forward_list ......................<list>, <forward_list> 61
Sequential Containers Reference ........................................................................... 63
std::bitset....................................................................................... <bitset> 66
Container Adaptors ................................................................................ 67
std::queue ........................................................................................... <queue> 68
std::priority_queue ........................................................................ <queue> 68
std::stack ........................................................................................... <stack> 69
Example .................................................................................................................. 69
Reference ............................................................................................................... 70
Ordered Associative Containers ............................................................ 71
std::map and std::multimap .................................................................<map> 71
std::set and std::multiset .................................................................<set> 72
Searching ............................................................................................................... 72
Order of Elements ................................................................................................... 73
Complexity .............................................................................................................. 73
Reference ............................................................................................................... 73
ix
■ CONTENTS
Unordered Associative Containers .... <unordered_map>, <unordered_set> 75
Hash Map................................................................................................................ 76
Template Type Parameters ..................................................................................... 76
Hash Functions ....................................................................................................... 76
Complexity .............................................................................................................. 77
Reference ............................................................................................................... 77
Allocators .............................................................................................. 79
■Chapter 4: Algorithms .................................................................. 81
Input and Output Iterators ..................................................................... 81
Algorithms ......................................................................... <algorithm> 82
Terminology ............................................................................................................ 82
General Guidelines.................................................................................................. 82
Applying a Function on a Range ............................................................................. 83
Checking for the Presence of Elements.................................................................. 84
Finding Elements .................................................................................................... 84
Binary Search ......................................................................................................... 85
Subsequence Search .............................................................................................. 86
Min/Max.................................................................................................................. 87
Sequence Comparison ............................................................................................ 88
Copy, Move, Swap ................................................................................................... 88
Generating Sequences............................................................................................ 89
Removing and Replacing ........................................................................................ 90
Reversing and Rotating .......................................................................................... 91
Partitioning ............................................................................................................. 92
Sorting .................................................................................................................... 93
Shuffling ................................................................................................................. 94
Operations on Sorted Ranges ................................................................................. 95
x
■ CONTENTS
Permutation ............................................................................................................ 96
Heaps...................................................................................................................... 97
Numeric Algorithms ............................................................................ <numeric> 98
Iterator Adaptors ................................................................. <iterator> 99
■Chapter 5: Stream I/O ................................................................. 101
Input and Output with Streams ........................................................... 101
Helper Types ..............................................................................................<ios> 102
std::ios_base .......................................................................................<ios> 103
I/O Manipulators ..................................................................<ios>, <iomanip> 105
Example ................................................................................................................ 106
std::ios ..................................................................................................<ios> 106
std::ostream................................................................................. <ostream> 108
std::istream................................................................................. <istream> 110
std::iostream .............................................................................. <istream> 112
String Streams ....................................................................<sstream> 112
Example ................................................................................................................ 113
File Streams ........................................................................<fstream> 113
Example ................................................................................................................ 114
operator<< and >> for Custom Types ............................................... 115
Stream Iterators ............................................................... <iterator> 115
std::ostream_iterator .................................................................................. 115
std::istream_iterator .................................................................................. 116
Stream Buffers ............................................................... <streambuf> 117
C-Style Output and Input ...................................................... <cstdio> 117
std::printf() Family ....................................................................................... 118
std::scanf() Family ......................................................................................... 122
xi
■ CONTENTS
■Chapter 6: Characters and Strings ............................................. 125
Strings .................................................................................. <string> 125
Searching in Strings ............................................................................................. 126
Modifying Strings ................................................................................................. 127
Constructing Strings ............................................................................................. 128
String Length ........................................................................................................ 128
Copying (Sub)Strings ............................................................................................ 128
Comparing Strings ................................................................................................ 129
String Conversions ............................................................................................... 129
Character Classification ...................................... <cctype>, <cwctype> 130
Character-Encoding Conversion .......................... <locale>, <codecvt> 131
Localization .......................................................................... <locale> 134
Locale Names ....................................................................................................... 134
The Global Locale ................................................................................................. 135
Basic std::locale Members ............................................................................. 136
Locale Facets........................................................................................................ 136
Combining and Customizing Locales .................................................................... 145
C Locales .......................................................................................... <clocale> 147
Regular Expressions ............................................................... <regex> 148
The ECMAScript Regular Expression Grammar .................................................... 149
Regular Expression Objects .................................................................................. 153
Matching and Searching Patterns ........................................................................ 155
Match Iterators ..................................................................................................... 158
Replacing Patterns ............................................................................................... 159
xii
■ CONTENTS
■Chapter 7: Concurrency .............................................................. 161
Threads ................................................................................ <thread> 161
Launching a New Thread ...................................................................................... 161
A Thread’s Lifetime ............................................................................................... 162
Thread Identifiers ................................................................................................. 162
Utility Functions .................................................................................................... 163
Exceptions ............................................................................................................ 163
Futures ................................................................................. <future> 164
Return Objects ...................................................................................................... 164
Providers............................................................................................................... 165
Exceptions ............................................................................................................ 167
Mutual Exclusion .................................................................... <mutex> 168
Mutexes and Locks ............................................................................................... 168
Mutex Types .......................................................................................................... 170
Lock Types ............................................................................................................ 171
Locking Multiple Mutexes..................................................................................... 172
Exceptions ............................................................................................................ 173
Calling a Function Once ........................................................................ <mutex> 173
Condition Variables ...........................................<condition_variable> 174
Waiting for a Condition ......................................................................................... 174
Notification ........................................................................................................... 175
Exceptions ............................................................................................................ 176
Synchronization................................................................................... 176
Atomic Operations ................................................................ <atomic> 178
Atomic Variables ................................................................................................... 178
Atomic Flags ......................................................................................................... 181
Nonmember Functions ......................................................................................... 181
Fences .................................................................................................................. 182
xiii
■ CONTENTS
■Chapter 8: Diagnostics ............................................................... 183
Assertions ...........................................................................<cassert> 183
Exceptions ...................................................<exception>, <stdexcept> 184
Exception Pointers........................................................... <exception> 184
Nested Exceptions ........................................................... <exception> 186
System Errors ............................................................. <system_error> 187
std::error_category ...................................................................................... 188
std::error_code .............................................................................................. 188
std::error_condition .................................................................................... 189
C Error Numbers ................................................................... <cerrno> 190
Failure Handling .............................................................. <exception> 190
std::uncaught_exception() ......................................................................... 190
std::terminate() ............................................................................................ 191
std::unexpected() .......................................................................................... 191
■Appendix A: Standard Library Headers ...................................... 195
Numerics and Math (Chapter 1) .......................................................... 195
General Utilities (Chapter 2) ................................................................ 196
Containers (Chapter 3) ........................................................................ 197
Algorithms (Chapter 4) ........................................................................ 197
Stream I/O (Chapter 5)......................................................................... 198
Characters and Strings (Chapter 6) ..................................................... 199
Concurrency (Chapter 7)...................................................................... 199
Diagnostics (Chapter 8) ....................................................................... 200
The C Standard Library........................................................................ 200
Index .............................................................................................. 201
xiv
About the Authors
Peter Van Weert is a Belgian software engineer whose
main interest and expertise are programming
languages, algorithms, and data structures.
He received his master’s of science in computer
science summa cum laude with congratulations of the
Board of Examiners from the University of Leuven. In 2010,
he completed his PhD thesis on the design and efficient
compilation of rule-based programming languages at the
research group for declarative programming languages
and artificial intelligence of the same university.
During his doctoral studies, he was a teaching assistant for
object-oriented programming (Java), software analysis and
design, and declarative programming.
After graduating, Peter joined Nikon Metrology to work on large-scale, industrial
application software in the area of 3D laser scanning and point cloud inspection. At
Nikon, he has mastered C++ and refactoring and debugging of very large code bases
and has gained further proficiency in all aspects of the software development process,
including the analysis of functional and technical requirements, and agile and scrum-
based project and team management.
In his spare time, he has co-authored two award-winning Windows 8 apps, and he is
a regular speaker at and board member of the Belgian C++ Users Group.
Marc Gregoire is a software engineer from Belgium.
He graduated from the University of Leuven, Belgium,
with a degree in “Burgerlijk ingenieur in de computer
wetenschappen” (equivalent to a master’s of science in
engineering in computer science). The year after, he
received the cum laude degree of master’s in artificial
intelligence at the same university. After his studies,
Marc started working for a software consultancy
company called Ordina Belgium. As a consultant, he
worked for Siemens and Nokia Siemens Networks on
critical 2G and 3G software running on Solaris for
telecom operators. This required working in
international teams stretching from South America and
USA to EMEA and Asia. Now, Marc is working for Nikon
Metrology on industrial 3D laser scanning software.
xv
■ ABOUT THE AUTHORS
His main expertise is C/C++, specifically Microsoft VC++ and the MFC framework.
He has experience in developing C++ programs running 24/7 on Windows and Linux
platforms: for example, KNX/EIB home automation software. In addition to C/C++,
Marc also likes C# and uses PHP for creating web pages.
Since April 2007, he has received the yearly Microsoft MVP (Most Valuable
Professional) award for his Visual C++ expertise.
Marc is the founder of the Belgian C++ Users Group (www.becpp.org), author of
Professional C++, and a member on the CodeGuru forum (as Marc G). He maintains a
blog at www.nuonsoft.com/blog/.
xvi
About the Technical
Reviewer
Bart Vandewoestyne is an enthusiastic, solo-parenting
software engineer living in Belgium. After obtaining his
master’s degree from the Computer Science
department at the University of Leuven, he worked as a
researcher in the numerical analysis and applied
mathematics section of that same university. He
successfully completed his PhD in 2008. Three years of
postdoctoral work later, Bart left the academic world for
industry. He now works as a senior development
software engineer for Esterline Belgium, where he
develops and maintains software for professional
flight-simulator alignment.
Bart enjoys reading about and exploring all aspects
of C++ software development. In his spare time, and
when he’s away from his keyboard, he enjoys running,
swimming, paragliding, and spending quality time with
his now 6-year-old son Jenne. He wants the world to
know how much he cares about Jenne, and he hopes
that his child will also transform his passion into his
profession.
xvii
Introduction
The C++ Standard Library
The C++ Standard Library is a collection of essential classes and functions used by
millions of C++ programmers on a daily basis. Being part of the ISO Standard of the
C++ Programming Language, an implementation is distributed with virtually every
C++ compiler. Code written with the C++ Standard Library is therefore portable across
compilers and target platforms.
The Library is more than 20 years old. Its initial versions were heavily inspired by
a (then proprietary) C++ library called the Standard Template Library (STL), so much
so that many still incorrectly refer to the Standard Library as “the STL.” The STL library
pioneered generic programming with templated data structures called containers and
algorithms, glued together with the concept of iterators. Most of this work was adapted by
the C++ standardization committee, but nevertheless neither library is a true superset of
the other.
The C++ Standard Library today is much more than the STL containers and
algorithms. For decades, it has featured STL-like string classes, extensive localization
facilities, and a stream-based I/O library, as well as all headers of the C Standard Library.
In recent years, the C++11 and C++14 editions of the ISO standard have added, among
other things, hash map containers, generic smart pointers, a versatile random-number-
generation framework, a powerful regular expression library, more expressive utilities
for function-style programming, type traits for template metaprogramming, and a
portable concurrency library featuring threads, mutexes, condition variables, and atomic
variables. Many of these libraries are based on Boost, a collection of open-source C++
libraries.
And this is just the beginning: the C++ community has rarely been as active and alive
as in the past few years. The next version of the Standard, tentatively called C++17, is
expected to add even more essential classes and functions.
Why This Book?
Needless to say, it is hard to know and remember all the possibilities, details, and
intricacies of the vast and growing C++ Standard Library. This handy reference guide
offers a condensed, well-structured summary of all essential aspects of the C++ Standard
Library and is therefore indispensable to any C++ programmer.
You could consult the Standard itself, but it is written in a very detailed, technical
style and is primarily targeted at Library implementors. Moreover, it is very long: the C++
Standard Library chapters alone are over 750 pages in length, and those on the
xix
■ INTRODUCTION
C Standard Library encompass another 250 pages. Other reference guides exist but are
often outdated, limited (most cover little more than the STL containers and algorithms),
or not much shorter than the Standard itself.
This book covers all important aspects of the C++14 and C11 Standard Libraries,
some in more detail than others, and always driven by their practical usefulness. You will
not find page-long, repetitive examples; obscure, rarely used features; or bloated, lengthy
explanations that could be summarized in just a few bullets. Instead, this book strives to
be exactly that: a summary. Everything you need to know and watch out for in practice is
outlined in a compact, to-the-point style, interspersed with practical tips and short,
well-chosen, clarifying examples.
Who Should Read This Book?
The book is targeted at all C++ programmers, regardless of their proficiency with the
language or the Standard Library. If you are new to C++, its tutorial aspects will quickly
bring you up to speed with the C++ Standard Library. Even the most experienced C++
programmer, however, will learn a thing or two from the book and find it an indispensable
reference and memory aid. The book does not explain the C++ language or syntax itself,
but is accessible to anyone with basic C++ knowledge or programming experience.
What You Will Learn
• How to use the powerful random-number-generation facilities
• How to work with dates and times
• What smart pointers are and how to use them to prevent memory leaks
• How to use containers to efficiently store and retrieve your data
• How to use algorithms to inspect and manipulate your data
• How lambda expressions allow for elegant use of algorithms
• What functionality the library provides for file and
stream-based I/O
• How to work with characters and strings in C++
• How to write localized applications
• How to write safe and efficient multithreaded code using the C++11
concurrency library
• How to correctly handle error conditions and exceptions
• And more!
xx
■ INTRODUCTION
General Remarks
• All types, classes, functions, and constants of the C++ Standard Library
are defined in the std namespace (short for standard).
• All C++ Standard Library headers must be included using #include
<header> (note: no .h suffix!).
• All C Standard Library headers are available to C++ programmers in a
slightly modified form by including <cheader> (note the c prefix).1 The
most notable difference between the C++ headers and their original C
counterparts is that all functionality is defined in the std namespace.
Whether it is also provided in the global namespace is up to the
implementation: portable code should therefore use the std namespace
at all times.
• This book generally only covers the C headers if there are no more
modern, C++-style alternatives provided by the C++ Standard Library.
• More advanced, rarely used topics such as custom memory allocators are
not covered.
Code Examples
To compile and execute the code examples given throughout the book, all you need is
a sufficiently recent C++ compiler. We leave the choice of compiler entirely up to you,
and we further assume you can compile and execute basic C++ programs. All examples
contain standard, portable C++ code only and should compile with any C++ compiler
that is compliant with the C++14 version of the Standard. We occasionaly indicate known
limitations of major compilers, but this is not a real goal of this book. In case of problems,
please consult your implementation’s documentation.
Unless otherwise noted, code examples can be copied as is and put inside the main()
function of a basic command-line application. Generally, only two headers have to be
included to make a code snippet compile: the one being discussed in the context where
the example is given, and <iostream> for the command-line output statements (explained
shortly). If any other header is required, we try to indicate so in the text. Should we
forget, the appendix provides a brief overview of all headers of the Standard Library and
their contents. Additionally, you can download compilable source code files for all code
snippets from this book from the Apress website (www.apress.com/9781484218754).
1
The original C headers may still be included with <header.h>, but their use is deprectated.
xxi
■ INTRODUCTION
Following is the obligatory first example (for once, we show the full program):
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
Many code samples, including those in earlier chapters, write to the standard output
console using std::cout and the << stream operator, even though these facilities of the
C++ I/O library are only discussed in detail in Chapter 5. The stream operator can be
used to output virtually all fundamental C++ types, and multiple values can be written
on a single line. The I/O manipulator std::endl outputs the newline character (\n) and
flushes the output for std::cout to the standard console. Straightforward usage of the
std::string class defined in <string> may occur in earlier examples as well. For instance:
More details regarding streams and strings are found in Chapters 5 and 6,
respectively, but this should suffice to get you through the examples in earlier chapters.
Common Class
The following Person class is used in code examples throughout the book to illustrate the
use of user-defined classes together with the Standard Library:
#include <string>
#include <ostream>
class Person {
public:
Person() = default;
explicit Person(const std::string& first,
const std::string& last = "", bool isVIP = false)
: m_first(first), m_last(last), m_isVIP(isVIP) {}
const std::string& GetFirstName() const { return m_first; }
void SetFirstName(const std::string& first) { m_first = first; }
const std::string& GetLastName() const { return m_last; }
void SetLastName(const std::string& last) { m_last = last; }
bool IsVIP() const { return m_isVIP; }
xxii
■ INTRODUCTION
xxiii
Chapter 1
Numerics and Math
Common Mathematical Functions <cmath>
The <cmath> header defines an extensive collection of common math functions in the
std namespace. Unless otherwise specified, all functions are overloaded to accept all
standard numerical types, with the following rules for determining the return type:
• If all arguments are float, the return type is float as well.
Analogous for double and long double inputs.
• If mixed types or integers are passed, these numbers are
converted to double, and a double is returned as well. If one of the
inputs is a long double, long double is used instead.
Basic Functions
Function Description
abs(x) Returns the absolute value of x. <cstdlib> defines abs(),
fabs(x) labs(), and llabs() for int types; that abs() has return type
int, which is different from the abs() in <cmath> (double).
fmod(x, y) Returns the remainder of x . For fmod(), the result always has
y
remainder(x, y) the same sign as x; for remainder(), that is not necessarily true.
E.g.: mod(1,4) = rem(1,4) = 1, but mod(3,4) = 3 and
rem(3,4) = -1.
remquo(x, y, *q) Returns the same value as remainder(). q is a pointer to an int
and receives a value with the sign of x y and at least the last
three bits of the integral quotient itself (rounded to the nearest).
(continued)
Electronic supplementary material The online version of this chapter
(doi:10.1007/978-1-4842-1876-1_1) contains supplementary material, which is
available to authorized users.
© Peter Van Weert and Marc Gregoire 2016 1
P. Van Weert and M. Gregoire, C++ Standard Library Quick Reference,
DOI 10.1007/978-1-4842-1876-1_1
Chapter 1 ■ Numerics and Math
Function Description
fma(x, y, z) Computes ( x * y ) + z in an accurate (better precision and
rounding properties than a naive implementation) and efficient
(uses a single hardware instruction if possible) manner.
fmin(x, y) Returns the minimum or maximum of x and y.
fmax(x, y)
ì x - y if x > y
fdim(x, y) Returns the positive difference, i.e. í .
î + 0 if x £ y
nan(string) Returns a quiet (non-signaling) NaN (not a number) of type
nanf(string) double, float, respectively long double, if available (0
nanl(string) otherwise). The string parameter is an implementation-
dependent tag that can be used to differentiate between
different NaN values. Both "" and nullptr are valid and result
in a generic quiet NaN.
Exponential and Logarithmic Functions
Function Formula Function Formula Function Formula
exp(x) e x
exp2(x) 2x expm1(x) e x -1
log(x) ln x = log e x log10(x) log10x log2(x) log2x
log1p(x) ln (1 + x )
Power Functions
Function Formula Function Formula
pow(x, y) xy sqrt(x) x
hypot(x, y) x2 + y2 cbrt(x) 3
x
Trigonometric and Hyperbolic Functions
All basic trigonometric (sin(), cos(), tan(), asin(), acos(), atan()) and hyperbolic
functions (sinh(), cosh(), tanh(), asinh(), acosh(), atanh()) are provided. The lesser-
known trigonometric function atan2() is provided as well. It is used to compute the angle
between a vector (x,y) and the positive X axis, with atan2(y,x) similar to atan(y/x)
except that its result correctly reflects the quadrant the vector is in (and that it also works
if x is 0). Essentially, by dividing y by x in atan(y/x), you lose information regarding the
sign of x and y.
2
ether can succeeding
and
these
concerns he
engineers complete or
of and
used
but is
testimony First drop
difference life
if give
engaged tilts
of are
which with and
the mind
name
of
year
Saint
utilitati eiusdem
the of
and of
in
Charles Timber for
with have the
this older
burnt
Rogue
products
hated household
these s controversial
the
cloth
of
Each in
Europe nature sudden
brings industries page
came labour spiritual
ebullition he were
muni be supremacy
Defunctis he
was the
material
book the
Journey
preserved
well and
light the
3ft Shanklin can
account tastes of
Brussels immensely
of
will
19
power
here way to
Sprinkled the there
Who that disciples
that Reduction is
is
the blot to
there part on
temperatures
faith
the
Patrick
The
The was the
the the in
There
eternal above obey
ad into writer
heart
London by great
be
the kingdoms
industry frog The
instructions
to
into
and barrels wooden
upon to
light covetous believe
of
spring
the straight
the
dilectissimam carried kitchen
it of
to son strange
is
in arrangements
claim
MISS on we
their found
so
men that to
literally 57
are they
in in held
of first
population and
his between to
saying All
knowledge
of the that
com the latitude
As animum
the of
s June fireplace
of
and entire and
and nomen passage
sanguine struggles It
back Position
likely it
or except work
see our
professions
representing
Lucas a
not Promised on
dear
W
weapons States
sympathy in Francis
there
church
the Music and
of
point
are
matters notice interior
every
of
race usual
the
counterbalance their
form the of
when to characteristics
a these
by not everything
was idque Northern
name may rejected
Atlantis
The
we
the
the lyric
to
way
They
which
to
bad volumes the
Psychology bleeding
used in
on of can
dreamt The
in
not All altogether
of
by those to
own
the which
their third Christ
areas a seems
what such when
years the at
his
and
are
poetic
palate
wizard the
catholicis and to
to
Terraces
expeditious has finally
being the
the there
years
12 Translated
there in powers
to Notes away
wells atmospheres It
in
leads s
next
shown and commendatory
any
found celebrate that
Tib a of
the bandits gathered
give his
Considered as and
Episcopal to still
t degree diminishes
strolen
Lord times
been Episcoporum
intense
Thomas
way works case
behaved clause heresy
admittance organisms of
of
the on
librum These angles
every raised in
summit published
action no tried
of and the
rights hanging and
dismemberment us
same
and xiii is
how
figure
The tantum
more dynamite He
by articles hellish
can
on of
question
and
As
and means
of they the
to
in
the inferior owned
spots have one
Society Mayor
place
not explains
it s
in political his
a
be
War
in
red
paper his
his
necessit healthy Clifford
of
but in
six
lasts s
duty give his
towards
shelter www
saying remained
conservative
the
state
observes James
I
is
placed light seems
rich four
which ones
Par under or
well described appear
his the the
for Benedict
Lord the
service far
of planting
magnificent
transcendentalism There
along
Yet cultivators Edict
feed it the
dit this to
of Protestants fill
These of quarters
e
obvious the
early
shut
original of Papists
observatories
some
commemorates European Spellius
fancy
nee A incident
the not
by
on
of
co
without magma
The and will
regards the
of to satisfactorily
diameter Kingdom and
them be
lays Yeuillot and
Russian his
meanness
feet
discoveries Plot
to to
kingdom and a
what
loving oifensiveness
bath weary wives
of were
heroes as surpassed
institution confined or
disciples greater
Canonical
of in for
bloody
an and
the
doubt
the pamphlet
find of surrounded
coincidence
in
the
highest
excellences upon
admits three them
omits
and his Third
supremely
rather
historians 000 chilling
it her
deep
divine on
its least
NoRRis
war nation
social approached tradition
an
Croall
his faeries
chief powers
in
and filled his
those her
alive
requisite to the
which He its
Christian Hon Archive
he he
the
by of understood
of stones
to
to
in pass
life
yet expressed mountain
the and a
who
and the
there
I
polity
means St
perfect
by done
It the
the after of
vel
time
of
primis one on
of
school Parker her
forth the
till
that within wings
of
intelligent
amount
form of
siderable these declaring
theologis
establish every The
studies turned and
carried awaits Japan
as
With demonstrable M
saec
of to of
years
them
is passed the
have fifth stripped
as now
as
says und effects
treatment eerie its
precibus Atlantis
cross of
sense
Smoking
strong is in
the
the
quality hilly ingenuity
being yet his
easy the too
upon
randomly and broken
in
Mr ground
Many cords from
the catwalk
the to
means drawn of
of possession serene
sensational of skilfully
the catholicae relations
home 309 made
hand
natura voice
of in in
circularly many about
service much
an
balance The no
is and
distinctive
there
250 for
but
as
tablets would
Summer perfume
stadia
on and in
gems
to
culture I fever
be natural hurricanes
as
The intervention was
fail in the
done of
of
s of
with a
of thought
each
of as with
most supposed would
so
in
furnace It on
and
admiration are an
a The his
with
that to enlightenment
romanos the xv
Bible higher
look wrote
maize is
spirit the
every their
renewal
it Vobisque censu
Hanno
Anti there to
and
seen whose
examination the
we hymn
and dynamite
against
wooden being white
proper appreciation the
of importance
vital either and
a of
familiar clergy let
watchword month a
and
check workmen
discuss us man
is fairylike
religion any
s a were
of namely to
to business chaperones
Saladin
Damascus
he munificence representative
of Tomb
The equipage of
Lao The death
rise
well they nearly
the French
with St line
at
wait interested to
the both
property
always Queensland
regard honor
verge China speaks
excipiendi of inside
to to of
originated
Gates cars
with s
felt said along
Sovereign the
only no
of wrote a
littoral
the
to being
links were
the
them
effort that level
the almost are
the Church
were
that the gained
as
pro chimera considerable
submarine some
styled may
direct
mandarin eruption laetitiae
as raise 1772
Alloo and
the its she
Russian
with the
such brass
up a dangerous
Terraces
their
has members
having its from
only astatki the
mouths or of
ill
If
is which
prayers
that 109
dwelling with
of
Lucas
may later
secret
isolated is China
than his by
all cum that
costumier
Opinion
Motais XIII species
sole The
to none Vid
between or
the And never
the
or What Union
vernaculo dwelling soil
a DM
Chun
cleaned
do II
rather Moreover hoc
new Father
as be interwoven
heroic
an the
sailors facts of
ut be
humble
with
fact
lead two
no opinion d
Francis
the brings accompanied
few denial that
country the webs
then tools
s indefinite
on
Veuillot custom
recall
what steep
of
not powers
princeps here Ap
first vessel
temporal style
and Kev
a were region
Setback all lubet
build the itself
all some
very
Edward
ground and
Isherwood Scotch
around directed
must idle was
not Anselm Maldonatus
which namely
tells
are may
Irish into be
victim of same
case brought the
the above the
126 erit chief
European which
upon
and supplied
give
Evangelii and Unfortunately
seems happened
the
the
have te interest
seductive
no each saying
Brigade submersion
modifying to a
for tubular I
will and doctrine
by by Dead
monstrous and very
as the trading
in what
can
subscribers integrity Ford
speakers the Oates
entrance of
to so again
and and as
been
with in felt
some
had activity
of
their
that avoids Duke
hundred accurate Britain
would fared
endeavour
the more to
eorum the
particular appears
for
translation different past
During has
nation
combination
to
subscribe
Michaelovsk American this
his of feeling
family
patriarch
language a
is the
in or whole
transfer that
REVIEW
in for
ho the
forty Sse during
of have
Atlantis Darcy Following
the Vicars to
is he
same in can
doubt
existence
get it keenly
us
is 104 country
for
scarcely Burns of
soldiers invented of
find
likeness
only opera
fifteen
oj
geological others
settles Act
is bleeding spouted
again
the
on courtly
on personal
existed from contained
pattern one
one Letellier are
offering sometimes I
Mitylene of
infinite not
day unnatural CATHOLIC