You are on page 1of 11

C++ Reference

The standard C++ library is a collection of functions, constants, classes, objects and templates that
extends the C++ language providing basic functionality to perform several tasks, like classes to interact
with the operating system, data containers, manipulators to operate with them and algorithms commonly
needed.

The declarations of the different elements provided by the library are split in several headers that shall
be included in the code in order to have access to its components:
algorithm complex exception list stack
bitset csetjmp fstream locale stdexcept
cassert csignal functional map strstream
cctype cstdarg iomanip memory streambuf
cerrno cstddef ios new string
cfloat cstdio iosfwd numeric typeinfo
ciso646 cstdlib iostream ostream utility
climits cstring istream queue valarray
clocale ctime iterator set vector
cmath deque limits sstream

It can be divided into:

C Library
The elements of the C language library are also included as a subset of the C++ Standard library. These
cover many aspects, from general utility functions and macros to input/output functions and dynamic
memory management functions:
cassert C Diagnostics Library (header)
cctype Character handling functions (header)
cerrno C Errors (header)
cfloat Characteristics of floating-point types (header)
ciso646 ISO 646 Alternative operator spellings (header)
climits Sizes of integral types (header)
clocale C localization library (header)
cmath C numerics library (header)
csetjmp Non local jumps (header)
csignal C library to handle signals (header)
cstdarg Variable arguments handling (header)
cstddef C Standard definitions (header)
cstdio C library to perform Input/Output operations (header)
cstdlib C Standard General Utilities Library (header)
cstring C Strings (header)
ctime C Time Library (header)

C++ Standard Library: Miscellaneous libraries


Language support library:
limits Numeric limits (header)
new Dynamic memory (header)
typeinfo Type information (header)
exception Standard exception class (class)

Diagnostics library:
stdexcept Exception classes (header)

General utilities library:


utility Utility components (header)
functional Function objects (header)
memory Memory elements (header)

Strings library:
string C++ Strings library (library)

Localization library:
locale Localization library (header)

C++ Standard Library: Standard Template Library (STL)


Containers library:
bitset Bitset (classtemplate)
deque Double ended queue (class template)
list List (class template)
map Map (class template)
multimap Multiple-key map (class template)
multiset Multiple-key set (class template)
priority_queue Priority queue (class
template)
queue FIFO queue (class template)
set Set (class template)
stack LIFO stack (class template)
vector Vector (class template)

Iterators library:
iterator Iterator definitions (header)

Algorithms library:
algorithm Standard Template Library: Algorithms (library)

Numeric library:
complex Complex numbers library (header)
valarray Library for arrays of numeric values (header)
numeric Generalized numeric operations (header)

C++ Standard Library: Input/Output Stream Library


Provides functionality to use an abstraction called streams specially designed to perform input and output operations on
sequences of character, like files or strings.
This functionality is provided through several related classes, as shown in the following relationship map, with the
corresponding header file names on top:
For more info see the reference page for the C++ Input/Output Library.

IOstream Library
library

Standard Input / Output Streams Library

The iostream library is an object-oriented library that provides input and output functionality using streams.

A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can
basically be represented as a source or destination of characters of indefinite length.

Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the
console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the physical
device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a
file, any input or output operation performed on that stream is physically reflected in the file.

To operate with streams, C++ provides the standard iostream library, which contains the following elements:

Basic class templates


The base of the iostream library is the hierarchy of class templates. The class templates provide most of the
functionality of the library in a type-independent fashion.

This is a set of class templates, each one having two template parameters: the char type (charT) parameter, that
determines the type of elements that are going to be manipulated and the traits parameter, that provides
additional characteristics specific for a particular type of elements.

The class templates in this class hierarchy have the same name as their char-type instantiations but with the
prefix basic_. For example, the class template whichistream is instantiated from is called basic_istream, the one
from which fstream is is called basic_fstream, and so on... The only exception is ios_base, which is by itself
type-independent, and therefore is not based on a template, but is a regular class.

Class template instantiations


The library incorporates two standard sets of instantiations of the entire iostream class template hierarchy: one is
narrow-oriented, to manipulate elements of type char and another one, wide-oriented, to manipulate elements of
type wchar_t.

The narrow-oriented (char type) instantiation is probably the better known part of the iostream library. Classes
like ios, istream and ofstream are narrow-oriented. The diagram on top of this page shows the names and
relationships of narrow-oriented classes.

The classes of the wide-oriented (wchar_t) instatiation follow the same naming conventions as the narrow-
oriented instantiation but with the name of each class and object prefixed with a w character,
forming wios, wistream and wofstream, as an example.

Standard objects
As part of the iostream library, the header file <iostream> declares certain objects that are used to perform input
and output operations on the standard input and output.

They are divided in two sets: narrow-oriented objects, which are the popular cin, cout, cerr and clog and their
wide-oriented counterparts, declared as wcin, wcout,wcerr and wclog.

Types
The iostream classes barely use fundamental types on their member's prototypes. They generally use defined types
that depend on the traits used in their instantiation. For the default char and wchar_t instantiations,
types streampos, streamoff and streamsize are used to represent positions, offsets and sizes, respectively.

Manipulators
Manipulators are global functions designed to be used together with insertion (<<) and extraction (>>) operators
performed on iostream stream objects. They generally modify properties and formatting settings of the
streams. endl, hex and scientific are some examples of manipulators.

Organization
The library and its hierarchy of classes is split in different files:
 <ios>, <istream>, <ostream>, <streambuf> and <iosfwd> aren't usually included directly in most C++
programs. They describe the base classes of the hierarchy and are automatically included by other header files of
the library that contain derived classes.
 <iostream> declares the objects used to communicate through the standard input and output
(including cin and cout).
 <fstream> defines the file stream classes (like the template basic_ifstream or the class ofstream) as well as the
internal buffer objects used with these (basic_filebuf). These classes are used to manipulate files using streams.
 <sstream>: The classes defined in this file are used to manipulate string objects as if they were streams.
 <iomanip> declares some standard manipulators with parameters to be used with extraction and insertion
operators to modify internal flags and formatting options.

Compatibility notes
The names, prototypes and examples included in this reference for the iostream classes mostly describe and use
the char instantiations of the class templates instead of the templates themselves, even though these classes are only one
of their possible instantiations. We believe this provides a better readability and is arguably as easy to obtain the names
and prototypes of the basic template from the char instantiation as the opposite.

Elements of the iostream library (char instantitation)


Classes:
ios_base Base class with type-independent members for the standard stream classes (class)
ios Base class with type-dependent members for the standard stream classes (class)
istream Input stream (class)
ostream Output Stream (class)
iostream Input/Output Stream (class)
ifstream Input file stream class (class)
ofstream Output file stream (class)
fstream Input/output file stream class (class)
istringstream Input string stream class (class)
ostringstream Output string stream class (class)
stringstream Input/output string stream class (class)
streambuf Base buffer class for streams (class)
filebuf File stream buffer (class)
stringbuf String stream buffer (class)

Objects:
cin Standard input stream (object)
cout Standard output stream (object)
cerr Standard output stream for errors (object)
clog Standard output stream for logging (object)

Types:
fpos Stream position class template (class template)
streamoff Stream offset type (type)
streampos Stream position type (type)
streamsize Stream size type (types)

Manipulators:
boolalpha Alphanumerical bool values (manipulator
function)
dec Use decimal base (manipulator function)
endl Insert newline and flush (manipulator function)
ends Insert null character (manipulator function)
fixed Use fixed-point notation (manipulator function)
flush Flush stream buffer (manipulator function)
hex Use hexadecimal base (manipulator function)
internal Adjust field by inserting characters at an internal position (manipulator function)
left Adjust output to the left (manipulator function)
noboolalpha No alphanumerical bool values (manipulator function)
noshowbase Do not show numerical base prefixes (manipulator
function)
noshowpoint Do not show decimal point (manipulator function)
noshowpos Do not show positive signs (manipulatorfunction)
noskipws Do not skip whitespaces (manipulator function)
nounitbuf Do not force flushes after insertions (manipulator function)
nouppercase Do not generate upper case letters (manipulator function)
oct Use octal base (manipulator function)
resetiosflags Reset format flags (manipulator function)
right Adjust output to the right (manipulator function)
scientific Use scientific notation (manipulator function)
setbase Set basefield flag (manipulator function)
setfill Set fill character (manipulator function)
setiosflags Set format flags (manipulator function)
setprecision Set decimal precision (manipulator function)
setw Set field width (manipulator function)
showbase Show numerical base prefixes (manipulator function)
showpoint Show decimal point (manipulator function)
showpos Show positive signs (manipulator function)
skipws Skip whitespaces (manipulator function)
unitbuf Flush buffer after insertions (manipulator function)
uppercase Generate upper-case letters (manipulator function)
ws Extract whitespaces (manipulator function)

STL Containers
library

Standard Template Library: Containers

A container is a holder object that stores a collection other objects (its elements). They are implemented as class templates,
which allows a great flexibility in the types supported as elements.

The container manages the storage space for its elements and provides member functions to access them, either directly or
through iterators (reference objects with similar properties to pointers).

Containers replicate structures very commonly used in programming: dynamic arrays (vector), queues (queue), stacks
(stack), heaps (priority_queue), linked lists (list), trees (set), associative arrays (map)...

Many containers have several member functions in common, and share functionalities. The decision of which type of
container to use for a specific need does not generally depend only on the functionality offered by the container, but also on
the efficiency of some of its members (complexity). This is especially true for sequence containers, which offer different
trade-offs in complexity between inserting/removing elements and accessing them.

stack, queue and priority_queue are implemented as container adaptors. Container adaptors are not full container classes,
but classes that provide a specific interface relying on an object of one of the container classes (such as deque or list) to
handle the elements. The underlying container is encapsulated in such a way that its elements are accessed by the
members of the container class independently of the underlying container class used.

Container class templates


Sequence containers:
vector Vector (class template)
deque Double ended queue (class template)
list List (class template)

Container adaptors:
stack LIFO stack (class template)
queue FIFO queue (class template)
priority_queue Priority queue (class template)

Associative containers :
set Set (class template)
multiset Multiple-key set (class template)
map Map (class template)
multimap Multiple-key map (class template)
bitset Bitset (class template)

Member map
This is a comparison chart with the different member functions present on each of the different
containers:

Sequence containers Associative containers


<vecto <deq
Headers <list> <set> <bitset>
r> ue>
com dequ multis multi
Members vector list set map bitset
plex e et map
constru construc constr constru constru constru constru
* constructor constructor
ctor tor uctor ctor ctor ctor ctor
destruct destruct destru destruc destruc destruc destruc
O(n) destructor
or or ctor tor tor tor tor
operato O(n) operator operat operator= operato operato operato operato operators
r= = or= r= r= r= r=
begin O(1) begin begin begin begin begin begin begin

iterat end O(1) end end end end end end end
ors rbegin O(1) rbegin rbegin rbegin rbegin rbegin rbegin rbegin
rend O(1) rend rend rend rend rend rend rend
size * size size size size size size size size
max_si max_siz max_s max_si max_si max_si max_si
capac * max_size
ze e ize ze ze ze ze
ity
empty O(1) empty empty empty empty empty empty empty
resize O(n) resize resize resize
front O(1) front front front
eleme back O(1) back back back
nt
acces operato * operator operat operato
operator[]
s r[] [] or[] r[]

at O(1) at at
assign O(n) assign assign assign
insert * insert insert insert insert insert insert insert
erase * erase erase erase erase erase erase erase
swap O(1) swap swap swap swap swap swap swap
clear O(n) clear clear clear clear clear clear clear

modif
push_fr push_f
O(1) push_front
iers ont ront

pop_fr pop_fr
O(1) pop_front
ont ont

push_b push_ba push_


O(1) push_back
ack ck back

pop_ba pop_bac pop_b


O(1) pop_back
ck k ack

key_co key_co key_co key_co key_co


O(1)
obser mp mp mp mp mp
vers value_c value_c value_c value_c value_c
O(1)
omp omp omp omp omp
O(lo
find g n)
find find find find

O(lo
count g n)
count count count count count

lower_ O(lo lower_ lower_ lower_ lower_


opera
tions bound g n) bound bound bound bound

upper_ O(lo upper_ upper_ upper_ upper_


bound g n) bound bound bound bound

equal_r O(lo equal_r equal_r equal_r equal_r


ange g n) ange ange ange ange
unique capacityr splice remove remove_if uniq set reset flipto_ulong to_
members eserve uemerge sort reverse stringtest any none

Amortized complexity shown. Legend: O(1) constant < O(log n) logarithmic < O(n) linear; *=depends on container

Container adaptors:
Container Adaptors
Headers <stack> <queue>
Members stack queue priority_queue
constructo
* constructor constructor constructor
r
size O(1) size size size
capacity
empty O(1) empty empty empty
front O(1) front
element access back O(1) back
top O(1) top top
push O(1) push push push
modifiers
pop O(1) pop pop pop

Standard Template Library: Algorithms

The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements.

A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of
some of the STL containers. Notice though, that algorithms operate through iterators directly on the values, not affecting in
any way the structure of any possible container (it never affects the size or storage allocation of the container).

Functions in <algorithm>
Non-modifying sequence operations:
for_each Apply function to range (template function)
find Find value in range (function template)
find_if Find element in range (function template)
find_end Find last subsequence in range (function template)
find_first_of Find element from set in range (function template)
adjacent_find Find equal adjacent elements in range (function template)
count Count appearances of value in range (function template)
count_if Return number of elements in range satisfying condition (function template)
mismatch Return first position where two ranges differ (function
template)
equal Test whether the elements in two ranges are equal (function template)
search Find subsequence in range (function template)
search_n Find succession of equal values in range (function template)

Modifying sequence operations:


copy Copy range of elements (function template)
copy_backward Copy range of elements backwards (function template)
swap Exchange values of two objects (functiontemplate)
swap_ranges Exchange values of two ranges (function template)
iter_swap Exchange values of objects pointed by two iterators (function template)
transform Apply function to range (function template)
replace Replace value in range (function template)
replace_if Replace values in range (function template)
replace_copy Copy range replacing value (function template)
replace_copy_if Copy range replacing value (function template)
fill Fill range with value (function template)
fill_n Fill sequence with value (function template)
generate Generate values for range with function (function template)
generate_n Generate values for sequence with function (function template)
remove Remove value from range (function template)
remove_if Remove elements from range (function template)
remove_copy Copy range removing value (function template)
remove_copy_if Copy range removing values (function template)
unique Remove consecutive duplicates in range (function
template)
unique_copy Copy range removing duplicates (function template)
reverse Reverse range (function template)
reverse_copy Copy range reversed (function template)
rotate Rotate elements in range (function template)
rotate_copy Copy rotated range (function template)
random_shuffle Rearrange elements in range randomly (function template)
partition Partition range in two (function template)
stable_partition Partition range in two - stable ordering (function template)

Sorting:
sort Sort elements in range (function template)
stable_sort Sort elements preserving order of equivalents (function template)
partial_sort Partially Sort elements in range (functiontemplate)
partial_sort_copy Copy and partially sort range (function template)
nth_element Sort element in range (function template)

Binary search (operating on sorted ranges):


lower_bound Return iterator to lower bound (function template)
upper_bound Return iterator to upper bound (function template)
equal_range Get subrange of equal elements (function template)
binary_search Test if value exists in sorted array (function template)

Merge (operating on sorted ranges):


merge Merge sorted ranges (function template)
inplace_merge Merge consecutive sorted ranges (function template)
includes Test whether sorted range includes another sorted range (function template)
set_union Union of two sorted ranges (function template)
set_intersection Intersection of two sorted ranges (function template)
set_difference Difference of two sorted ranges (function template)
set_symmetric_difference Symmetric difference of two sorted ranges (function template)

Heap:
push_heap Push element into heap range (functiontemplate)
pop_heap Pop element from heap range (function template)
make_heap Make heap from range (function template)
sort_heap Sort elements of heap (function template)

Min/max:
min Return the lesser of two arguments (function template)
max Return the greater of two arguments (function template)
min_element Return smallest element in range (function template)
max_element Return largest element in range (function template)
lexicographical_compare Lexicographical less-than comparison (function template)
next_permutation Transform range to next permutation (function template)
prev_permutation Transform range to previous permutation (function template)

Miscellaneous
library

Standard Library - Miscellaneous headers

Other headers part of the C++ standard library:

complex Complex number class (class template)


exception Standard exception class (class)
functional Function objects (header)
iterator Iterator definitions (header)
limits Numeric limits (header)
locale Locale class (class)
memory Memory elements (header)
new Dynamic memory (header)
numeric Generalized numeric operations (header)
stdexcept Exception classes (header)
typeinfo Type information (header)
utility Utility components (header)
valarray Valarray class (class template)

Sources
  Generic Console programs

File Description Source


Set of simple example sources to follow the C++ Tutorial included
 C++ Tutorial Sources Juan Soulie
in the documents section of this site.

 Fraction Example program to add and reduce fractions. Abraham Ishaq

A Fraction class that has the ability to add, subtract, multiply,


 Fraction Daniel Pronych
divide and show various statistics of the fraction.
Small program for beginners demonstrating the use of loops and
 Triangle Gary Paduana
iostream + iomanip libraries.
This is a collection of functions, and classes that will aid you in
 Master String Jared Bruni
very explicit string manipulation.

 Encrypt Encrypts/Decrypts a piece of text using vigenere algorithm. Sam Alexander

A simple program demonstrating tokenizing by drawing a


 Rectangle Nick White
rectangle.
A simple program that converts a string into its binary
 Binary convert Matt Fowler
representation.

  Windows programs

File Description Source


A small program that shows one of the fundamentals of Windows
 Winnie Tom Lee
programming: How to create a window.

 SDI Frame A basic framework for Single-Document-Interface applications. Gary Hall

 BMP Loader Example on how to load a BMP File. Juan Soulie

 GIF View Example on how to load and display animated GIF and BMP Files. Juan Soulie

 CWinTcpSocket C++ Winsock wrapper class. Tom Lee

Header file containing a lot of C++ functions. Over 6,000 lines of


 Master Library code with code ranging from DirectX to Winsock. Good resource Jared Bruni
for windows C++ programming (Visual C++ project files).
Basic intro Windows API, with multiple windows (Visual C++
 Win32 Example Jared Bruni
project files, using C).

 Win32 Example (II) Basic intro Windows API, controls, menu (Visual C++ project files). Jared Bruni

This is a simple application that allows you to download a file from


 URL Downloader Jared Bruni
a web page (Visual C++ project files).
Basic intro Direct3D8, sets up the window and draws a few things
 Basic Direct 3D 8 Jared Bruni
(Visual C++/DirectX project files).
Beta version of a direct3d game that the author is programming at
 Tank 3.0 Beta Christian Reimann
the moment.

 HWPrint Example program to demonstrate printing using Win32 API. Tom Lee

  MS-DOS programs

File Description Source

 Notepad Text editor. Zahid Ashfaq

If you have any self-explanatory source and you want it to be included here contact us.

You might also like