MSL_C++_Reference
MSL_C++_Reference
2 17 C++ Library 43
Overview of the MSL C++ Reference . . . . . . . . . . . . 43
17.1 Definitions . . . . . . . . . . . . . . . . . . . . . . 43
17.2 Additional Definitions. . . . . . . . . . . . . . . . . 47
17.3 Methods of Descriptions . . . . . . . . . . . . . . . . 47
17.3.1 Structure of each subclause. . . . . . . . . . . . . 47
17.3.2 Other Conventions . . . . . . . . . . . . . . . . 48
17.4 Library-wide Requirements . . . . . . . . . . . . . . 49
17.4.1 Library contents and organization. . . . . . . . . . 50
17.4.2 Using the library . . . . . . . . . . . . . . . . . 52
17.4.3 Constraints on programs. . . . . . . . . . . . . . 52
17.4.4 Conforming Implementations . . . . . . . . . . . 54
17.4.4.8 Restrictions On Exception Handling . . . . . . . . 54
Features not implemented in MSL C++ . . . . . . . . . . . 55
Template Functionality . . . . . . . . . . . . . . . . . 55
ANSI/ISO Library Functionality . . . . . . . . . . . . . 55
4 Diagnostics Library 73
Overview of Diagnostics LIbrary . . . . . . . . . . . . . . 73
Exception Classes . . . . . . . . . . . . . . . . . . . . . 73
Class exception . . . . . . . . . . . . . . . . . . . . 74
Constructor–exception . . . . . . . . . . . . . . . . . 74
Copy Constructor–exception. . . . . . . . . . . . . . . 74
Assignment Operator–exception . . . . . . . . . . . . . 75
Destructor–exception . . . . . . . . . . . . . . . . . . 75
exception::what . . . . . . . . . . . . . . . . . . . . 75
Class logic_error . . . . . . . . . . . . . . . . . . . . 75
Constructor–logic_error . . . . . . . . . . . . . . . . . 75
Class domain_error. . . . . . . . . . . . . . . . . . . 76
Constructor–domain_error . . . . . . . . . . . . . . . 76
Class invalid_argument . . . . . . . . . . . . . . . . . 76
Constructor–invalid_argument. . . . . . . . . . . . . . 76
Class length_error . . . . . . . . . . . . . . . . . . . 76
Constructor–length_error . . . . . . . . . . . . . . . . 77
Class out_of_range . . . . . . . . . . . . . . . . . . . 77
Constructor–out_of_range . . . . . . . . . . . . . . . . 77
23 Mutex.h 669
Overview of Mutex Support Library . . . . . . . . . . . . 669
Header <mutex.h> . . . . . . . . . . . . . . . . . . . . 669
null_mutex . . . . . . . . . . . . . . . . . . . . . . . 672
Constructor and Destructor . . . . . . . . . . . . . . . 672
Constructor . . . . . . . . . . . . . . . . . . . . . . 672
Destructor. . . . . . . . . . . . . . . . . . . . . . . 672
Public Member Functions . . . . . . . . . . . . . . . . 673
remove . . . . . . . . . . . . . . . . . . . . . . . . 673
acquire . . . . . . . . . . . . . . . . . . . . . . . . 673
release . . . . . . . . . . . . . . . . . . . . . . . . 673
mutex . . . . . . . . . . . . . . . . . . . . . . . . . . 673
Constructor and Destructor . . . . . . . . . . . . . . . 674
Constructor . . . . . . . . . . . . . . . . . . . . . . 674
Destructor. . . . . . . . . . . . . . . . . . . . . . . 674
Public Member Functions . . . . . . . . . . . . . . . . 674
remove . . . . . . . . . . . . . . . . . . . . . . . . 674
acquire . . . . . . . . . . . . . . . . . . . . . . . . 674
release . . . . . . . . . . . . . . . . . . . . . . . . 674
try_lock . . . . . . . . . . . . . . . . . . . . . . . . 675
mutex_block . . . . . . . . . . . . . . . . . . . . . . . 675
Constructor and Destructors . . . . . . . . . . . . . . . 675
Constructor . . . . . . . . . . . . . . . . . . . . . . 675
Destructor. . . . . . . . . . . . . . . . . . . . . . . 675
Public Member Functions . . . . . . . . . . . . . . . . 676
remove . . . . . . . . . . . . . . . . . . . . . . . . 676
release . . . . . . . . . . . . . . . . . . . . . . . . 676
17.1 Definitions
This section discusses the meaning of certain terms in the MSL C++
library.
• “17.1.1 Arbitrary-Positional Stream” on page 44
• “17.1.2 Character” on page 44
• “17.1.3 Character Sequences” on page 44
• “17.1.4 Comparison Function” on page 44
• “17.1.5 Component” on page 45
A stream that can seek to any position within the length of the
stream. An arbitrary-positional stream is also a repositional stream
17.1.2 Character
17.1.5 Component
17.1.10 ObjectState
17.1.12 NTCTS
A stream that can seek only to a position that was previously en-
countered.
17.1.18 Traits
Multi-Thread Safety
Thus the library will work in the presence of multiple threads in the
same way as in single thread provided the user does not share ob-
jects between threads or locks between accesses to objects that are
shared.
17.3.1.1 Summary
All library entities except macros, operator new and operator delete
are defined within the namespace std or namespaces nested within
namespace std.
17.4.1.2 Headers
Header Description
<cstddef> Types
<limits> Implementation properties
<cstdlib> Start and termination
<new> Dynamic memory management
<typeinfo> Type identification
Header Description
<exception> Exception handling
<cstdarg> Other runtime support
17.4.2.1 Headers
17.4.2.2 Linkage
17.4.3.2 Headers
The behavior of any header file with the same name as a Metrow-
erks Standard Library public or private header, is undefined.
A C++ program may provide the definition for any of eight dy-
namic memory allocation function signatures declared in header
<new>.
operator new(size_t)
operator new(size_t, const std::nothrow_t&)
operator new[](size_t)
operator new[](size_t, const std::nothrow_t&)
operator delete(void*)
operator delete(void*, const std::nothrow_t&)
operator delete[](void*)
operator delete[](void*, const std::nothrow_t&)
Template Functionality
There are minimal areas of the Standard library that depend on C++
features that have so far not been implemented.
Macros
The macros defined are:
• “NULL” on page 58
• “offsetoff” on page 58
• “sizeof” on page 58
NULL
Description The macro NULL is an implementation-defined C++ null-pointer
constant in this International Standard. In MSL this evaluates to
zero.
offsetoff
Description The macro offsetoff accepts a restricted set of type arguments in
this International Standard. type shall be a POD1 structure or a
POD union.
sizeof
Description The sizeof operator yields the number of bytes in the object repre-
sentation of its operand. The operand can be either an expression,
which is not evaluated, or a parenthesized type-id.
Type Implementations
There are several fundamental types. They are:
• “Character types” on page 59
1.A
POD structure or union is a union that has no members that are of type pointer to
members.The acronym for POD stands for “Plain Old Data”.
• “Enumeration” on page 59
• “Integral types” on page 59
• “Wide character types” on page 60
• “Bool type” on page 60
• “Floating point types” on page 60
• “Void type” on page 60
Character types
Objects declared as characters(char) shall be large enough to store
any member of the implementation’s basic character set. If a charac-
ter from this set is stored in a character object, its value shall be
equivalent to the integer code of that character. It is implementa-
tion-defined whether a char object can take on negative values.
Characters can be explicitly declared unsigned or signed. Plain
char, signed char, and unsigned char are three distinct types.
A char, a signed char, and an unsigned char occupy the same
amount of storage and have the same alignment requirements; that
is, they have the same object representation. For character types, all
bits of the object representation participate in the value representa-
tion. For unsigned character types, all possible bit patterns of the
value representation represent numbers.
Enumeration
An enumeration comprises a set of named integer constant val-
ues, which form the basis for an integral subrange that includes
those values. Each distinct enumeration constitutes a different
enumerated type. Each constant has the type of its enumeration.
Integral types
There are four signed integer types: signed char, short int,
int and long int. In this list, each type provides at least as much
storage as those preceding it in the list, but the implementation can
otherwise make any of them equal in storage size. Plain ints have
the natural size suggested by the machine architecture; the other
signed integer types are provided to meet special needs.
Bool type
Values of type bool are either true(1) or false(0). There are
no signed, unsigned, short, or long bool types or values.
Void type
The void type has an empty set of values. It is used as the return
type for functions that do not return a value.
Numeric Limits
The numeric_limits component provides a C++ program with
information about various properties of the implementation’s repre-
sentation of the fundamental types. Specializations will be provided
for each fundamental type, both floating point and integer, includ-
ing bool. The member is_specialized shall be true for all such
specializations of numeric_limits.
numeric_limits::is_specialized
Description The member is_specialized makes it possible to distinguish be-
tween scalar types, which have specializations, and non-scalar
types, which do not.
numeric_limits::min
Description This function returns the minimum finite value that can be
CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc. For this func-
tion, floating types with denormalization, return the minimum pos-
itive normalized value, denorm_min. The value returned by this
function is meaningful for all specializations in which
is_bounded==true, or is_bounded==false and
is_signed==false.
numeric_limits::max
Description This function returns the maximum finite value that can be
CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX, etc. The value re-
turned by this function is meaningful for all specializations in which
is_bounded==true.
numeric_limits::digits
Description It stores the number of radix digits that can be represented without
change. For built-in integer types, it denotes the number of non-sign
bits in the representation. For floating point types, it denotes the
number of radix digits in the mantissa which can be
FLT_MANT_DIG, DBL_MANT_DIG or LDBL_MANT_DIG.
numeric_limits::digits10
Description It stores the number of base 10 digits that can be represented with-
out change. The value can be one among FLT_DIG, DBL_DIG or
numeric_limits::is_signed
Description It stores a value true if the type is signed. It is meaningful for all
specializations.
numeric_limits::is_integer
Description It stores a value that is true, if the type is integer. It is meaningful
for all specializations.
numeric_limits::is_exact
Description It stores a value true if the type uses an exact representation. All in-
teger types are exact, but not vice versa. For example, rational and
fixed-exponent representations are exact but not integer. It is mean-
ingful for all specializations.
numeric_limits::radix
Description It stores a value that specifies the base of radix of the exponent rep-
resentation for floating types. Its value is usually 2 or can be
FLT_RADIX. For integer types it specifies the base of the representa-
tion. It is meaningful for all specializations.
numeric_limits::epsilon
Description It returns the difference between 1 and the least value greater than 1
that is representable. The value can be either FLT_EPSILON,
DBL_EPSILON or LDBL_EPSILON. The value returned is meaning-
ful only for floating point types.
numeric_limits::round_error
Description It returns a value that denotes the maximum rounding error that is
permitted. It is meaningful only for floating point types.
numeric_limits::min_exponent
Description It stores the minimum negative integer such that radix raised to
that power is in range. It is meaningful only for floating point types
and the values can be FLT_MIN_EXP,
DBL_MIN_EXP,LDBL_MIN_EXP.
numeric_limits::min_exponent10
Description It stores the minimum negative integer such that 10 raised to that
power is in range. It is meaningful only for floating point types and
the values can be FLT_MIN_10_EXP, DBL_MIN_10_EXP,
LDBL_MIN_10_EXP.
numeric_limits::max_exponent
Description It stores the maximum positive integer such that radix raised to that
power is in range. It is meaningful only for floating point types and
numeric_limits::max_exponent10
Description It stores the maximum positive integer such that 10 raised to that
power is in range. It is meaningful only for floating point types and
the values can be FLT_MAX_10_EXP, DBL_MAX_10_EXP,
LDBL_MAX_10_EXP.
numeric_limits::has_infinity
Description It stores a value true if the type has a representation for positive in-
finity. It is meaningful only for floating point types. It will be true
for all specialization in which is_iec559==true.
numeric_limits::has_quiet_NaN
Description It stores a value true if the type has a representation for a
quiet(non-signaling) Not a Number. It is meaningful only for
floating point types. The value will be true for all specializations in
which is_iec559==true.
numeric_limits::has_signaling_NaN
Description It stores a value true if the type has a representation for a signaling
Not a Number. It is meaningful only for floating point types. The
value will be true for all specializations in which
is_iec559==true.
numeric_limits::has_denorm
Description It stores true if the type allows denormalized values (i.e. variable
number of exponent bits). The value is meaningful only for floating
point types.
numeric_limits::infinity
Description It returns the representation of positive infinity, if available. It is
meaningful only for specializations for which
has_infinity==true. Required in specializations for which
is_iec559==true.
numeric_limits::quiet_NaN
Description This function returns the representation of a quiet Not a Number if
has_quiet_NaN==true.
numeric_limits::signaling_NaN
Description This function returns the representation of a signaling Not a Num-
ber if has_signaling_NaN==true.
numeric_limits::denorm_min
Description It returns the minimum positive denormalized value. It is meaning-
ful for all floating point types. In this function specialization for
numeric_limits::is_bounded
Description It stores a value true if the set of values representable by the type is
finite. All built-in types are bounded, this member would be false
for arbitrary precision types. It is meaningful for all specializations.
numeric_limits::is_modulo
Description It stores a value true if the type is modulo. A type is modulo if it is
possible to add two positive numbers and have a result that wraps
around to a third number that is less than either of the two numbers.
This has a value false for all floating types, true for unsigned in-
tegers, and true for signed integers on most machines and is mean-
ingful for all specializations.
numeric_limits::traps
Description It stores a value true if trapping is implemented for the type. It is
meaningful for all specializations.
numeric_limits::tinyness_before
Description It stores a value true if tinyness is detected before rounding. It is
meaningful only for floating point types.
numeric_limits::round_style
Description It stores the rounding style for the type. The value stored is mean-
ingful for all floating point types. Specializations for integer types
shall return round_toward_zero.
Class bad_alloc
The class bad_alloc, derived from the class exception, defines
the type of objects thrown as exceptions by the implementation to
report a failure to allocate storage.
Constructor–bad_alloc
Description This function constructs an object of class bad_alloc.
Copy Constructor–bad_alloc
Description This function copies an object of class bad_alloc.
Assignment Operator–bad_alloc
Description This function copies an object of class bad_alloc.
bad_alloc::what
Description Our implementation returns a string object instead of const
char*. This function returns the string associated with the excep-
tion if some allocation is done, else it returns string().
Class bad_cast
The class bad_cast, derived from the class exception, defines
the type of objects thrown as exceptions by the implementation to
report the execution of an invalid dynamic-cast expression.
Constructor–bad_cast
Description This function constructs an object of class bad_cast.
Copy Constructor–bad_cast
Description This function copies or constructs an object of class bad_cast.
Assignment Operator–bad_cast
Description This function copies an object of class bad_cast.
bad_cast::what
Description Our implementation returns a string object instead of const
char*. This function returns the string associated with the excep-
tion if some allocation is done, else it returns string().
Class bad_typeid
The class bad_typeid, derived from the class exception, de-
fines the type of objects thrown as exceptions by the implementa-
tion to report a null pointer in a typeid expression.
Constructor–bad_typeid
Description This function constructs an object of class bad_typeid.
Copy Constructor–bad_typeid
Description These functions copy an object of class bad_typeid.
Assignment Operator–bad_typeid
Description This function copies an object of class bad_typeid.
bad_typeid::what
Description Our implementation returns a string object instead of const
char*. This function returns the string associated with the excep-
tion if some allocation is done, else it returns string().
Exception Classes
There are several exception-related classes in the diagnostics library.
The base class is Class exception. Other exceptoin classes derive
from exception.
Class exception
Description The class exception defines the base class for the types of objects
thrown as exceptions by C++ standard library components, and cer-
tain expressions, to report errors detected during program execu-
tion.
Constructor–exception
Description This function constructs an object of class exception. It does not
throw any exceptions.
Copy Constructor–exception
Description This function copies an exception object.
Assignment Operator–exception
Description This function copies an exception object.
Destructor–exception
Description This function destroys an object of class exception.
exception::what
Description Our implementation returns a string object instead of const
char*. This function returns the string associated with the excep-
tion if some allocation is done, else it returns string().
Class logic_error
Description The class logic_error, derived from “Class exception” on page
74, defines the type of objects thrown as exceptions to report errors
presumably detectable before the program executes, such as viola-
tions of logical preconditions or class invariants.
Constructor–logic_error
Description This function constructs an object of class logic_error.
Class domain_error
Description The class domain_error, derived from “Class logic_error” on page
75, defines the type of objects thrown as exceptions to report do-
main errors.
Constructor–domain_error
Description This function constructs an object of class domain_error.
Class invalid_argument
Description The class invalid_argument defines the type of objects thrown
as exceptions to report an invalid argument.
Constructor–invalid_argument
Description This function constructs an object of class invalid_argument.
Class length_error
Description The class length_error, derived from “Class logic_error” on page
75, defines the type of objects thrown as exceptions to report an at-
tempt to produce an object whose length equals or exceeds its maxi-
mum allowable size.
Constructor–length_error
Description This function constructs an object of class length_error.
Class out_of_range
Description The class out_of_range, derived from “Class logic_error” on page
75, defines the type of objects thrown as exceptions to report an ar-
gument value not in its expected range.
Constructor–out_of_range
Description This function constructs an object of class out_of_range.
Class runtime_error
Description The class runtime_error, derived from “Class exception” on page
74, defines the type of objects thrown as exceptions to report errors
presumably detectable only when the program executes.
Constructor–runtime_error
Description This function constructs an object of class runtime_error.
Class range_error
Description The class range_error, derived from “Class runtime_error” on
page 77, defines the type of objects thrown as exceptions to report
range errors.
Constructor–range_error
Description This function constructs an object of class range_error.
Class overflow_error
Description The class overflow_error, derived from “Class runtime_error”
on page 77, defines the type of objects thrown as exceptions to re-
port an arithmetic overflow error.
Constructor–overflow_error
Description This function constructs an object of class overflow_error.
Allocator Classes
Different memory models have different requirements for pointers,
references, integer sizes, etc. The Allocator class encapsulates
information about pointers, constant pointers, references, constant
references, sizes of objects, difference types between pointers, allo-
cation and deallocation functions, and some other functions. The
exact set of types and functions defined within the allocator are ex-
plained in the Default Allocator Interface, later in this chapter.
template<class T>
class types {
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
};
allocator();
~allocator();
template<class T>
void deallocate(types<T>::pointer p);
Description In the allocator interface it can be seen that the type information is
encapsulated in the nested template class types. Since nested class
templates are not yet supported by any compilers, our implementa-
Typedef Declarations
Table 5.1 The following typedef’s are defined in the class allocator<T>
.
allocator::pointer allocator::const_pointer
allocator::reference allocator::const_reference
allocator::value_type allocator::const_address
allocator::pointer
Description The type of a pointer in the memory model.
allocator::const_pointer
Description The type of a constant pointer in the memory model.
allocator::reference
Description The type of a reference in the memory model.
allocator::const_reference
Description The type of a constant reference in the memory model.
allocator::value_type
Description value_type refers to the type of the objects in the container. By de-
fault, containers contain objects of the type with which they are in-
stantiated. For example, vector<int*> is a declaration of a vector
of pointers to integers.
Constructor–allocator
Description Constructs an allocator object.
Prototype allocator();
Destructor–allocator
Description Destroys an allocator object.
Prototype ~allocator();
allocator::size_type
Description size_type is the type that can represent the size of the largest object
in the memory model.
allocator::difference_type
Description This is the type that can represent the difference between any two
pointers in the memory model.
allocator::address
Description Returns a pointer to the referenced object x.
Prototype template
< class T >
allocator<T>::pointer address
(allocator<T>::reference x);
allocator::const_address
Description Returns a constant pointer to the referenced object x.
Prototype template
< class T >
allocator<T>::const_pointer const_address
(allocator<T>::const_reference x);
allocator::allocate
Description This member function allocates memory for n objects of type
size_type but the objects are not constructed. It uses the global op-
erator new.
Prototype template
< class T >
allocator<T>::pointer allocate
(size_type n);
allocator::deallocate
Description Deallocates all of the storage pointed to by the pointer p using the
global operator delete. All objects in the area pointed to by p
should be destroyed prior to the call of deallocate. The function is
templatized to allow it to be specialized for particular types in cus-
tom allocators.
Prototype template
< class T >
void deallocate
(allocator<T>::pointer p);
allocator::max_size
Description Returns the largest positive value of difference_type. This is the
same as the largest number of elements that the container can hold
in the given memory model.
Custom Allocators
The data types representing pointers (size_type) as well as the
difference between two pointers (difference_type) differ across
memory models.
allocator::vec_default
Description A vector of 100 integers using the default allocator.
allocator::vec_large
Description A vector of 1000 integers using the far allocator.
allocator::vec_huge
Description A vector of 100,000 integers using the huge allocator.
Allocator Requirements
This section discusses
• “Function Objects” on page 90
Function Objects
Description A function object encapsulates a function in an object for use by
other components. This is done by overloading the function call op-
erator, operator(), of the corresponding class.
These costs make a difference when the functions involved are very
simple ones, such as integer additions or comparisons.
In both of the above examples, the addition and negation will be in-
lined.
Function Adaptors
Description Function adaptors are STL classes that allow users to construct a
wider variety of function objects. Using function adaptors is often
easier than direct construction of a new function object type with a
struct or class definition.
finds the first integer in array x that is greater than 200. The base
function object greater<int>() takes two arguments x and y and re-
turns the greater value. By applying the binder bind2nd to this func-
tion object and the number 200, we produce a function object that
defines a unary function that takes a single argument x and returns
true if x > 200. This function object is then used as a parameter to
find_if, to find the first element in the array that is greater than 200.
Arithmetic Operations
Files #include <function.h>
Description STL provides basic function object classes for all of the arithmetic
operators in the language. The functionality of the operators is de-
scribed below. The function object classes are:
plus
Description The plus function object accepts two operands x and y of type T,
and returns the result of the computation of x + y.
minus
Description The minus function object accepts two operands x and y of type T,
and returns the result of the computation of x - y.
times
Description The times function object accepts two operands x and y of type T,
and returns the result of the computation of x * y.
divides
Description The divides function object accepts two operands x and y of type T,
and returns the result of the computation of x / y.
modulus
Description The modulus function object accepts two operands, x and y, of type
T, and returns their result of the computation x % y.
struct modulus<T>
negate
Description negate is a unary function that accepts a single operand x of type T,
and returns the result of the computation of -x.
Comparison Operations
Files #include <function.h>
Description STL provides basic function object classes for all of the comparison
operators in the language. The basic functionality of the comparison
objects is described below.
equal_to
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x == y.
not_equal_to
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x != y.
greater
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x > y.
less
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x < y.
greater_equal
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x >= y.
less_equal
Description An object of this type accepts two parameters, x and y, of type T,
and returns true if x <= y.
Logical Operations
Files #include <function.h>
Description STL provides basic function object classes for the following logical
operators in the language: and, or, not. The basic functionality of the
logical operators is described below.
logical_and
Description An object of this type accepts two parameters, x and y, of type T,
and returns the boolean result of the logical and operation: x && y.
logical_or
Description An object of this type accepts two parameters, x and y, of type T,
and returns the boolean result of the logical or operation: x || y.
logical_not
Description An object of this type accepts a single parameter, x, of type T, and
returns the boolean result of the logical not operation: !x.
Negator Adaptors
Files #include <function.h>
Description Negators are function adaptors that take a predicate and return its
complement. STL provides the negators not1 and not2 that take a
unary and binary predicate respectively and return their comple-
ments.
not1
Description This function accepts a unary predicate x as input and returns its
complement !x.
Prototype template
< class Predicate >
unary_negate<Predicate> not1
(const predicate& x);
not2
Description This function accepts a binary predicate x as input and returns its
complement, !x.
Prototype template
< class Predicate >
binary_negate<Predicate> not2
(const predicate& x);
Binder Adaptors
Files #include <function.h>
Description Binders are function adaptors that convert binary function objects
into unary function objects by binding an argument to some partic-
ular value. STL provides two binders bind1st and bind2nd,
which are described below.
bind1st
Description This adapter accepts a function object op of two arguments and a
value x, of type T. It returns a function object of one argument, con-
structed out of op with the first argument bound to x.
Prototype template
< class Operation,
class T >
binder1st<Operation> bind1st
(const Operation& op,
const T& x);
bind2nd
Description This adapter accepts a function object op of two arguments and a
value x, of type T. It returns a function object of one argument, con-
structed out of op with the second argument bound to x.
Prototype template
< class Operation,
class T >
binder2nd<Operation> bind2nd
(const Operation& op,
const T& x);
Description STL provides two adaptors for pointers to functions: one for unary
and the other for binary functions. Both the functions have the same
name (which is overloaded).
ptr_fun–unary
Description This function adapter accepts a pointer to a unary function that
takes an argument of type Arg and returns a result of type Result.
A function object of type pointer_to_unary_function<Arg,
Result> is constructed out of this argument, and returned.
Prototype template
< class Arg,
class Result >
ptr_fun(Result (*x) (Arg));
ptr_fun–binary
Description This function adapter accepts a pointer to a binary function that ac-
cepts arguments of type Arg1 and Arg2 and returns a result of type
Result. A function object of type
pointer_to_binary_function<Arg, Result> is constructed
out of this argument, and returned.
Prototype template
< class Arg,
class Result >
ptr_fun(Result (*x) (Arg1, Arg2));
Specialized Algorithms
All the iterators that are used as formal template parameters in
these algorithms are required to have their operator* return an
object for which operator& is defined and returns a pointer to T.
See “Overview of Iterators” on page 283 where algorithms are dis-
cussed in detail.
uninitialized_copy
Description This function behaves as follows: while (first != last) con-
struct (&*result++, *first++); This function returns re-
sult.
Prototype template
< class InputIterator,
class ForwardIterator >
ForwardIterator uninitialized_copy
(InputIterator first,
InputIterator last,
ForwardIterator result);
uninitialized_fill
Description This function behaves as follows:
while (first != last)
construct (&*first++, x);
Prototype template
< class ForwardIterator,
class T >
void uninitialized_fill
(ForwardIterator first,
ForwardIterator last,
const T& x);
uninitialized_fill_n
Description This function behaves as follows:
while (n--)
construct (&*first++, x);
Prototype template
< class ForwardIterator,
class Size,
class T>
void uninitialized_fill_n
(ForwardIterator first, Size n, const T& x);
~auto_ptr();
Constructor–auto_ptr
Description This function requires p to point to an object of class X or a class de-
rived from X for which delete p is defined and accessible. or else p
is a null pointer.
auto_ptr Destructor
Description Destroys the auto pointer.
Prototype ~auto_ptr();
auto_ptr::get
Description This function returns the pointer p specified as the argument to the
constructor auto_ptr (X* p) or as the argument to the most re-
cent call to reset (X* p).
auto_ptr::release
Description This function releases the pointer and after a call to this function
get() will return 0.
Assignment Operator=auto_ptr
Description Copies the argument a to *this.
Dereferencing Operator*auto_ptr
Description This returns *get () provided get() does not return 0.
Association Operator–>auto_ptr
Description Returns the pointer associated.
copy Used for copying a NTCTS that does not contain the NTCTS
already.
static char_type* copy
(char_type*, const char_type*, size_t);
not_eof Used for bool inequality checking.
static int_type not_eof
(const int_type&);
to_char_type Used to convert to a char type from an int_type
static char_type to_char_type
(const int_type&);
to_int_type Used to convert from a char type to an int_type.
static int_type to_int_type
(const char_type&);
eq_int_type Used to test for deletion.
static bool eq_int_type
(const int_type&, const int_type& );
get_state Used to store the state of the file buffer.
static state_type get_state
(pos_type pos);
eof Used to test for the end of a file.
static int_type eof();
NOTE: The assign, eq and lt are the same as the =, == and < op-
erators.
namespace std {
template
<class charT,
class traits =char_traits<charT>,
class Allocator = allocator<charT> >
class basic_string;
template
<class charT, class traits, class Allocator>
basic_string <charT,traits, Allocator>
operator+
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
const charT* lhs,
const basic_string
<charT, traits, Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(charT lhs, const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const basic_string
<charT,traits,Allocator>& lhs, charT rhs);
template
<class charT, class traits, class Allocator>
bool operator==
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator==
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator==
(const basic_string<charT,
traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator!=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits, Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator!=
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator!=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator<
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator<
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator>
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator<=
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
bool operator>=
template
<class charT, class traits, class Allocator>
void swap
(basic_string<charT,traits,Allocator>& lhs,
basic_string<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
operator>>
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str);
template
<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<
(basic_ostream<charT, traits>& os,
const basic_string
<charT,traits,Allocator>& str);
template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str,
charT delim);
template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str);
public:
typedef traits traits_type;
typedef typename traits::char_type value_type;
typedef Allocator allocator_type;
typedef typename Allocator::size_type size_type;
typedef typename Allocator::difference_type
difference_type;
typedef typename Allocator::reference reference;
typedef typename Allocator::const_reference
const_reference;
typedef typename Allocator::pointer pointer;
typedef typename Allocator::const_pointer
const_pointer;
// typedef implementation defined iterator;
// typedef implementation definedconst_iterator;
typedef std::reverse_iterator<iterator>
reverse_iterator;
typedef std::reverse_iterator<const_iterator>
const_reverse_iterator;
explicit basic_string
(const Allocator& a = Allocator());
basic_string
(const basic_string& str,
size_type pos = 0,
size_type n = npos,
const Allocator& a = Allocator());
basic_string
(const charT* s,
size_type n,
const Allocator& a = Allocator());
basic_string
(const charT* s,
const Allocator& a = Allocator());
basic_string
(size_type n,
charT c,
~basic_string();
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
size_type copy
(charT* s, size_type n,
size_type pos = 0) const;
void swap(basic_string<charT,traits,Allocator>&);
size_type find_first_not_of
(const basic_string& str,
size_type pos = 0) const;
size_type find_first_not_of
(const charT* s, size_type pos,
size_type n) const;
size_type find_first_not_of
(const charT* s, size_type pos = 0) const;
size_type find_first_not_of
(charT c, size_type pos = 0) const;
size_type find_last_not_of
(const basic_string& str,
size_type pos = npos) const;
size_type find_last_not_of
(const charT* s,
size_type pos, size_type n) const;
size_type find_last_not_of
(const charT* s, size_type pos = npos) const;
size_type find_last_not_of
(charT c, size_type pos = npos) const;
basic_string substr
(size_type pos = 0, size_type n = npos) const;
int compare(const basic_string& str) const;
int compare(
size_type pos1, size_type n1,
const basic_string& str) const;
int compare
(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2) const;
int compare(const charT* s) const;
int compare
(size_type pos1, size_type n1, const charT* s,
size_type n2 = npos) const;
};
}
Constructors
basic_string
(const basic_string& str,
size_type pos = 0,
size_type n = npos,
const Allocator& a = Allocator());
Remarks This constructor takes a string class argument and cre-
ates a copy of that string, with size of the length of that string and a
capacity at least as large as that string.
• An exception is thrown upon failure
basic_string
(const charT* s,
size_type n,
const Allocator& a = Allocator());
Remarks This constructor takes a const char array argument
and creates a copy of that array with the size limited to the size_type
argument.
• The charT* argument shall not be a null pointer
• An exception is thrown upon failure
basic_string
(const charT* s,
const Allocator& a = Allocator());
Remarks This constructor takes an const char array argu-
ment. The size is determined by the size of the char array.
• The charT* argument shall not be a null pointer
basic_string
(size_type n,
charT c,
const Allocator& a = Allocator());
Remarks This constructor creates a string of size_type n size re-
peating charT c as the filler.
• A length_error is thrown if n is less than npos.
template<class InputIterator>
basic_string
(InputIterator begin,
InputIterator end,
const Allocator& a = Allocator());
Remarks This iterator string takes InputIterator arguments and
creates a string with its first position starts with begin and its end-
ing position is end. Size is the distance between beginning and
end.
Destructor
Assignment Operator
Description Assigns the input string, char array or char type to the current
string.
Remarks Both of the overloaded functions construct a string object from the
input s, and append it to the current string.
begin
end
rbegin
rend
21.3.3 Capacity
Member functions for determining a strings capacity.
size
length
max_size
resize
Remarks If the size of the string is longer than size_type n, it shortens the
string to n, if the size of the string is shorter than n it appends the
string to size n with charT c or charT() if no filler is specified.
capacity
reserve
clear
empty
operator[]
at
21.3.5 Modifiers
Operators for appending a string.
21.3.5.1 operator+=
21.3.5.2 append
basic_string& append(
const basic_string& str,
size_type pos,size_type n);
template<class InputIterator>
basic_string& append
(InputIterator first, InputIterator last);
21.5.3.3 assign
basic_string& assign
(const basic_string& str,
size_type pos, size_type n);
template<class InputIterator>
basic_string& assign
(InputIterator first, InputIterator last);
Remarks If there is a size argument whichever is smaller the string size or ar-
gument value will be assigned.
21.3.5.4 insert
basic_string& insert
(size_type pos1, const basic_string& str,
basic_string& insert
(size_type pos, const charT* s, size_type n);
basic_string& insert
(size_type pos, const charT* s);
basic_string& insert
(size_type pos, size_type n, charT c);
iterator insert(iterator p, charT c = charT());
template<class InputIterator>
void insert
(iterator p, InputIterator first,
InputIterator last);
21.3.5.5 erase
21.3.5.6 replace
basic_string& replace
(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2);
basic_string& replace
(size_type pos, size_type n1,
const charT* s,size_type n2);
basic_string& replace
(size_type pos, size_type n1, const charT* s);
basic_string& replace
(size_type pos, size_type n1,
size_type n2, charT c);
basic_string& replace
(iterator i1, iterator i2,
const basic_string& str);
basic_string& replace
(iterator i1, iterator i2,
const charT* s, size_type n);
basic_string& replace(
iterator i1, iterator i2, const charT* s);
basic_string& replace
(iterator i1, iterator i2,
size_type n, charT c);
template<class InputIterator>
basic_string& replace
(iterator i1, iterator i2,
InputIterator j1, InputIterator j2);
21.3.5.7 copy
Remarks The function copy does not pad the string with Null
characters.
21.3.5.8 swap
c_str
data
get_allocator
21.3.6.1 find
size_type find
(const charT* s, size_type pos,
size_type n) const;
size_type find
(const charT* s, size_type pos = 0) const;
21.3.6.2 rfind
size_type rfind
(const charT* s, size_type pos,
size_type n) const;
size_type rfind
(const charT* s, size_type pos = npos) const;
size_type rfind
21.6.3.3 find_first_of
Description Finds the first position of one of the elements in the function’s argu-
ment starting from the beginning.
size_type find_first_of
(const charT* s, size_type pos,
size_type n) const;
size_type find_first_of
(const charT* s, size_type pos = 0) const;
size_type find_first_of
(charT c, size_type pos = 0) const;
21.3.6.4 find_last_of
Description Finds the last position of one of the elements in the function’s argu-
ment starting from the beginning.
size_type find_last_of
(const charT* s,
size_type pos, size_type n) const;
size_type find_last_of
(const charT* s, size_type pos = npos) const;
size_type find_last_of
(charT c, size_type pos = npos) const;
21.3.6.5 find_first_not_of
Description Finds the first position that is not one of the elements in the func-
tion’s argument starting from the beginning.
size_type find_first_not_of
(const charT* s, size_type pos,
size_type n) const;
size_type find_first_not_of
(const charT* s, size_type pos = 0) const;
size_type find_first_not_of
(charT c, size_type pos = 0) const;
21.3.6.6 find_last_not_of
Description Finds the last position that is not one of the elements in the func-
tion’s argument starting from the beginning.
size_type find_last_not_of
(const charT* s,
size_type pos, size_type n) const;
size_type find_last_not_of
size_type find_last_not_of
(charT c, size_type pos = npos) const;
21.3.6.7 substr
21.3.6.8 compare
int compare(
size_type pos1, size_type n1,
const basic_string& str) const;
int compare
(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2) const;
int compare
(size_type pos1, size_type n1, const charT* s,
size_type n2 = npos) const;
Returns Less than zero if the string is smaller than the argument lex-
icographically, zero if the string is the same size as the argu-
ment lexicographically and greater than zero if the string is
larger than the argument lexicographically.
Prototype template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const basic_string
<charT,traits, Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(charT lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
template
<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+
(const basic_string
<charT,traits,Allocator>& lhs, charT rhs);
21.3.7.2 operator==
Prototype template
<class charT, class traits, class Allocator>
bool operator==
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator==
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator==
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
21.3.7.3 operator!=
Prototype template
<class charT, class traits, class Allocator>
bool operator!=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator!=
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator!=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
21.3.7.4 operator<
Prototype template
<class charT, class traits, class Allocator>
bool operator<
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
Returns True if the first argument is lexicographically less than the sec-
ond argument otherwise false.
21.3.7.5 operator>
Prototype template
<class charT, class traits, class Allocator>
bool operator>
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
21.3.7.6 operator<=
Prototype template
<class charT, class traits, class Allocator>
bool operator<=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<=
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator<=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
21.3.7.7 operator>=
Prototype template
<class charT, class traits, class Allocator>
bool operator>=
(const basic_string
<charT,traits,Allocator>& lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>=
(const charT* lhs,
const basic_string
<charT,traits,Allocator>& rhs);
template
<class charT, class traits, class Allocator>
bool operator>=
(const basic_string
<charT,traits,Allocator>& lhs,
const charT* rhs);
21.3.7.8 swap
Description This non member swap exchanges the first and second arguments.
Prototype template
<class charT, class traits, class Allocator>
void swap
(basic_string<charT,traits,Allocator>& lhs,
basic_string
<charT,traits,Allocator>& rhs);
operator>>
Prototype template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
operator>>
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str);
operator<<
Description Inserts characters from a string object from into a output stream.
Prototype template
<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<
(basic_ostream<charT, traits>& os,
const basic_string
<charT,traits,Allocator>& str);
getline
Prototype template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline
(basic_istream<charT,traits>& is,
basic_string
<charT,traits,Allocator>& str,
charT delim);
template
<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str)
Character Support
String Support
The standard provides for namespace and wide character type for
Null Terminated Character Type Sequence functionality.
Description The localization library is a set of classes that help C++ program-
mers to encapsulate the cultural differences that come up especially
while porting an application across different user communities.
Hence, this library provides a set of classes that include internation-
alization support for character classification, string collation, for-
matting and parsing of date, time, numeric and monetary quanti-
ties, message retrieval etc.
locale, facet etc., which are part of the C++ standard library and the
header <locale> declares the elements of localization library from
the standard C library.
Class locale
Class locale is used for implementing a type-safe polymorphic
collection of facets (feature-sets) indexed by facet types. The follow-
ing sections illustrate the components of the class locale.
Typedef Declarations
Description Category, when given a legal value, represents a collection of fac-
ets. Valid category values include 0 and the locale member bit-
Constructors
Default Constructor
Description Default constructor constructs a locale which is a snapshot of the
current global locale. The current global locale can be set by calling
either the standard “C” function setlocale() or locale::glo-
bal(const locale&).
Remarks Constructs a locale using the standard C locale names (for example,
“POSIX”). If the argument std_name passed to it is not a valid
Prototype locale
(const locale& other,
const char* std_name,
category cat);
Remarks Creates a locale as a copy of other except for the facets identified
by the category argument cat, for which the semantics will be the
same as that of the second argument std_name. The resulting locale
will have a name if and only if other has a name.
Prototype template
< class Facet >
locale
(const locale& other,
Facet* f);
Remarks A locale is constructed which does not have a name. The con-
structed locale has all the features set from the first locale argument
other, except that of the type Facet, for which the second argu-
ment is used.
Prototype template
< class Facet >
locale
(const locale& other,
const locale& one);
Remarks A locale which does not have a name is constructed such that all
the facets are incorporated from the first argument other and that
facet which is identified by the template parameter Facet, is incor-
porated from the second argument one. If the second argument
does not have a facet of that particular type, runtime_error ex-
ception is thrown.
Prototype locale
(const locale& other,
Remarks A locale is constructed which has all the facets from the first argu-
ment other, except those facet(s) that are specified by the category
argument cat. These facets that are specified by the categories are
installed from the second argument. The constructed locale will
have a name if and only if the first two locales are named.
Remarks Since member templates are not supported, our library does not
provide this function yet.
locale::name
locale::name locale::has
locale::use
Description The name of *this, if it has one; otherwise, the string “*”.
locale::has
Description An indication whether the facet requested is present in *this. Also,
see use.
Remarks The semantics of this function is the same as explained above, ex-
cept that locale argument is also passed as an argument, instead of
being implicit.
locale::use
Description The function returns a reference to the Facet of the locale. If the facet
requested in not present in the locale on which the function was ap-
plied but present in the current global locale, returns the global lo-
cale’s instance of Facet.
Remarks The semantics of this function is the same as explained above, ex-
cept that locale argument is also passed as an argument, instead of
being implicit.
locale::global
locale::global locale::classic
locale::transparent
Description The function sets the global locale to its argument. Subsequent calls
to the default constructor and of other library functions affected by
the function setlocale(), use the locale loc until the next call to
this function or setlocale().
locale::classic
Description A call to this member returns the standard “C” locale. This is equiv-
alent to constructing a locale using a call to the constructor lo-
cale(“C”).
locale::transparent
Description This function returns the continuously updated global locale. A lo-
cale which implements semantics that vary dynamically as the glo-
bal locale is changed.
Global Operators
Table 7.4 The global operators are:
Description This function tries to read a line into a string and construct a locale
from it. If either operation fails, sets failbit of streams. This operator
is not yet implemented in our library.
Prototype template
< class charT,
class Traits>
basic_istream<charT, Traits>& operator >>
(basic_istream<charT,
Traits>& s,
locale& loc);
Prototype template
< class charT,
class Traits >
basic_ostream<charT, Traits>& operator <<
(basic_ostream<charT,
Traits>& s,
locale& loc);
Class facet
Description Class facet is the base class for locale feature sets. Declaration of
the class facet is given below.
protected :
facet (size_t refs = 0);
virtual ~facet ();
private :
facet (const facet&); // not defined
void operator= (const facet&); // not
defined
};
where name names the locale, and the refs argument is passed to
the base class constructor. If there is no “..._byname” version of a
particular facet, the base class implements such semantics itself.
//...
protected :
~Facet () {}
};
Remarks There are 6 different categories in which the facets provided by C++
localization library are divided. They are collate, ctype, mone-
tary, numeric, time, messages. Each of the standard categories
includes a family of facets. See also:
• “The Numerics Category” on page 158
• “The Collate Category” on page 165
• “Ctype Category” on page 167
• “The Monetary Category” on page 178
Class id
Description This class is used for identification of a locale facet. A mandatory
object of this class used as an index in every derived facet facilitates
lookup and initialization of facets. This type-id mechanism ensures
that every facet type installed in a locale is assigned a unique id. Id
is for every facet type and not for every facet object.
Class numpunct
Description This class specifies numeric punctuation. The base class provides
classic “C” numeric formats, while numpunct_byname version sup-
ports named locale (e.g. POSIX, X/OPEN) numeric formatting se-
mantics. Other two numeric facets, num_get and num_put use
numpunct facet installed in a particular locale to parse/format nu-
meric quantities.
numpunct::char_type
Definition typedef charT char_type;
numpunct::string
Definition typedef basic_string<charT> string;
numpunct::decimal_point
numpunct::decimal_point numpunct::thousands_sep
numpunct::grouping numpunct::truename
numpunct::falsename
Description The function returns a string for use as the decimal radix separator.
The base class implementation of this member returns a “.”. The
num_get<charT,InputIterator> class is not required to recog-
nize numbers formatted using a decimal radix separator if it is not a
one-character string.
numpunct::thousands_sep
Description The function returns a string which is the thousand separator. The
base class implementation of this member returns the empty string.
The num_get<charT, InputIterator> class is not required to
recognize the numbers formatted using a thousand separator if is
not a one-character string.
numpunct::grouping
Description This function returns a vector vec in which vec[i] represents the
number of digits in the group at position i starting with 0 as the
rightmost group. If vec.size() <= i, the number is the same as
group (i-1); if (i < 0 || vec[i] <= 0), the size of the digit
group is unlimited. The base-class implementation this returns the
empty vector.
numpunct::truename
Description Returns a string representing the name of the boolean value true.
The base class implementation return the strings “true”.
numpunct::falsename
Description Returns a string representing the name of the boolean value false.
The base class implementation return the strings “false”.
Class num_get
Description Template class num_get has the following set of typedef’s and pub-
lic member functions.
• “Typedef Declarations num_get” on page 161
• “Public Member Functions num_get” on page 162
char_type
Definition typedef charT char_type;
iter_type
Definition typedef InputIterator iter_type;
ios
Definition typedef basic_ios<charT> ios;
num_get::get
Description All the above functions read characters from in, interpreting them
according to flags set in str and the ctype<charT> facet and num-
punct<charT> facet installed in the locale loc. These functions ig-
nore the state of str initially. But they indicate failure by calling
str.setstate (ios_base::failbit). If an error occurs, v is
not changed; otherwise it is set to the resulting value. Digit group-
ing separators are optional; if present, digit grouping is checked
after the entire number is read. When reading a non-numeric bool-
ean value, the names are compared exactly.
(iter_type in,
iter_type end,
ios& str,
const locale&,
double& v) const;
iter_type get
(iter_type in,
iter_type end,
ios& str,
const locale&,
long double& v) const;
Class num_put
Description Template class num_put has the following set of typedef’s and
public member functions.
• “Typedef Declarations num_put” on page 163
• “Public Member Functions num_put” on page 164
char_type
Definition typedef charT char_type;
iter_type
Definition typedef OutputIterator iter_type;
ios
Definition typedef basic_ios<charT> ios;
num_put::put
Description All the above functions write characters to the sequence out, for-
matting val according to the flags set in str, ctype<charT> and
numpunct<charT> facets installed inside locale loc. These func-
tions insert digit group separators as specified by
numpunct<charT>::grouping().
Remarks All the above functions ignore and do not change the stream state.
They return an iterator pointing immediately after the last character
produced.
Class Collate
Description This class provides features for use in the collation (comparison)
and hashing of strings. A locale member function template, opera-
tor(), uses the collate facet to allow a locale to act directly as the
predicate argument for standard algorithms (see Chapter 9) and
containers operating on strings. The base class implementation ap-
plied lexicographic ordering (see 9.30).
• “Typedef Declarations collate” on page 165
• “Public Member Functions collate” on page 166
char_type
Definition typedef charT char_type;
string
Definition typedef basic_string<charT> string;
collate::compare
collate::compare collate::transform
collate::hash
Description Compares the two strings and returns 1 if the first string is greater
than the second, -1 if less; zero otherwise.
collate::transform
Description This function returns a string that, when compared lexicographi-
cally with the result of calling transform() on another string,
yields the same result as calling compare() on the same two
strings.
collate::hash
Description Returns an integer value equal to the result of calling hash() on
any other string for which compare() returns 0(i.e equal) when
passed the two strings.
Ctype Category
In this category, there are two templatized classes, ctype<charT>
and codecvt<fromtT, toT, stateT>. There is also a specializa-
tion of ctype<charT> for the char data type.
Class ctype<charT>
Description The definition of class ctype_base which is the base class for
ctype is given below.
char_type
Definition typedef charT char_type;
ctype::is
ctype::is ctype::do_is
ctype::scan_is ctype::scan_not
ctype::toupper ctype::tolower
ctype::widen ctype::narrow
Prototype bool is
(ctype_mask mask,
char_type c) const;
ctype::do_is
Description This function classify a character or sequence of characters. For each
argument character, this function identifies a value M of type
ctype::scan_is
Description This function locates a character in the buffer [low, high) that
conforms to the classification mask, mask. It returns the smallest
pointer p in the range [low, high) such that (*p) would return
true; otherwise, returns high.
ctype::scan_not
Description This function locates a character in the buffer [low, high) that
fails to the classification mask, mask. It returns the smallest pointer
p in the range [low, high) such that (*p) would return false;
otherwise, returns high.
ctype::toupper
Description These functions convert a character or sequence of characters to
upper-case. The first function returns the corresponding upper-case
character if it is known to exist, or its argument if not. The second
form replaces each character *p in the range [low, high) for
which a corresponding upper-case character exists, with that char-
acter and returns high.
ctype::tolower
Description These functions convert a character or sequence of characters to
lower-case. The first function returns the corresponding lower-case
character if it is known to exist, or its argument if not. The second
form replaces each character *p in the range [low, high) for
which a corresponding lower-case character exists, with that charac-
ter and returns high.
ctype::widen
Description These function apply the simplest reasonable transformation from a
char value or sequence of char values to the corresponding
char_type value or values. The only characters for which unique
transformations are required are the digits, alphabetic characters, ‘-’,
‘+’, newline and space. For any character c, the transformed charac-
ter of c is not a member of any character classification that c is not
also a member of. The first function returns the transformed value
and the second form transforms each character *p in the range
ctype::narrow
Description These function apply the simplest reasonable transformation from a
char_type value or sequence of char_type values to the corre-
sponding char value or values. The only characters for which
unique transformations are required are the digits, alphabetic char-
acters, ‘-’, ‘+’, newline and space. For any character c, the trans-
formed character of c is not a member of any character classification
that c is not also a member of. In addition, the expression (nar-
row(c)-’0’) evaluates to the digit value of the character. The first
function returns the transformed value or dfault is no mapping is
readily available and the second form transforms each character *p
in the range [low, high) placing the result(or dfault if no sim-
plest transformation is readily available) in dest[p-low] and re-
turns high.
ctype::ctype_mask
Definition static const ctype_mask;
ctype::table_
Definition const ctype_ mask* const table_;
ctype::classic_table_
Definition static const mask classic_table_[UCHAR_MAX+1];
ctype::delete_it_
Definition bool delete_it_;
constructor ctype<char>
constructor ctype<char> ctype::is for
ctype<char>
ctype::scan_is for ctype::scan_not for
ctype<char> ctype<char>
ctype::tolower for ctype::toupper for
ctype<char> ctype<char>
ctype::widen for ctype::narrow for
ctype<char> ctype<char>
Description This constructor initializes the protected member table_ with the
tab argument if nonzero, or the static value classic_table_ otherwise,
and initializes the private member delete_it_ to (tab &&
del). The refs argument is passed to the base class constructor.
Prototype ctype
(const ctype_mask* tab = 0,
bool del = false,
size_t refs = 0);
Prototype bool is
(ctype_mask mask,
char c) const;
const char* is
(const char* low,
Class codecvt
Description Definition of class codecvt_base, used as a base class for codecvt
facet is given below.
from_type
Definition typedef fromT from_type;
to_type
Definition typedef toT to_type;
state_type
Definition typedef stateT state_type;
Class moneypunct
Description This class provides money punctuation, similar to numpunct<> of
the numerics category.
• “Typedef Declarations moneypunct” on page 179
• “Public Member Functions moneypunct” on page 179
char_type
Definition typedef charT char_type;
string_type
Definition typedef basic_string<charT> string_type;
moneypunct::decimal_point
moneypunct::decimal_point moneypunct::thousands_sep
moneypunct::groupint moneypunct::curr_symbol
moneypunct::positive_sign moneypunct::negative_sign
moneypunct::frac_digits moneypunct::neg_format
moneypunct::frac_digits
Prototype basic_string<charT,traits>
decimal_point() const;
moneypunct::thousands_sep
Description This function returns the digit group separator to use in case
grouping() specifies a digit grouping pattern.
Prototype basic_string<charT,traits>
thousands_sep() const;
Remarks The two functions above have been changed to return charT, in the
April 1995 draft. But this implementation still returns a string.
moneypunct::groupint
Description This function returns a vector vec in which vec[i] represents the
number of digits in the group at position i starting with 0 as the
rightmost group. If vec.size() <= i, the number is the same as
group (i-1); if (i < 0 || vec[i] <= 0), the size of the digit
group is unlimited. The base-class implementation this returns the
empty vector.
moneypunct::curr_symbol
Description This function returns the string to use as the currency identifier
symbol.
moneypunct::positive_sign
Description This function returns the string to use to indicate a positive mone-
tary value.
moneypunct::negative_sign
Description This function returns the string to use to indicate a negative mone-
tary value. If this is a one-char-string containing ‘(‘, it is paired with
a matching ‘)’.
moneypunct::frac_digits
Description This function returns the number of digits after the decimal radix
separator, if any.
moneypunct::pos_format
Description This function returns a four-element array specifying the order in
which the syntactic elements appear in the monetary format. In this
array, each element is an enumeration value of type
money_base::part. Each enumeration value appears exactly
once. none, if present, is not first; space, if present, is neither first
nor last. Otherwise, the elements may appear in any order. In inter-
national instantiations, the result is always { symbol, sign,
none, value}.
moneypunct::neg_format
Description This function returns a four-element array specifying the order in
which the syntactic elements appear in the monetary format. In this
array, each element is an enumeration value of type
money_base::part. Each enumeration value appears exactly
once. none, if present, is not first; space, if present, is neither first
nor last. Otherwise, the elements may appear in any order. In inter-
national instantiations, the result is always { symbol, sign,
none, value}.
Class money_put
Description Class money_put contains the following set of typedefs and public
member functions.
• “Typedef Declarations money_put” on page 182
• “Public Member Functions money_put” on page 182
char_type
Definition typedef charT char_type;
iter_type
Definition typedef OutputIterator iter_type;
string
Definition typedef basic_string<charT> string;
ios
Definition typedef basic_ios<charT> ios;
money_put::put
Description Writes characters to s, according to the format specified by the mon-
eypunct<charT> facet of loc, and f.flags (). Ignores any frac-
tional part of units, or any characters in digits beyond the(optional)
leading ‘-’ and immediately subsequent digits. If format flags spec-
ify filling with internal space, the fill characters are placed where
none or space appears in the formatting pattern. Returns an iterator
pointing immediately after the last character produced.
Class money_get
Description Class money_get contains the following set of typedefs and public
member functions.
• “Typedef Declarations money_get” on page 183
• “Public Member Functions money_get” on page 184
char_type
Definition typedef charT char_type;
iter_type
Definition typedef InputIterator iter_type;
string
Definition typedef basic_string<charT> string;
ios
Definition typedef basic_ios<charT> ios;
money_get::get
Description These functions read characters from s until they have constructed
a monetary value, as specified in str.flags() and the money-
punct<charT> facet of loc, or until it encounters an error or runs
out of characters. The result is a pure sequence of digits, represent-
ing a count of the smallest unit of currency representable. Digit
group separators are optional; if present, digit grouping is checked
after all syntactic elements have been read. Where space or none
appear in the format pattern, except at the end optional whitespace
is consumed. These functions set units or digits from the se-
quence of digits found. units is negated, or digits is preceded by
‘-’ for a negative value. These functions indicate a failure by calling
str.setstate (failbit). On error, units or digits argument
is unchanged. These function return an iterator pointing immedi-
ately beyond the last character recognized as part of a valid mone-
tary quantity.
all the container classes. These features are discussed in this section
as well.
The common members of all STL containers fall into two distinct
categories: type definitions and member functions. We
take a look at each in turn.
value_type
Definition X::value_type
reference
Description Type that can be used for storing into X::value_type objects. This
type is usually X::value_type&.
Definition X::reference
const_reference
Definition X::const_reference
pointer
Definition X::pointer
iterator
Definition X::iterator
const_iterator
Description A iterator type that can be used with constant instances of type X. It
is either a constant random access iterator type (for vector or deque)
or a constant bidirectional iterator type (for other containers).
Definition X::const_iterator
reverse_iterator
Definition X::reverse_iterator
const_reverse_iterator
Definition X::const_reverse_iterator
difference_type
Description The type that can represent the difference between any two X itera-
tor objects (varies with the memory model).
Definition X::difference_type
size_type
Description The type that can represent the size of any X instance (varies with
the memory model).
Definition X::size_type
Default Constructor
Prototype X()
Prototype X(a);
Prototype X u(a);
Destructor
Prototype (&a)->~X();
begin
Description Returns an iterator (const_iterator for constant a), that can be used
to begin traversing all locations in the container.
Prototype a.begin();
end
Description Returns an iterator (const_iterator for constant a), that can be used
in a comparison for ending traversal through the container.
Prototype a.end();
rbegin
Prototype a.rbegin();
rend
Prototype a.rend();
Equality Operator ==
Prototype a == b
Prototype a != b
Assignment Operator =
Prototype r = a
size
Prototype a.size();
max_size
Prototype a.max_size();
empty
Prototype a.empty();
Prototype a < b
Prototype a > b
Prototype a <= b
Prototype a >= b
swap
Prototype a.swap(b);
Remarks From the above definitions, we note that several comparison func-
tions, constructors, type definitions and other member functions are
shared between all STL containers, allowing their interfaces to be
very uniform.
Prototype X(n,t);
X a(n,t);
X(i,j);
X a(i,j);
insert
Prototype a.insert(p,t);
Prototype a.insert(p,n,t);
Prototype a.insert(p,i,j);
erase
Prototype a.erase(q);
Equality of Keys
For associative containers, it is important to note that equality of
keys depends on the equivalence relation imposed by the compari-
son, and not on the operator== on keys. Thus, two keys k1 and k2
are considered equal if, for a comparison object comp,
comp(k1,k2)==false && comp(k2,k1)==false.
Additional Definitions
The set and map containers support unique keys; they can store at
most one element of each key. multiset and multimap containers
support equal keys; i.e., they can store multiple elements that have
the same key.
For set and multiset, the value type is the same as the key type; i.e.,
the values stored in sets and multisets are basically the keys them-
selves. For map and multimap, the value type is pair<const
Key,T>; i.e., the elements stored in maps and multimaps are pairs
whose first elements are const Key values and whose second ele-
ments are T values.
Listed below are the type definitions and member functions defined
by associative containers in addition to the common container mem-
bers outlined previously.
Description The type of keys, Key, with which the container is instantiated.
Definition X::key_type
key_compare
Description The comparison object type, Compare, with which the container is
instantiated.
Definition X::key_compare
value_compare
Definition X::value_compare
Constructors
Prototype X();
X a;
Prototype X(c);
X a(c);
key_comp
Prototype a.key_comp();
value_comp
Prototype a.value_comp();
insert
Prototype a_uniq.insert(t);
Remarks Inserts t if and only if there is no element in the container with key
equal to the key of t. Returns a pair<iterator,bool> whose
bool component indicates whether the insertion was made and
whose iterator component points to the element with key equal to
the key of t. Takes time logarithmic in the size of the container.
a_eq.insert(p,t);
Remarks Inserts t into the container and returns the iterator pointing to the
newly inserted element.
a.insert(p,t);
Remarks Inserts t if and only if there is no element with key equal to the key
of t in containers that support unique keys (i.e., sets and maps). Al-
ways inserts t in containers that support equal keys (i.e., multisets
and multimaps). Iterator p is a hint pointing to where the insert
should start to search. Takes time logarithmic in the size of the con-
tainer in general, but amortized constant if t is inserted right after p.
a.insert(i,j);
Remarks Inserts the elements from the range [i,j) into the container. Takes
NlogN time in general, where N is the distance from i to j. Linear if
[i,j) is sorted according to value_comp().
erase
Prototype a.erase(k);
Remarks Erases all elements in the container with key equal to k. Returns the
number of erased elements.
a.erase(q);
Remarks Erases all the elements in the range [q1,q2). Takes log(size() + N)
time, where N is the distance from q1 to q2.
find
Prototype a.find(k);
count
Prototype a.count(k);
lower_bound
Description Returns an iterator pointing to the first element with key not less
than k.
Prototype a.lower_bound(k);
upper_bound
Description Returns an iterator pointing to the first element with key greater
than k.
Prototype a.upper_bound(k);
equal_range
Prototype a.equal_range(k);
Declaration template
< class T >
class vector;
const_iterator
T*
reference
Description The type T& that can be used for storing into T objects.
const_reference
const_reference;
Definition The type const T& that can be used for storing into T objects.
size_type
Description size_type is an unsigned integral type that can represent the size of
any vector instance.
difference_type
Description A signed integral type that can represent the difference between any
two pointers to vector::iterator objects.
value_type
reverse_iterator
const_reverse_iterator
Prototype vector();
Remarks Constructs a vector of size n and initial izes all its elements with
value. If the second argument is not supplied, value is obtained
with the default constructor, T(), for the element value type T.
Assignment Operator =
Description The vector assignment operator. Replaces the contents of the cur-
rent vector with a copy of the parameter vector x.
Reserve
Remarks Reallocation invalidates all the references, pointers, and iterators re-
ferring to the elements in the vector. It is guaranteed that no reallo-
cation takes place during the insertions that happen after reserve
takes place till the time when the size of the vector reaches the size
specified by reserve.
Destructor
Description The vector destructor. Returns all allocated storage back to the free
store.
Prototype ~vector();
vector::swap
Description Swaps the contents of the current vector with those of the input vec-
tor x. The current vector replaces x and vice versa.
vector::end
vector::rbegin
vector::rend
vector::size
vector::max_size
vector::capacity
Description Returns the largest number of elements that the vector can store
without reallocation. See also the reserve member function.
vector::empty
Subset Operator []
Description Returns the nth element from the beginning of the vector in constant
time.
vector::front
Description Returns the first element of the vector; i.e., the element referred to
by the iterator begin(). Undefined if the vector is empty.
vector::back
Description Returns the last element of the vector; i.e., the element pointed to by
the iterator (end()-1) . Undefined if the vector is empty.
vector::push_back
vector::insert
Remarks Inserts the element x at the position in the vector referred to by the
iterator position. Elements already in the vector are moved as re-
quired. The iterator returned refers to the position at which the ele-
ment was inserted.
Remarks Copies of elements in the range [first,last) are inserted into the vec-
tor at the position referred to by the iterator position.
Prototype
void pop_back();
vector::erase
Remarks Erases the element of the vector pointed to by the iterator position.
Remarks The iterators first and last are assumed to point into the vector, and
all elements in the range [first,last) are erased from the vector.
erase invalidates all iterators and references after the point of the
erase.The destructor of T is called for each erased element and the
assignment operator of T is called the number of times equal to the
number of elements in the vector after the erased elements.
Description This class implements a deque of objects of type T. Deques are very
much like vectors, except that they can be expanded in both direc-
tions: they allow constant time insertion and deletion ob objects at
either end.
iterator
const_iterator
pointer
reference
Description The type T& that can be used for storing into T objects.
const_reference
Description The type const T& for const references that can be used for storing
into T objects.
size_type
Description size_type is an unsigned integral type that can represent the size of
any deque instance.
difference_type
Description A signed integral type that can represent the difference between any
two deque::iterator objects.
value_type
reverse_iterator
const_reverse_iterator
Prototype deque();
Remarks Constructs a deque of size n, and initializes all its elements with
value. The default for value is set to T(), where T() is the default con-
structor of the type passed to the deque class template.
Prototype deque
(const_iterator first,
const_iterator last);
Assignment Operator =
Remarks The deque assignment operator. Replaces the contents of the current
deque with a copy of the parameter deque x.
Destructor
Description The set destructor. Returns all allocated storage back to the free
store.
Prototype ~deque();
deque::swap
Description Swaps the contents of the current deque with those of the input
deque x. The current deque replaces x and vice versa.
deque::end
deque::rbegin
deque::rend
deque::size
deque::max_size
deque::empty
Subset Operator []
deque::front
Description Returns the first element of the deque; i.e., the element pointed to by
the iterator begin().
deque::back
Description Returns the last element of the deque; i.e., the element pointed to by
the iterator (end()-1) .
deque::push_back
deque::insert
Remarks Inserts the element x at the position in the deque pointed to by the
iterator position. The iterator returned points to the position that
contains the inserted element.
Description Inserts elements into the deque before the position pointed to by the
iterator position. Copies of elements in the range [first,last) are in-
serted into the deque.
Description
Prototype
void pop_front();
deque::pop_back
deque::erase
Remarks Erases the element of the deque pointed to by the iterator position.
void erase(iterator first, iterator last);
Remarks The iterators first and last are assumed to point into the deque, and
all elements in the range [first,last) are erased from the deque.
Storage Management
As with all STL containers, all storage management in deques is
handled automatically. Deques are implemented using segmented
storage (unlike vectors). This means that all deque elements are not
necessarily kept in contiguous locations in memory.
Complexity of Insertion
Deques are specially optimized for insertion of single elements at ei-
ther the beginning or the end of the data structure. Such insertions
always take constant time and cause a single call to the copy con-
structor of T, where T is the type of the inserted object.
from the insertion point to the beginning of the deque and the dis-
tance from the insertion point to the end of the deque.
The insert and push member functions invalidate all the iterators
and references to the deque.
Declaration template
< class T >
class list;
Description This class implements the sequence abstraction as a linked list. All
lists are “doubly-linked” and may be traversed in either direction.
Besides sort, lists also include some other special member functions
for splicing two lists, reversing lists, making all list elements unique
and for merging two lists. All of these special member functions are
discussed on “Special Operations list” on page 230.
iterator
const_iterator
pointer
reference
Description The type T& that can be used for storing into T objects.
const_reference
Description The type const T& for const references that can be used for storing
into T objects.
size_type
Description size_type is an unsigned integral type that can represent the size of
any list instance.
difference_type
Description A signed integral type that can represent the difference between any
two list::iterator objects.
value_type
reverse_iterator
const_reverse_iterator
Prototype list();
Description Constructs a list of size n, and initializes all its elements with value.
Remarks The list copy constructor. Constructs a list and initializes it with
copies of the elements of list x .
Remarks Constructs a list of size last-first and initializes it with copies of ele-
ments in the range [first,last).
Assignment Operator =
Description The list assignment operator. Replaces the contents of the current
list with a copy of the parameter list x.
Destructor
Description The list destructor. Returns all allocated storage back to the free
store.
Prototype ~list();
list::swap
Description Swaps the contents of the current list with those of the input list x.
The current list replaces x and vice versa.
Description Returns an iterator (const_iterator for constant list) that can be used
to begin traversing through the list.
list::end
Description Returns an iterator (const_iterator for constant list) that can be used
in a comparison for ending traversal through the list.
list::rbegin
list::rend
list::size
list::max_size
list::empty
Description Returns true if the list contains no elements (i.e., if begin() == end()),
false otherwise
list::front
Description Returns the first element of the list; i.e., the element pointed to by
the iterator begin() .
list::back
Description Returns the last element of the list; i.e., the element pointed to by the
iterator (end()-1) .
list::push_back
list::insert
Remarks Inserts the element x at the position in the list pointed to by the iter-
ator position. The iterator returned points to the position that con-
tains the inserted element.
Remarks Inserts elements into the list before the position pointed to by the it-
erator position. Copies of elements in the range [first,last) are in-
serted into the list.
list::pop_back
list::erase
Description Erases one or more elements of the list pointed to by the iterator po-
sition.
Remarks Erases the element of the list pointed to by the iterator position.
Remarks The iterators first and last are assumed to point into the list, and all
elements in the range [first, last) are erased from the list.
Description These member functions inserts the contents of list x before the iter-
ator position, and x becomes empty.
Remarks This member function inserts the contents of list x before the iterator
position, and x becomes empty. The operation takes constant time.
Essentially, the contents of x are transferred into the current list.
Remarks Inserts the element pointed to by iterator x_elem from list x before
position, and removes the element from x. It takes constant time.
x_elem is assumed to be a valid iterator of the list x. The function ba-
sically transfers a single element from the list x into the current list.
Remarks Inserts the elements in the range [first, last) before the iterator posi-
tion, and removes the elements from list x. The operation takes lin-
ear time. The range [first,last) is assumed to be a valid range in x.
list::remove
Description This function removes all elements in the list that are equal tovalue,
using T::operator==. The relative order of other elements is not
affected. The entire list is traversed exactly once.
list::unique
Description This function erases all but the first element from every consecutive
group of equal elements in the list. Exactly size()-1 applications of
T::operator== are done. This function is most useful when the list is
sorted, so that all elements that are equal appear in consecutive po-
sitions. In that case, each element in the resulting list is unique.
list::merge
Description This function merges the argument list x into the current list. It is as-
sumed that both lists are sorted according to the operator< of type
T. The merge is stable; i.e., for equal elements in the two lists, the el-
ements from the current list always precede the elements from the
list::reverse
Description Reverses the order of the elements in the list. It takes linear time.
list::sort
Description Sorts the list according to the operator< of type T. The sort is stable;
i.e., the relative order of equal elements is preserved. Approxi-
mately NlogN comparisons are done, where N is equal to size().
Declaration template
< class Key,
class Compare = less<Key> >
class set;
Description A set<Key, Compare> stores unique elements of type Key, and al-
lows for the retrieval of the elements themselves. All elements in the
set are ordered by the ordering relation Compare, which induces a
total ordering on the elements.
As with all STL containers, the set container only allocates storage
and provides a minimal set of operations (such as insert, erase, find,
count, etc.). The set does not itself provide operations for union, in-
tersection, difference etc. These operations are handled by generic
algorithms in STL.
key_type
Description The type of the keys with which the set is instantiated.
value_type
Description value_type represents the type of the values stored in the set. This is
the same as key_type.
value_type represents the type of the values stored in the set. This is
the same as key_type.
pointer
reference
Description The type Key& that can be used for storing into Key objects.
const_reference
Description The type Const Key& for const references that can be used for stor-
ing into Key objects.
The type Key& (const Key& for const references) that can be used
for storing into Key objects.
compare_key
Description The comparison object type, Compare, with which the set is instan-
tiated. This type is used to order the keys in the set.
value_compare
Description This is the ordering relation that is used to order the values stored in
the set. Its type is the same as key_compare, since the type of a value
stored in a set is the same as the type of the key.
iterator
const_iterator
size_type
Description size_type is an unsigned integral type that can represent the size of
any set instance.
difference_type
Description A signed integral type that can represent the difference between any
two set::iterator objects.
reverse_iterator
const_reverse_iterator
Description The default constructor. Constructs an empty set using the relation
comp to order the elements.
Remarks The set copy constructor. Constructs a set and initializes it with cop-
ies of the elements of set x.
Prototype set
(const value_type* first,
const value_type* last,
const Compare& comp = Compare());
Assignment Operator =
Description The set assignment operator. Replaces the contents of the current set
with a copy of the parameter set x.
set::swap
Description Swaps the contents of the current set with those of the input set x.
The current set replaces x and vice versa.
Destructor
Description The set destructor. Returns all allocated storage back to the free
store.
Prototype ~set();
const set<Key,
Compare>& y);
Description This function returns the comparison object of the set. The compari-
son object is an object of class Compare, which represents the order-
ing relation used to construct the set.
set::value_comp
set::begin
Description Returns the iterator that can be used to begin traversing through all
locations in the set.
set::end
Description Returns an iterator that can be used in a comparison for ending tra-
versal through the set.
set::rbegin
set::rend
set::empty
set::size
set::max_size
Description Returns the maximum possible size of the set. The maximum size is
simply the total number of elements of type Key that can be repre-
sented in the memory model used.
Remarks Inserts the element x into the set if x is not already present in the set.
The iterator position is a hint, indicating where the insert function
should start to search to do the insert. The search is necessary since
sets are ordered containers.
Remarks Inserts the element x into the set if x is not already present in the set.
The returned value is a pair, whose bool component indicates
whether the insertion has taken place, and whose iterator compo-
nent points to the just inserted element in the set, if the insertion
takes place, otherwise to the element x already present.
Remarks Copies of elements in the range [first,last) are inserted into the set.
This insert member function allows elements from other containers
to be inserted into the set.
Remarks Erases the set element pointed to by the iterator position. The time
taken is amortized constant.
Remarks Erases all the set elements with key equal to x (i.e., removes all x’s
from the set). Returns the number of erased elements, which is 1 if x
is present in the set, and 0 otherwise (since sets do not store dupli-
cate elements). In general, this function takes time proportional to
log (size()) + count(x) , where count(k) is a set member function that
returns the number of elements with key equal to k.
Remarks The iterators first and last are assumed to point into the set, and all
elements in the range [first,last) are erased from the set. The time
taken is log(size())+N, where N is the distance from first to last.
Description Searches for the element x in the set. If x is found, the function re-
turns the iterator pointing to it. Otherwise, end() is returned. The
function takes O(log N) time, where N is the number of elements in
the set.
set::count
Description Returns the number of elements in the set that are equal to x. If x is
present in the set, this number is always 1; otherwise, it is 0. The
function takes O(log(size())) time.
set::lower_bound
Description Returns an iterator pointing to the first set element whose key is not
less than x. Since set elements are not repeated, the returned iterator
points to x itself if x is present in the set. If x is not present in the set,
end() is returned. The function takes O(log N) time, where N is the
number of elements in the set.
set::upper_bound
Description The upper_bound function returns an iterator to the first set ele-
ment whose key is greater than x. If no such element is found, end()
is returned. The function takes O(log N) time, where N is the num-
ber of elements in the set.
set::equal_range
Declaration template
< class Key,
class Compare = less<Key> >
class multiset;
The interface of the multiset class is exactly the same as that of the
regular set class. The only difference is that multisets possibly con-
tain multiple values of the same key value. As a result, some of the
member functions also have slightly different semantics.
key_type
Description The type of the keys with which the multiset is instantiated.
value_type
Description value_type represents the type of the values stored in the multiset.
This is the same as key_type.
pointer
reference
Description The type Key& that can be used for storing into Key objects.
const_reference
Description The type const Key& for const references that can be used for stor-
ing into Key objects.
key_compare
Description The comparison object type, Compare, with which the multiset is in-
stantiated. This type is used to order the keys in the multiset.
value_compare
Description This is the ordering relation that is used to order the values stored in
the multiset. Its type is the same as key_compare, since the type of a
value stored in a multiset is the same as the type of the key.
iterator
const_iterator
size_type
Description size_type is an unsigned integral type that can represent the size of
any multiset instance.
difference_type
Description A signed integral type that can represent the difference between any
two multiset::iterator objects.
reverse_iterator
const_reverse_iterator
Description The default constructor. Constructs an empty multiset using the re-
lation comp to order the elements.
Prototype multiset
(const value_type* first,
const value_type* last,
const Compare& comp = Compare());
Assignment Operator =
Description The multiset assignment operator. Replaces the contents of the cur-
rent multiset with a copy of the parameter multiset x.
multiset::swap
Description Swaps the contents of the current multiset with those of the input
multiset x. The current multiset replaces x and vice versa.
Destructor
Description The multiset destructor. Returns all allocated storage back to the
free store.
Prototype ~multiset();
Description This function returns the comparison object of the multiset. The
comparison object is an object of class Compare, which represents
the ordering relation used to construct the multiset.
multiset::value_comp
multiset::begin
Description Returns the iterator that can be used to begin traversing through all
locations in the multiset.
multiset::end
Description Returns an iterator that can be used in a comparison for ending tra-
versal through the multiset.
multiset::rbegin
multiset::rend
multiset::empty
multiset::size
multiset::max_size
Description Returns the maximum possible size of the multiset. The maximum
size is simply the total number of elements of type Key that can be
represented in the memory model used.
Remarks Inserts the element x into the multiset if x is not already present in
the multiset. The iterator position is a hint, indicating where the in-
sert function should start to search to do the insert. This insertion
Remarks Inserts the element x into the multiset and returns the iterator point-
ing to the newly inserted element.The function takes O(log N) time,
where N is the number of elements in the multiset.
Remarks Copies of elements in the range [first,last) are inserted into the mul-
tiset. This insert member function allows elements from other con-
tainers to be inserted into the multiset.
Remarks Erases the multiset element with key equal to x (i.e., removes all x’s
from the multiset). Returns the number of erased elements. In gen-
eral, this function takes time proportional to log (size()) + count(x),
Remarks The iterators first and last are assumed to point into the multiset,
and all elements in the range [first,last) are erased from the multiset.
The time taken is log(size())+N, where N is the distance from first to
last.
Description Searches for the element x in the multiset. If x is found, the function
returns the iterator pointing to it. Otherwise, end() is returned. The
function takes O(log N) time, where N is the number of elements in
the multiset.
multiset::count
Description Returns the number of elements in the multiset that are equal to x.
The function takes O(log N) time, where N is the number of ele-
ments in the multiset.
multiset::lower_bound
Description Returns an iterator pointing to the first multiset element whose key
is not less than x. If no such element is found, end() is returned. The
function takes O(log N) time, where N is the number of elements in
the multiset.
multiset::upper_bound
Description The upper_bound function returns an iterator to the first multiset el-
ement whose key is greater than x. If no such element is found,
end() is returned. The function takes O(log N) time, where N is the
number of elements in the multiset.
multiset::equal_range
Declaration template
< class Key,
class T,
class Compare = less<Key> >
class map;
Elements are stored in maps as pairs in which each Key has an asso-
ciated value of type T. Since maps store only unique keys, each map
contains is at most one <Key, T> pair for each Key value. It is not
possible to associate a single Key with more than one value.
key_type
value_type
Description value_type represents the type of the values stored in the map.
Since maps store pairs of values, value_type is a pair which associ-
ates every key (of type Key) with a value of type T.
key_compare
Description This is the comparison object type, Compare, with which the map is
instantiated. It is used to order keys in the map.
value_compare
iterator
const_iterator
pointer
reference
Description The type pair<const Key,T>& that can be used for storing into
map::value_type objects.
const_reference
Description The type const Key,T>& (const pair<const Key,T>& for const refer-
ences that can be used for storing into map::value_type objects.
size_type
Description size_type is an unsigned integral type that can represent the size of
any map instance.
difference_type
Description A signed integral type that can represent the difference between any
two map::iterator objects.
reverse_iterator
const_reverse_iterator
Description The default constructor. Constructs an empty map using the rela-
tion comp to order the elements.
Remarks The map copy constructor. Constructs a map and initializes it with
copies of the elements of map x.
Prototype map
(const value_type* first,
const value_type* last,
const Compare& comp = Compare());
Assignment Operator =
Description The map assignment operator. Replaces the contents of the current
map with a copy of the parameter map x.
map::swap
Description Swaps the contents of the current map with those of the input map
x. The current map replaces x and vice versa.
Destructor
Description The map destructor. Returns all allocated storage back to the free
store.
Prototype ~map();
Description This function returns the comparison object of the map. The com-
parison object is an object of class Compare, which represents the
ordering relation used to construct the map.
map::value_comp
map::begin
map::end
map::rbegin
map::rend
map::empty
map::size
map::max_size
Description Returns the maximum possible size of the map. The maximum size
is simply the total number of elements of type Key that can be repre-
sented in the memory model used.
Sub Operator []
Remarks Inserts the value x into the map if x is not already present in the
map. The iterator position is a hint, indicating where the insert func-
tion should start to search to do the insert. This insertion takes O(log
N) time in general, where N is the number of elements in the set, but
is amortized constant if x is inserted right after the iterator position.
Remarks Inserts the value x into the map if x is not already present in the
map. The returned value is a pair , whose bool component indicates
whether the insertion has taken place, and whose iterator compo-
nent points to the just inserted value in the map, if the insertion
takes place, otherwise to the value x already present.
NOTE: If Notice, that x is a pair of type pair< Key, T>. The func-
tion takes O(log N) time, where N is the number of elements in the
set.
Remarks Copies of elements in the range [first,last) are inserted into the map.
This insert member function allows elements from other containers
to be inserted into the map. In general, this insertion takes
O(Nlog(size()+N)) time, where N is the distance from first to last,
and O(N) time if the range [first,last) is sorted according to the map
ordering relation value_comp() .
Remarks Erases the map element pointed to by the iterator position. The time
taken is amortized constant.
Remarks Erases the map element with key equal to x (i.e., removes all pairs
whose first element is x from the map). Returns the number of
erased elements, which is 1 if x is present in the map, and 0 other-
wise. In general, this function takes time proportional to log (size())
+ count(x) , where count(k) is a map member function that returns
the number of elements with key equal to k.
Remarks The iterators first and last are assumed to point into the map, and all
elements in the range [first,last) are erased from the map. The time
taken is log(size())+N, where N is the distance from first to last.
Description Searches the map for an element with Key equal to x. If such an ele-
ment is found, the function returns the iterator (const_iterator for
map::count
Description Returns the number of elements in the map with Key equal to x. If
an element with Key equal to x has been inserted into the map then
this number is always 1; otherwise, it is 0.
map::lower_bound
map::upper_bound
map::equal_range
Declaration template
< class Key,
class T,
class Compare = less<Key> >
class multimap;
key_type
value_type
Description value_type represents the type of the values stored in the multimap.
Since multimaps store pairs of values, value_type is a pair which as-
sociates every key (of type Key) with a value of type T.
key_compare
Description This is the comparison object type, Compare, with which the map is
instantiated. It is used to order keys in the map.
value_compare
iterator
const_iterator
value_type*
reference
Description The type pair<const Key,T>& that can be used for storing into
map::value_type objects.
const_reference
Description The type const pair<const Key,T>& for const references that can be
used for storing into map::value_type objects.
size_type
Description size_type is an unsigned integral type that can represent the size of
any map instance.
difference_type
Description A signed integral type that can represent the difference between any
two map::iterator objects.
reverse_iterator
const_reverse_iterator
Prototype multimap
(const multimap<Key,
T,
Compare>& x);
Assignment Operator =
multimap::swap
Description Swaps the contents of the current multimap with those of the input
multimap x. The current multimap replaces x and vice versa.
Destructor
Description The multimap destructor. Returns all allocated storage back to the
free store.
Prototype ~multimap();
Description This function returns the comparison object of the multimap. The
comparison object is an object of class Compare, which represents
the ordering relation used to construct the multimap.
multimap::value_comp
multimap::begin
multimap::end
multimap::rbegin
multimap::rend
multimap::empty
multimap::size
multimap::max_size
Description Returns the maximum possible size of the multimap. The maximum
size is simply the total number of elements of type Key that can be
represented in the memory model used.
Remarks Inserts the value x into the multimap if x is not already present in
the multimap. The iterator position is a hint, indicating where the
insert function should start to search to do the insert. The insertion
takes O(log N) time in general, where N is the number of elements
in the map, but is amortized constant if x is inserted right after the
iterator position.
Remarks Inserts the value x into the multimap and returns the iterator point-
ing to the newly inserted value.
NOTE: The value x is a pair of the form pair<const Key, T>. The
insertion takes O(log N) time, where N is the number of elements
in the map.
void insert
(const value_type* first,
const value_type* last);
Remarks Copies of elements in the range [first,last) are inserted into the mul-
timap. This insert member function allows elements from other con-
tainers to be inserted into the multimap. In general, the time taken
for this insertion is O(Nlog(size()+N)), where N is the distance from
first to last, and O(N) if the range [first,last) is sorted according to
the multimap ordering relation value_comp().
Description Erases one or more elements or values from the multimap object.
Remarks Erases the multimap element pointed to by the iterator position. The
time taken is amortized constant.
Remarks Erases the multimap element with key equal to x (i.e., removes all
pairs whose first element is x from the multimap). Returns the num-
ber of erased elements.
Remarks The iterators first and last are assumed to point into th e multimap,
and all elements in the range [first,last) are erased from the multi-
map. The time taken is O(log(size()) + N) , where N is the distance
from first to last.
Description Searches the multimap for an element with Key equal to x. If such
an element is found, the function returns the iterator (const_iterator
for constant multimaps) pointing to it. Otherwise, end() is returned.
The function takes O(log N) time, where N is the number of ele-
ments in the multimap.
multimap::count
Description Returns the number of elements in the multimap with key equal to
x.
multimap::lower_bound
multimap::upper_bound
multimap::equal_range
Description A stack is a data structure that allows the following operations: in-
sertion at one end, deletion from the same end, retrieving the value
at the end, and testing for emptiness. Thus, stacks provide a “last-
in/first-out” service. The element deleted or retrieved is always the
last one inserted.
stack::size
Description Returns the current size of the stack (i.e the number of elements the
stack currently holds).
stack::top
Description Returns the element at the top of the stack. The stack remains un-
changed.
stack::push
stack::pop
(const stack<container>& x,
const stack<container>& y);
queue::size
Description Returns the current size of the queue (i.e the number of elements the
queue currently holds).
queue::front
Description Returns the element at the front of the queue. The queue remains
unchanged.
queue::back
Description Returns the element at the end of the queue. This is the element that
was last inserted into the queue. The queue remains unchanged.
queue::push
queue::pop
NOTE: Since > is used instead of <, the element available for re-
trieval at any time is actually the smallest element rather than the
largest.
Constructors priority_queue
Default Constructor
Prototype priority_queue
(const value_type* first,
const value_type* last,
const Compare& x = Compare());
priority_queue::size
Description Returns the current size of the priority_queue (i.e the number of ele-
ments the priority_queue currently holds).
priority_queue::top
priority_queue::push
priority_queue::pop
Overview of Iterators
This chapter is a reference guide to the requirements that must be
satisfied by a class or a built-in type to be used as an iterator. The –
iterators of a particular category include: stream iterator classes, it-
erator adaptors (reverse iterators and insert iterators).
Value type
Iterators are objects that have operator* returning a value of some
class or built-in type T called the value type of the iterator.
Distance type
For every iterator type for which equality is defined, there is a corre-
sponding signed integral type called the distance type of the
iterator.
Past-the-end values
Just as a regular pointer to an array guarantees that there is a valid
pointer value pointing past the last element of the array, so for any
iterator type there is an iterator value that points past the last ele-
ment of a corresponding container. These values are called past-
the-end values.
Dereferenceable values.
Values of the iterator for which operator* is defined are called
dereferenceable. STL components never assume that past-the-end
values are dereferenceable.
Singular values.
Iterators might also have singular values that are not associated
with any container. For example, after the declaration of an unini-
tialized pointer x (as with int* x;), x should always be assumed
to have a singular value of a pointer. Results of most expressions are
undefined for singular values. The only exception is an assignment
of a non-singular value to an iterator that holds a singular value. In
this case the singular value is overwritten the same way as any
other value. Dereferenceable and past-the-end values are always
non-singular.
Reachability
An iterator j is called reachable from an iterator i if and only if
there is a finite sequence of applications of operator++ to i that
makes i == j. If i is reachable from j, they refer to the same con-
tainer.
Ranges
Most of the library’s algorithmic templates that operate on contain-
ers have interfaces that use ranges. A range is a pair of iterators that
serve as beginning and end markers for a computation. A range [i,
i) is an empty range; in general, a range [i, j) refers to the posi-
tions in a container starting with the one referred to by i up to but
not including the one pointed to by j. Range [i, j) is valid if and
only if j is reachable from i. The result of the application of the al-
gorithms in the library to invalid ranges is undefined.
NOTE: For all iterator operations that are required in each cate-
gory, the computing time requirement is constant time (amor-
tized). For this reason, we will not mention computing times sepa-
rately in any of the following sections on requirements.
Iterator Requirements
This section discusses the requirements for all five types of iterators.
The topics in this section are:
• “Input Iterator Requirements” on page 286
• “Output Iterator Requirements” on page 287
In this and the following four requirements sections, for each itera-
tor type X we will assume
• a and b denote values of type X,
• n denotes a value of the distance type for X,
• r denotes a value of X&,
• t denotes a value of value type T, and
• u, tmp, and m denote identifiers.
Stream Iterators
The library provides stream iterators, defined by template
classes, to allow algorithms to work directly with input/output
streams. The istream_iterator class defines input iterator types
and the ostream_iterator class defines output iterator types. For
example, the following code fragment:
istream_iterator<int> end_of_stream;
partial_sum_copy(istream_iterator<int>(cin),
end_of_stream,ostream_iterator<int>(cout,“\n”));
reads a file containing integers from the input stream cin, and
prints the partial sums to cout, separated by newline characters.
Prototype template
template
< class T,
class charT,
class traits = char_traits<charT>
Constructor istream_iterator
Default Constructor
Description Constructs the end-of-stream iterator value.
Prototype istream_iterator();
Destructor
Prototype ~istream_iterator();
Dereferencing Operator *
Description Dereferencing operator. By returning a reference to const T, it en-
sures that it cannot be used to write values to the input stream for
which the iterator is constructed.
Incrementation Operator ++
Description Incrementation operators.
Remarks This operator reads and stores a value of T each time it is called.
Remarks This operator reads and stores x values of T each time it is called.
Equality Operator ==
Description Equality operator. Two end-of-stream iterators are always equal. An
end-of-stream iterator is not equal to a non-end-of-stream iterator.
Two non-end-of-stream iterators are equal when they are con-
structed from the same stream.
Prototype template
< class T,
class Distance>
bool operator==
(const istream_iterator<T,Distance>& x,
const istream_iterator<T,Distance>& y);
Prototype template
< class T,
class charT,
class traits = char_traits<charT> >
class ostream_iterator : public output_iterator;
Remarks It is not possible to read a value of the output iterator. It can only be
used to write values out to an output stream for which it is con-
structed.
Constructor ostream_iterator
Default Constructor
Description Constructs an iterator that can be used to write to the output stream
s.
Destructor
Prototype ~ostream_iterator ();
Dereferencing Operator *
Description Dereferencing operator. An assignment *o = t through an output
iterator o causes t to be written to the output stream and the stream
pointer advanced in preparation for the next write.
Assignment Operator =
Description Assignment operator. Replaces the current iterator with a copy of
the iterator x.
Incrementation Operator ++
Description These operators are present to allow ostream iterators to be used
with algorithms that both assign through an output iterator and ad-
char_type
Prototype typedef charT char_type;
traits_type
Prototype typedef traits traits_type;
streambuf
Prototype typedef basic_streambuf<charT, traits>
streambuf;
istream
Prototype typedef basic_istream<charT,
traits istream;
Constructor istreambuf_iterator
Default Constructor
Description Constructs an end-of-stream iterator.
Prototype istreambuf_iterator
(basic_istream<charT, traits>& s);
Operators istreambuf_iterator
Dereferencing Operator *
Description This operator extracts one character pointed to by the streambuf
*sbuf_.
Incrementation Operator ++
Description These operators advances the iterator.
();
Remarks This operator advances the iterator and returns the result.
Remarks This operator advances the iterator and returns the proxy object
keeping the character pointed to by the previous iterator.
istream_iterator::equal
Description This function returns true if and only if both iterators are either at
end-of-stream, or are the end-of-stream value, regardless of what
streambuf they iterator over.
istream_iterator::iterator_category
Description Returns the category of the iterator s.
Equality Operator ==
Description operator== returns a.equal (b).
Prototype template
< class charT,
class traits >
bool operator==
(istreambuf_iterator<charT, traits>& a,
istreambuf_iterator<charT, traits>& b);
Prototype template
< class charT,
class traits >
bool operator!=
(istreambuf_iterator<charT,
traits>& a,
istreambuf_iterator<charT, traits>& b);
char_type
Prototype typedef charT char_type;
traits_type
Prototype typedef traits traits_type;
streambuf
Prototype typedef basic_streambuf<charT, traits>
streambuf;
ostream
Prototype typedef basic_ostream<charT, traits> ostream;
Constructor ostreambuf_iterator
Default Constructor
Description Constructs an iterator with sbuf_ set to 0.
Operators ostreambuf_iterator
Dereferecing Operator *
Description This operator returns *this.
ostreambuf_iterator::equal
Description This function returns true if sbuf_ == b.sbuf_.
ostreambuf_iterator::iterator_category
Description Returns output_iterator_tag().
Equality Operator ==
Description operator== returns a.equal (b).
Prototype template
< class charT,
class traits >
bool operator!=
(ostreambuf_iterator<charT,
traits>& a,
ostreambuf_iterator<charT,
traits>& b);
Prototype template
< class BidirectionalIterator,
class T,
class Reference = T&,
class Distance = ptrdiff_t >
class reverse_bidirectional_iterator : public
bidirectional_iterator<T, Distance>
Constructor reverse_bidirectional_iterator
Default Constructor
Prototype reverse_bidirectional_iterator();
Overloaded Constructors
Prototype explicit reverse_bidirectional_iterator
(BidirectionalIterator x);
reverse_bidirectional_iterator::base
Prototype BidirectionalIterator base();
Dereferencing Operator *
Prototype Dereference operator *();
Incrementation Operator ++
Prototype reverse_bidirectional_iterator
< BidirectionalIterator,
T,
Reference,
Distance >&
operator ++();
Prototype reverse_bidirectional_iterator
< BidirectionalIterator,
T,
Reference,
Distance >
operator ++(int);
Decrementation Operator --
Prototype reverse_bidirectional_iterator
< BidirectionalIterator,
T,
Reference,
Distance>&
operator --();
Prototype reverse_bidirectional_iterator
<BidirectionalIterator,
T,
Reference,
Distance>
operator --(int);
Equality Operator ==
Description Return a true if the reverse_bidirectional_iterator x is
equal to reverse_bidirectional_iterator y.
Prototype
template
< class BidirectionalIterator, class T, class Distance >
bool operator ==
(const reverse_bidirectional_iterator
<BidirectionalIterator, T, Reference, Distance >& x,
const reverse_bidirectional_iterator
<BidirectionalIterator, T, Reference, Distance>& y);
Prototype template
< class RandomAccessIterator,
class T,
class Reference = T&,
class Distance = ptrdiff_t >
class reverse_iterator : public
random_access_iterator <T, Distance>;
Constructor reverse_iterator
Default Constructor
Prototype reverse_iterator();
reverse_iterator::base
Prototype RandomAccessIterator base();
Dereferencing Operator *
Prototype Reference operator *();
Incrementation Operator ++
Prototype reverse_iterator
< RandomAccessIterator,
T,
Reference,
Distance >&
operator ++();
Prototype reverse_iterator
< RandomAccessIterator,
T,
Reference,
Distance >
operator ++(int);
Decrementation Operator --
Prototype reverse_iterator
< RandomAccessIterator,
T,
Reference,
Distance>&
operator --();
Prototype reverse_iterator<RandomAccessIterator, T,
Reference, Distance> operator --(int);
Add Operator +
Prototype reverse_iterator
< RandomAccessIterator,
T,
Reference,
Distance >
operator+
(Distance n) const;
Minus Operator -
Prototype reverse_iterator
< RandomAccessIterator,
T,
Reference,
Distance >
operator -
(Distance n) const;
(Distance n);
Subset Operator []
Prototype Reference operator[] (Distance n);
Equality Operator ==
Prototype
template
< class RandomAccessIterator,
class T,
class Reference,
class Distance >
bool operator ==
(const reverse_iterator
<RandomAccessIterator, T, Reference, Distance>& x,
const reverse_iterator
< RandomAccessIterator, T, Reference, Distance>& y);
Minus Operator -
Prototype
template
< class RandomAccessIterator,
class T,
class Reference,
class Distance >
Distance operator -
(const reverse_iterator
< RandomAccessIterator, T, Reference, Distance >& x,
const reverse_iterator
< RandomAccessIterator, T, Reference, Distance >& y);
Add Operator +
Prototype
template
< class RandomAccessIterator,
class T,
class Reference,
class Distance >
Reverse_iterator< RandomAccessIterator,T, Reference, Distance >
operator +
(Distance n,
const reverse_iterator
<RandomAccessIterator,T,Reference,Distance>& x);
Prototype template
< class Container >
class back_insert_iterator : public
output_iterator;
Constructor back_insert_iterator
Copy Constructor
Prototype explicit back_insert_iterator(Container& x);
Assignment Operator =
Prototype back_insert_iterator
< Containe r>&
operator=
(const typename
Container::value_type& value);
Dereferencing Operator *
Prototype back_insert_iterator<Container>& operator*();
Incrementation Operator ++
Prototype back_insert_iterator<Container>& operator++();
back_insert_iterator::back_inserter
Prototype template
< class Container >
back_insert_iterator
< Container > back_inserter(Container& x);
Prototype template
< class Container >
class front_insert_iterator : public
output_iterator;
Constructor front_insert_iterator
Copy Constructor
Prototype explicit front_insert_iterator(Container& x);
Assignment Operator =
Prototype front_insert_iterator<Container>& operator =
(const typename Container::value_type& value);
Dereferencing Operator *
Prototype front_insert_iterator<Container>& operator*();
Incrementation Operator ++
Prototype front_insert_iterator<Container>& operator++();
Prototype front_insert_iterator
< Container >
operator++(int);
front_insert_iterator::front_inserter
Prototype template
< class Container >
front_insert_iterator< Container >
front_inserter(Container& x);
Prototype template
< class Container >
class insert_iterator : public output_iterator;
Constructor insert_iterator
Copy Constructor
Prototype insert_iterator
(Container& x,
typename Container::iterator i);
Assignment Operator =
Prototype insert_iterator< Container >& operator =
(const typename
Container::value_type& value);
Dereferencing Operator *
Prototype insert_iterator< Container >& operator*();
Incrementation Operator ++
Prototype insert_iterator< Container >& operator++();
insert_iterator::inserter
Prototype template
< class Container,
class Iterator >
insert_iterator< Container > inserter
(Container& x, Iterator i);
All of the library algorithms are generic, in the sense that they can
operate on a variety of data structures. The algorithms are not di-
rectly parameterized in terms of data structures. Instead, they are
parameterized by iterator types. This allows the algorithms to work
with user-defined data structures, as long as these data structures
have iterator types satisfying the assumptions of the algorithms.
Finally, algorithms that take predicates end with the suffix _if
(which follows the suffix _copy, for copying algorithms).
Binary Predicates
A BinaryPredicate class is used whenever an algorithm expects
a function object that when applied to the result of dereferencing
two corresponding iterators or to dereferencing an iterator and a
type T (where T is part of the function signature), returns a value
testable as true.
BinaryPredicate always takes the first iterator type as its first ar-
gument. That is, in those cases when T value is part of the function
signature, binary_pred can be used as follows:
if (binary_pred(first, value)) {....}
for_each
Description The for_each algorithm applies a specified function to each ele-
ment of the input container.
Prototype template
< class InputIterator,
class Function >
Function for_each
(InputIterator first,
InputIterator last,
Function f);
find
Description The first version of the algorithm traverses the iterators (first,
last] and returns the first iterator i such that *i == value. In ei-
ther case, if such an iterator is not found then the iterator last is re-
turned.
Prototype template
< class InputIterator,
class T >
InputIterator find
(InputIterator first,
InputIterator last,
const T& value);
find_if
Description The second version returns the first iterator i such that pred(*i)
== true. In either case, if such an iterator is not found then the iter-
ator last is returned.
Prototype template
adjacent_find
Description The adjacent_find algorithm returns an iterator i referring to the
first consecutive duplicate element in the range [first, last), or
last if there is no such element. By consecutive duplicate, it is
meant that an element is equal to the element immediately follow-
ing it in the range.
Prototype template
< class InputIterator >
InputIterator adjacent_find
(InputIterator first,
InputIterator last);
template
< class InputIterator,
class BinaryPredicate >
InputIterator adjacent_find
(InputIterator first,
InputIterator last,
BinaryPredicate binary_pred);
Remarks Comparisons are done using operator== in the first version of the
algorithm and a function object binary_pred in the second ver-
sion.
count
Description The count algorithm adds the number of elements in the range
[first, last) that are equal to value, and places the result into
the reference argument n.
Prototype template
< class InputIterator,
class T,
class Size >
void count(InputIterator first,
InputIterator last,
const T& value,
Size& n);
Remarks Count must store the result into a reference argument since it can-
not deduce the size type from the built-in iterator types, such as
int*.
count_if
Description The count_if algorithm adds to n the number of iterators in the
range [first, last) for which the condition pred(*i) ==
true is satisfied.
Prototype template
< class InputIterator,
class Predicate,
class Size >
void count_if
(InputIterator first,
InputIterator last,
Predicate pred,
Size& n);
mismatch
Description mismatch compares corresponding pairs of elements from two
ranges, and returns the first mismatched pair.
Prototype template
< class InputIterator1,
class InputIterator2 >
pair<InputIterator1, InputIterator2> mismatch
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2);
template
< class InputIterator1,
class InputIterator2,
class BinaryPredicate >
pair<InputIterator1, InputIterator2> mismatch
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
BinaryPredicate binary_pred);
Remarks The algorithm finds the first position at which the values in the
range [first1, last1) disagree with the values in the range
starting at first2. It returns a pair of iterators i and j which sat-
isfy the following conditions:
• i points into the range [first, last)
• j points into the range beginning at first2
• i and j are both equidistant from the beginning of their cor-
responding ranges.
• *i != *j, or binary_pred(i, j) == false, depending
on the version of mismatch invoked. In the first version,
checks for equality are made with operator== and in the
equal
Description equal returns true if the ranges [first1, last1) and the range
of size first1-last1 beginning at first2 contain the same ele-
ments in the same order, false otherwise.
Prototype template
< class InputIterator1,
class InputIterator2 >
bool equal
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2);
template
< class InputIterator1,
class InputIterator2,
class BinaryPredicate >
bool equal
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
BinaryPredicate binary_pred);
Remarks In the first version of equal, checks for element equality are made
with operator==, and in the second version they are made with
the function object pred.
search
Description search checks whether the second range [first2, last2) is
contained in the first range [first1, last1). If so, the iterator i
in [first1, last1) that represents the start of the second range
in the first is returned. Otherwise, the past-the-end location of the
first range, (i.e. last1), is returned.
Prototype template
< class ForwardIterator1,
class ForwardIterator2 >
void search
(ForwardIterator1 first1,
Forward Iterator1 last1,
ForwardIterator2 first2,
ForwardIterator2 last2);
template
< class ForwardIterator1,
class ForwardIterator2,
class BinaryPredicate >
void search
(ForwardIterator1 first1,
ForwardIterator1 last1,
ForwardIterator2 first2,
ForwardIterator2 last2,
BinaryPredicate binary_pred);
Remarks In the first version of the algorithm, checks for element equality are
made with operator==, while in the second they are made with
the function object binary_pred.
copy
Description copy copies elements from the sequence [first, last) to the se-
quence of size last - first beginning at the iterator result,
and returns the past-the-end iterator, result + last - first.
For each non-negative integer n < (last-first), the operation
*(result + n) = *(first + n) is performed. The result of
copy is undefined if result is in the range [first, last).
Prototype template
< class InputIterator,
class OutputIterator >
void copy
(InputIterator first,
InputIterator last,
OutputIterator result);
Complexity Time complexity is linear for both copy algorithms. At most n as-
signments are performed, where n is the size of the range [first,
last). Space complexity is constant.
copy_backward
Description copy_backward copies all of the values in the range [first,
last) to the range of size last - first starting at the iterator
result, and returns the iterator that contains the last element cop-
ied (i.e. the beginning of the sequence). For copy_backward, the
source and destination ranges may overlap if result >= last.
Prototype template
< class BidirectionalIterator1,
class BidirectionalIterator2 >
void copy_backward
(InputIterator first,
InputIterator last,
OutputIterator result);
Complexity Time complexity is linear for both copy algorithms. At most n as-
signments are performed, where n is the size of the range [first,
last). Space complexity is constant.
swap
Description The swap function exchanges two elements.
Prototype template
< class T >
void swap
(T &a,
T &b);
Complexity The time required is constant for swap and iter_swap. For
swap_ranges, the time complexity is linear. The number of swaps
performed is the size of the range [first, last). Space complex-
ity is constant for all the swap algorithms.
iter_swap
Description The function iter_swap exchanges values pointed to by two itera-
tors.
Prototype template
< class ForwardIterator1,
ForwardIterator2 >
void iter_swap
(ForwardIterator1 a,
ForwardIterator2 b);
Complexity The time required is constant for swap and iter_swap. For
swap_ranges, the time complexity is linear. The number of swaps
performed is the size of the range [first, last). Space complex-
ity is constant for all the swap algorithms.
swap_ranges
Description The function swap_ranges exchanges the elements in the range
[first, last) with those in the range of size last - first be-
ginning at first2. swap_ranges returns the past-the-end iterator,
first2+last-first.
Prototype template
< class ForwardIterator1,
class ForwardIterator2 >
ForwardIterator swap_ranges
(ForwardIterator1 first1,
ForwardIterator1 last1,
ForwardIterator2 first2);
Complexity The time required is constant for swap and iter_swap. For
swap_ranges, the time complexity is linear. The number of swaps
performed is the size of the range [first, last). Space complex-
ity is constant for all the swap algorithms.
transform
Description The first version of transform generates an output sequence of ele-
ments by applying a unary function op to each element of the input
sequence [first, last).
Prototype template
< class InputIterator,
class OutputIterator,
class UnaryOperation >
OutputIterator transform
(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryOperation op);
template
< class InputIterator1,
class InputIterator2,
class OutputIterator,
class BinaryOperation >
OutputIterator transform
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryOperation binary_op);
replace
Description The replace algorithm modifies the range [first, last) so that
all elements equal to old_value are replaced by new_value, while
other values remain unchanged.
Prototype template
< class ForwardIterator,
class T >
void replace
(ForwardIterator first,
ForwardIterator last,
const T& old_value,
const T& new_value);
Complexity Time complexity is linear for all replace algorithms. The number of
equality operations performed, or of applications of the predicate
pred, is the size of the range [first, last). Space complexity is
constant.
replace_if
Description replace_if modifies the range [first, last) so that all ele-
ments that satisfy the predicate pred are replaced by new_value,
while other values remain unchanged.
Prototype template
< class ForwardIterator,
class Predicate, class T >
void replace_if
(ForwardIterator first,
ForwardITerator last,
Predicate pred,
const T& new_value);
Complexity Time complexity is linear for all replace algorithms. The number of
equality operations performed, or of applications of the predicate
pred, is the size of the range [first, last). Space complexity is
constant.
replace_copy
Description replace_copy is similar to replace, except that the original se-
quence is not modified. Rather, the altered sequence is placed in the
range of size last - first beginning at result.
Prototype template
< class InputIterator,
class OutputIterator,
class T >
OutputIterator replace_copy
(InputIterator first,
InputIterator last,
OutputIterator result,
Complexity Time complexity is linear for all replace algorithms. The number of
equality operations performed, or of applications of the predicate
pred, is the size of the range [first, last). Space complexity is
constant.
replace_copy_if
Description replace_copy_if is similar to replace_if, except that the origi-
nal sequence is not modified. Rather, the altered sequence is placed
in the range of size last - first beginning at result.
Prototype template
< class InputIterator,
class OutputIterator,
class Predicate,
class T >
OutputIterator replace_copy_if
(InputIterator first,
InputIterator last,
OutputIterator result,
Predicate pred,
const T& new_value):
Complexity Time complexity is linear for all replace algorithms. The number of
equality operations performed, or of applications of the predicate
pred, is the size of the range [first, last). Space complexity is
constant.
fill
Description fill assigns value through all the iterators in the range [first,
last).
Prototype template
< class ForwardIterator,
class T >
void fill
(ForwardIterator first,
ForwardIterator
last,
const T& value);
Complexity Time complexity is linear. The number of assignments for both ver-
sions of the algorithm is the size of the range [first, last).
Space complexity is constant.
fill_n
Description fill_n assigns value through all the iterators in the range
[first, first + n).
Prototype template
< class ForwardIterator,
class Size,
class T >
void fill_n
(ForwardIterator first,
Size n,
const T& value);
Complexity Time complexity is linear. The number of assignments for both ver-
sions of the algorithm is the size of the range [first, last).
Space complexity is constant.
generate
Description generate fills the range [first, last) with the sequence gener-
ated by last - first successive calls to the function object gen.
Prototype template
< class ForwardIterator,
class Generator >
void generate
(ForwardIterator first,
ForwardIterator last,
Generator gen);
generate_n
Description generate_n fills the range of size n beginning at first with the
sequence generated by n successive calls to gen.
Prototype template
< class ForwardIterator,
class Size,
class Generator >
void generate_n
(ForwardIterator first,
Size n,
Generator gen);
remove
Description The function remove removes those elements from the range
[first, last) that are equal to value, and returns the location i
that is the past-the-end iterator for the resulting range of values that
are not equal to value.
Prototype template
< class ForwardIterator,
class T >
ForwardIterator remove
(ForwardIterator first,
ForwardIterator last,
const T& value);
All versions of remove are stable, that is, the relative order of the el-
ements that are not removed is the same as their relative order in
the original range.
Complexity Time complexity is linear for all versions of remove. The number of
assignments is the number of elements not removed, at most the
size of the range [first, last). Space complexity is constant for
all the remove algorithms.
remove_if
Description The function remove_if removes those elements from the range
[first, last) which satisfy the predicate pred, and returns the
location i that is the past-the-end iterator for the resulting range of
values that are not equal to value.
Prototype template
< class ForwardIterator,
class Predicate >
ForwardIterator remove_if
(ForwardIterator first,
ForwardIterator last,
Predicate pred);
All versions of remove are stable, that is, the relative order of the el-
ements that are not removed is the same as their relative order in
the original range.
Complexity Time complexity is linear for all versions of remove. The number of
assignments is the number of elements not removed, at most the
size of the range [first, last). Space complexity is constant for
all the remove algorithms.
remove_copy
Description remove_copy is similar to remove, except that the final resulting
sequences are copied into the range beginning at result.
Prototype template
< class InputIterator,
class OutputIterator,
class T >
OutputIterator remove_copy
(InputIterator first,
InputIterator last,
OutputIterator result,
const T& value);
Remarks All versions of remove are stable, that is, the relative order of the el-
ements that are not removed is the same as their relative order in
the original range.
Complexity Time complexity is linear for all versions of remove. The number of
assignments is the number of elements not removed, at most the
size of the range [first, last). Space complexity is constant for
all the remove algorithms.
remove_copy_if
Description remove_copy_if is similar to remove_if, except that the final re-
sulting sequences are copied into the range beginning at result.
Prototype template
< class InputIterator,
class OutputIterator,
class Predicate >
OutputIterator remove_copy_if
(InputIterator first,
InputIterator last,
OutputIterator result,
Predicate pred);
Remarks All versions of remove are stable, that is, the relative order of the el-
ements that are not removed is the same as their relative order in
the original range.
Complexity Time complexity is linear for all versions of remove. The number of
assignments is the number of elements not removed, at most the
size of the range [first, last). Space complexity is constant for
all the remove algorithms.
unique
Description unique eliminates consecutive duplicates from the range [first,
last). An element is considered to be a consecutive duplicate if it
is equal to an element in the location to its immediate right in the
range.
In the first version of unique, checks for equality are made using
operator==, while in the second they are made with the function
object binary_pred.
Prototype template
< class ForwardIterator >
ForwardIterator unique
(ForwardIterator first,
ForwardIterator last);
Prototype template
< class ForwardIterator,
class BinaryPredicate >
ForwardIterator unique
(Forwarditerator first,
ForwardIterator last,
BinaryPredicate binary_pred);
Remarks All versions of unique return the end of the resulting range.
Complexity Time complexity is linear for all versions of unique. Exactly last -
first applications of the corresponding predicates are done. Space
complexity is constant for unique, and linear for unique_copy.
unique_copy
Description unique_copy is similar to unique, except that the resulting se-
quence is copied into the range starting at result.
Prototype template
< class inputIterator,
class OutputIterator >
OutputIterator unique_copy
(InputIterator first,
InputIterator last,
OutputIterator result);
template
< class ForwardIterator,
class BinaryPredicate >
OutputIterator unique_copy
(InputIterator first,
InputIterator last,
OutputIterator result,
BinaryPredicate binary_pred);
Remarks All versions of unique return the end of the resulting range.
Complexity Time complexity is linear for all versions of unique. Exactly last -
first applications of the corresponding predicates are done. Space
complexity is constant for unique, and linear for unique_copy.
reverse
Description The reverse algorithm reverses the order of elements in the range
[first, last).
Prototype template
< class BidirectionalIterator >
void reverse
(BidirectionalIterator first,
BidirectionalIterator last);
Complexity Time complexity is linear. For reverse, exactly [n/2] element ex-
changes are performed, where n is the size [first, last). For
reverse_copy, exactly last-first assignments are done. Space
complexity is constant.
reverse_copy
Description The reverse_copy algorithm reverses the sequence [first,
last) and copies the resulting sequence into the range beginning
result.
Prototype template
< class BidirectionalIterator,
class OutputIterator >
OutputIterator reverse_copy
(BidirectionalIterator first,
BidirectionalIterator last,
OutputIterator result);
Complexity Time complexity is linear. For reverse, exactly [n/2] element ex-
changes are performed, where n is the size [first, last). For
reverse_copy, exactly last-first assignments are done. Space
complexity is constant.
rotate
Description The rotate algorithm shifts elements in a sequence leftward as fol-
lows: for each non-negative integer i < (last - first), rotate
Prototype template
< class ForwardIterator >
void rotate
(ForwardIterator first,
ForwardIterator middle,
ForwardIterator last);
rotate_copy
Description rotate_copy is similar to rotate, except that it copies the ele-
ments of the resulting sequence into a range of size last-first
starting at the location result.
Prototype template
< class ForwardIterator,
class OutputIterator >
void rotate_copy
(ForwardIterator first,
ForwardIterator middle,
ForwardIterator last,
OutputIterator result);
random_shuffle
Description random_shuffle shuffles the elements in the range [first,
last) with uniform distribution. random_shuffle can take a par-
ticular random number generating function object rand such that
rand returns a randomly chosen double in the interval [0, 1).
Prototype template
< class RandomAccessIterator >
void random_shuffle
(RandomAccessIterator first,
RandomAccessIterator last);
Prototype template
< class RandomAccessIterator,
class RandomNumberGenerator >
void random_shuffle
(RandomAccessIterator first,
RandomAccessIterator last,
RandomNumberGenerator& rand);
partition
Description The partition algorithm places all elements in the range [first,
last) that satisfy pred before all elements that do not satisfy it.
Prototype template
< class BidirectionalIterator,
class Predicate >
void partition
(BidirectionalIterator first,
BidirectionalIterator last,
Predicate pred);
Remarks Both algorithms return an iterator i such that for any iterator j in
the range [first,i), pred(*j) == true, and for any iterator k
in the range [i, last), pred(*k) == false.
Complexity Time complexity is linear for both versions of the algorithm. Space
complexity is constant.
stable_partition
Prototype template
< class BidirectionalIterator,
class Predicate >
void stable_partition
(BidirectionalIterator first,
BidirectionalIterator last,
Predicate pred);
Remarks Both algorithms return an iterator i such that for any iterator j in
the range [first,i), pred(*j) == true, and for any iterator k
in the range [i, last), pred(*k) == false.
Complexity Time complexity is linear for both versions of the algorithm. For
stable_partition, the time and space complexity varies with the
available memory.
All of the algorithms have two versions: one that uses operator<
for comparisons and another that uses a function object of type
Compare.
For all algorithms that take Compare, there is a version that uses
operator< instead. That is, comp(*i, *j) == true defaults to
*i < *j == true. For the algorithms to work correctly, comp has
to induce a total ordering on the values.
Sorting
Four different sorting algorithms are provided by the library: sort,
stable_sort, partial_sort and partial_sort_copy.
sort uses the quicksort algorithm, which is generally the fastest for
a randomly shuffled sequence. It should be used as the default sort-
ing algorithm. However, in the worst case, sort might take qua-
dratic time. This worst case occurs if the original input to the algo-
rithm is already sorted.
sort
Description sort sorts the elements in the range [first, last). It uses a fast
quicksort algorithm. If worst case behavior is important
stable_sort or partial_sort should be used.
Prototype template
< class RandomAccessIterator >
void sort
(RandomAccessIterator first,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void sort
(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
stable_sort
Description stable_sort sorts the elements in the range [first, last), and
ensures that the relative order of the equal elements is preserved.
Prototype template
< class RandomAccessIterator >
void stable_sort
(RandomAccessIterator first,
RandomAccessIterator last);
Prototype template
< class RandomAccessIterator,
class Compare >
void stable_sort
(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
partial_sort
Description partial_sort sorts only a subsequence of the input range. It
places the first middle-first sorted elements from the range
[first, last) into the range [first,middle). The rest of the
Prototype template
< class RandomAccessIterator >
void partial_sort
(RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void partial_sort
(RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last,
Compare comp);
partial_sort_copy
Description partial_sort_copy is similar to partial_sort. The algorithm
places the first min(last-first, result_last -
result_first) sorted elements from the range [first, last)
into the sequence beginning at result_first.
Prototype template
< class InputIterator,
class RandomAccessIterator
>RandomAccessIterator partial_sort_copy
(InputIterator first, InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last);
template
nth_element
Description The nth_element algorithm is a restricted form of the sort algo-
rithm. It places an element of a sequence in the location where it
would be if the sequence were sorted.
Prototype template
< class RandomAccessIterator >
void nth_element
(RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void nth_element
(RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last,
Compare comp);
Remarks In the first version of the algorithm, element comparisons are done
using operator<, while in the second version they are done using
the function object comp.
Complexity The algorithm takes O(N) time on the average, where N is the size of
the range [first, last). Space complexity is constant.
Binary Searching
All of the algorithms in this section are versions of binary search.
binary_search
Description The binary_search function returns true if value is in the range
[first, last) and false otherwise.
Prototype template
< class ForwardIterator,
class T >
bool binary_search
(ForwardIterator first,
ForwardIterator last,
const T& value);
template
< class ForwardIterator,
class T,
Complexity For random access iterators only, the number of comparisons will
be
• at most log(N)+1, for lower_bound and upper_bound
• at most log(N)+2, for binary_search
• at most 2*log(N)+1, for equal_range
For all iterators other than random access, time complexity is linear,
since the algorithm has to sequentially traverse through the data
structure. Space complexity is constant for all the binary search al-
gorithms.
lower_bound
Description The lower_bound functions return an iterator i referring to the
first position in the sorted sequence in the range [first, last)
into which value may be inserted while maintaining the sorted or-
dering.
Prototype template
< class ForwardIterator,
class T >
ForwardIterator lower_bound
(ForwardIterator first,
ForwardIterator last,
const T& value);
template
Complexity For random access iterators only, the number of comparisons will
be
• at most log(N)+1, for lower_bound and upper_bound
• at most log(N)+2, for binary_search
• at most 2*log(N)+1, for equal_range
For all iterators other than random access, time complexity is linear,
since the algorithm has to sequentially traverse through the data
structure. Space complexity is constant for all the binary search al-
gorithms.
upper_bound
Description The upper_bound functions return an iterator i referring to the last
position in the sorted sequence in the range [first, last) into
which value may be inserted while maintaining the sorted order-
ing.
Prototype template
< class ForwardIterator,
class T >
ForwardIterator upper_bound
(ForwardIterator first,
ForwardIterator last,
Complexity For random access iterators only, the number of comparisons will
be
• at most log(N)+1, for lower_bound and upper_bound
• at most log(N)+2, for binary_search
• at most 2*log(N)+1, for equal_range
For all iterators other than random access, time complexity is linear,
since the algorithm has to sequentially traverse through the data
structure. Space complexity is constant for all the binary search al-
gorithms.
equal_range
Description The equal_range functions return a pair of iterators i and j refer-
ring to the first and last positions in the sorted sequence in the range
[first, last) into which value may be inserted while main-
taining the sorted ordering.
Prototype template
< class ForwardIterator, class T >
pair< ForwardIterator, ForwardIterator >
equal_range
(ForwardIterator first,
ForwardIterator last,
const T& value);
template
< class ForwardIterator, class T >
pair < ForwardIterator, ForwardIterator >
equal_range
(ForwardIterator first,
ForwardIterator last,
const T& value,
Compare comp);
Complexity For random access iterators only, the number of comparisons will
be
• at most log(N)+1, for lower_bound and upper_bound
• at most log(N)+2, for binary_search
• at most 2*log(N)+1, for equal_range
For all iterators other than random access, time complexity is linear,
since the algorithm has to sequentially traverse through the data
structure. Space complexity is constant for all the binary search al-
gorithms.
Merging
The merge algorithms join two sorted ranges.
merge
Description merge merges two sorted ranges [first1, last1) and [first2,
last2) into the range [result,result + (last1 - first1) +
(last2 - first2)). The merge is stable, that is, for equal ele-
ments in the two ranges, the elements from the first range always
precede the elements from the second. merge returns result +
(last1 - first1) + (last2 - first2). The result of merge
is undefined if the resulting range overlaps with either of the origi-
nal ranges.
Prototype template
< class InputIterator1,
class InputIterator2,
class OutputIterator >
OutputIterator merge
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator last2,
OutputIterator result);
template
< class InputIterator1,
class InputIterator2,
class OutputIterator,
class Compare >
OutputIterator merge
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator last2,
OutputIterator result,
Compare comp);
inplace_merge
Description inplace_merge merges two sorted consecutive ranges
[first,middle) and [middle,last) putting the result of the
merge into the range [first, last). The merge is stable, that
is, for equal elements in the two ranges, the elements from the first
range always precede the elements from the second.
Prototype template
< class BidirectionalIterator >
void inplace_merge
(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last);
template
< class BidirectionalIterator,
class Compare >
void inplace_merge
(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last,
Compare comp);
includes
Description includes checks if the second sequence is a subset of the first se-
quence (both ranges are assumed to be sorted). The algorithm re-
turns true if every element in the range [first2, last2) is con-
tained in the range [first1, last1), and false otherwise.
Prototype template
< class InputIterator1,
class InputIterator2 >
bool includes
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2);
template
< class InputIterator1,
class InputIterator2,
class Compare >
bool includes
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
Compare comp);
Complexity TAll of the set operations functions require linear time. In all cases,
at most ((last1 - first1) + (last2 - first2)) * 2 - 1
comparisons are performed. Space complexity is constant.
set_union
Description set_union constructs a sorted union of the elements from the two
ranges. set_union is stable, that is, if an element is present in both
ranges, the one from the first range is copied.
Prototype template
< class InputIterator1,
class InputIterator2,
TAll of the set operations functions require linear time. In all cases,
at most ((last1 - first1) + (last2 - first2)) * 2 - 1
comparisons are performed. Space complexity is constant.
set_intersection
Description set_intersection constructs a sorted intersection of the ele-
ments from the two ranges. set_intersection is guaranteed to
be stable, that is, if an element is present in both ranges, the one
from the first range is copied into the intersection.
Prototype template
< class InputIterator1,
class InputIterator2, class OutputIterator >
OutputIterator set_intersection
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result);
template
< class InputIterator1,
class InputIterator2,
class OutputIterator,
class Compare >
OutputIterator set_intersection
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp);
Complexity TAll of the set operations functions require linear time. In all cases,
at most ((last1 - first1) + (last2 - first2)) * 2 - 1
comparisons are performed. Space complexity is constant.
set_difference
Description set_difference constructs a sorted difference of the elements
from the two ranges. This difference contains elements that are
present in the first set but not in the second.
Prototype template
< class InputIterator1,
class InputIterator2,
class OutputIterator >
OutputIterator set_difference
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result);
template
< class InputIterator1,
class InputIterator2,
class OutputIterator,
class Compare >
OutputIterator set_difference
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp);
Complexity TAll of the set operations functions require linear time. In all cases,
at most ((last1 - first1) + (last2 - first2)) * 2 - 1
comparisons are performed. Space complexity is constant.
set_symmetric_difference
Prototype template
< class InputIterator1,
class InputIterator2,
class OutputIterator >
OutputIterator set_symmetric_difference
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result);
template
< class InputIterator1,
class InputIterator2,
class OutputIterator,
class Compare >
OutputIterator set_symmetric_difference
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp);
Complexity TAll of the set operations functions require linear time. In all cases,
at most ((last1 - first1) + (last2 - first2)) * 2 - 1
comparisons are performed. Space complexity is constant.
Heap Operations
A heap represents a particular organization of a random access data
structure (such as a vector or a deque). Given a range [first,
last), where first and last are random access iterators, we say
that the elements in the range represent a heap if two key properties
are satisfied:
• The value pointed to by the iterator first is the largest ele-
ment in the range
• The value pointed to by the iterator first may be removed
by pop_heap, or a new element added by push_heap, in
logarithmic time. Both pop_heap and push_heap return
valid heaps.
push_heap
Description push_heap assumes the range [first1, last - 1) is a valid
heap and properly places the value in the location last - 1 into
the resulting heap [first, last).
Prototype template
< class RandomAccessIterator >
void push_heap
(RandomAccessIterator first,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void push_heap
(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
pop_heap
Description pop_heap assumes the range [first, last) is a valid heap, then
swaps the value in the location first with the value in the location
last - 1 and makes [first, last - 1) into a heap.
Prototype template
< class RandomAccessIterator >
void pop_heap
(RandomAccessIterator first,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void pop_heap
(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
make_heap
Description The make_heap functions construct a heap in the range [first,
last) using the elements in the range [first, last).
Prototype template
< class RandomAccessIterator >
void make_heap(
RandomAccessIterator first,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void make_heap(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
sort_heap
Description The sort_heap functions sort the elements that are stored in the
heap represented in the range [first, last).
Prototype template
< class RandomAccessIterator >
void sort_heap
(RandomAccessIterator first,
RandomAccessIterator last);
template
< class RandomAccessIterator,
class Compare >
void sort_heap
(RandomAccessIterator first,
RandomAccessIterator last,
Compare comp);
min
Description The min function is passed two elements, and returns the one that is
smaller.
Prototype template
< class T >
T min
(const T &a,
const T &b);
template
< class T,
class Compare >
T min
(const T &a,
const T &b,
Compare comp);
Complexity min and max take constant time. Space complexity is constant for all
min and max algorithms.
max
Description The max function is passed two elements, and returns the one that is
larger.
Prototype template
< class T >
T max
(const T &a,
const T &b);
template
< class T,
class Compare >
T max
(const T &a,
const T &b,
Compare comp);
Complexity min and max take constant time. Space complexity is constant for all
min and max algorithms.
min_element
Description The min_element function returns an iterator i referring to the
minimum of the elements in the range [first, last).
Prototype template
< class InputIterator >
InputIterator min_element
(InputIterator first,
InputIterator last);
template
Complexity Tmin_element takes linear time, with the number of element com-
parisons being the size of the range [first, last). Space com-
plexity is constant for all min and max algorithms.
max_element
Description The max_element functions returns an iterator i referring to the
maximum of the elements in the range [first, last).
Prototype template
< class InputIterator >
InputIterator max_element
(InputIterator first,
InputIterator last);
template
< class InputIterator,
class Compare >
InputIterator max_element
(InputIterator first,
InputIterator last,
Compare comp);
Complexity Tmax_element takes linear time, with the number of element com-
parisons being the size of the range [first, last). Space com-
plexity is constant for all min and max algorithms.
Lexicographical Comparison
The lexicographical comparison algorithm compares two sequences
of elements.
lexicographical_compare
Description The lexicographical comparison of two sequences [first1,
last1) and [first2, last2) is defined as follows: traverse the
sequences, comparing corresponding pairs of elements e1 and e2. If
e1 < e2, stop and return true. If e2 < e1, stop and return
false. Otherwise, continue to the next corresponding pair of ele-
ments.
If the first sequence is exhausted but the second is not, then return
true, otherwise return false.
Prototype template
< class InputIterator1,
class InputIterator2 >
bool lexicographical_compare
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2);
template
< class InputIterator1,
class InputIterator2,
class Compare >
bool lexicographical_compare
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
Compare comp);
Permutation Generators
The library provides two permutation generation algorithms:
next_permutation and prev_permutation. As with all sorting
related operations, there are two versions of each algorithm: one
that uses operator< for comparisons, and one that uses a function
object comp.
next_permutation
Description next_permutation takes a sequence defined by the range
[first, last) and transforms it into the next permutation. The
next permutation is found by assuming that the set of all permuta-
tions is lexicographically sorted with respect to operator< or
comp. If such a permutation exists, the algorithm returns true. Oth-
erwise, it transforms the sequence into the smallest permutation
(i.e., the one sorted in an ascending order), and returns false.
Prototype template
< class BidirectionalIterator >
bool next_permutation
(BidirectionalIterator first,
BidirectionalIterator last);
template
< class BidirectionalIterator,
class Compare >
bool next_permutation
(BidirectionalIterator first,
BidirectionalIterator last,
Compare comp);
Complexity Time complexity is linear for both algorithms. The number of com-
parisons done is at most n where n is half the range [first,
last). Space complexity is constant.
prev_permutation
Description prev_permutation takes a sequence defined by the range
[first, last) and transforms it into the previous permutation.
The previous permutation is found by assuming that the set of all
permutations is lexicographically sorted with respect to operator<
or comp. If such a permutation exists, it returns true. Otherwise, it
transforms the sequence into the largest permutation, (i.e., the de-
scending sorted one), and returns false.
Prototype template
< class BidirectionalIterator >
bool prev_permutation
(BidirectionalIterator first,
BidirectionalIterator last);
template
< class BidirectionalIterator,
class Compare >
bool prev_permutation
(BidirectionalIterator first,
BidirectionalIterator last,
Compare comp);
Complexity Time complexity is linear for both algorithms. The number of com-
parisons done is at most n where n is half the range [first,
last). Space complexity is constant.
accumulate
Description accumulate is similar to the APL reduction operator and the Com-
mon Lisp reduce function, but avoids the difficulty of defining the
result of reduction on an empty sequence by always requiring an
initial value.
Prototype template
< class InputIterator,class T >
T accumulate
(InputIterator first,
InputIterator last,
T init);
template
< class InputIterator,
class T,
class BinaryOperation >
T accumulate
(InputIterator first,
InputIterator last,
T init,
BinaryOperation binary_op);
inner_product
Description The inner_product algorithm computes its result by initializing the
accumulator acc with initial value init and then modifying it as fol-
lows:
acc = acc + (*i1) * (*i2)
or
acc = binary_op1(acc, binary_op2(*i1, *i2))
in order.
Prototype template
< class InputIterator1,
class InputIterator2,
class T >
T inner_product
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
T init);
template
< class InputIterator1,
class InputIterator2,
class T,
class BinaryOperation1,
class BinaryOperation2 >
T inner_product
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
T init,
BinaryOperation1 binary_op1,
BinaryOperation2 binary_op2);
partial_sum
Description The partial_sum algorithm computes partial sums of the input
sequence and stores the result in the output sequence.
or
binary_op(binary_op
(., binary_op(*first + *(first + 1)) +...)
+ (*first + (i - result))).
Prototype template
< class InputIterator,
class OutputIterator >
InputIterator partial_sum
(InputIterator first,
InputIterator last,
OutputIterator result);
template
< class InputIterator,
class OutputIterator,
class BinaryOperation >
InputIterator partial_sum
(InputIterator first,
InputIterator last,
OutputIterator result,
BinaryOperation binary_op);
adjacent_difference
Description adjacent_difference assigns to every element referred to by it-
erator i in the range
[result + 1, result + (last - first))
or
binary_op(*(first + (i - result)),
*(first + (i - result) - 1)).
Prototype template
< class InputIterator,
class OutputIterator >
InputIterator adjacent_difference
(InputIterator first,
InputIterator last,
OutputIterator result);
template
< class InputIterator,
class OutputIterator,
class BinaryOperation>
InputIterator adjacent_difference
(InputIterator first,
InputIterator last,
OutputIterator result,
BinaryOperation binary_op);
Remarks result may be equal to first; i.e., the algorithm can work “in-
place”.
Numeric Arrays
The header <valarray> defines five template classes: valarray,
slice_array, gslice_array, mask_array and
indirect_array, two classes: slice and gslice, and a series of
related function signatures for representing and manipulating ar-
rays of values.
Constructors valarray
Default Constructor
Description This constructs an object of class valarray<T>, which has zero
length until it is passed into a library function as a modifiable lvalue
or through a non-constant this pointer.
Prototype valarray();
Overloaded Constructors
Prototype valarray (size_t);
Remarks This constructor sets the array length equal to the value of the argu-
ment. The elements of the array are constructed using the default
constructor for the instantiating type T.
valarray (const T&, size_t);
Remarks This constructor sets the array equal to the value of the second argu-
ment and initializes all the elements with the value of the first argu-
ment.
valarray (const T*, size_t);
Remarks The array created by this constructor has a length equal to the sec-
ond argument. The values of the elements of the array are initialized
with the first n values pointed to by the first argument. It is neces-
sary that the value of the second argument is greater than the num-
ber of vales pointed to by the first argument.
Copy Constructor
Description Copy constructor creates a distinct array rather than a alias.
Conversion Constructors
Description These are conversion constructors which convert one of the four ref-
erence templates to valarray.
Destructor
Description Destructor for valarray.
Assignment Operator =
Description The assignment operator modifies the length of the *this array to
be equal to that of the argument array. Each element of *this array
is then assigned the value of the corresponding element of the argu-
ment array. Assignment is the usual way to change the length of an
array after initialization. Assignment results in a distinct array
rather than an alias.
Subscript Operator []
Description For const valarray objects, the subscript operator returns the value
of the corresponding element of the array. For non-const valarray
objects, a reference to the corresponding element of the array is re-
turned.
Subscript Operator []
Description Each of these operations returns a subset of the array. The const-
qualified versions return this subset as a new valarray. The non-
const versions return a class template object which has reference
semantics to the original array.
Add Operator +
Prototype valarray<T> operator+() const;
Minus Operator -
Prototype valarray<T> operator-() const;
Complement Operator ~
Prototype valarray<T> operator~() const;
Not Operator !
Prototype valarray<T> operator!() const;
Multiply Operator *
Prototype template
< class T >
valarray<T> operator*
(const valarray<T>&,
const valarray<T>&);
Divide Operator /
Prototype template
< class T >
valarray<T> operator/
(const valarray<T>&,
const valarray<T>&);
Remainder Operator %
Prototype template
< class T >
valarray<T> operator%
(const valarray<T>&,
const valarray<T>&);
Add Operator +
Prototype template
< class T >
valarray<T> operator+
(const valarray<T>&,
const valarray<T>&);
Minus Operator -
Prototype template
< class T >
valarray<T>
operator-
(const valarray<T>&,
const valarray<T>&);
Bitwise Or Operator
Prototype template
< class T >
valarray<T> operator|
(const valarray<T>&,
const valarray<T>&);
const valarray<T>&);
Logical Or Operator ||
Prototype template
< class T >
valarray<T> operator||
(const valarray<T>&,
const valarray<T>&);
Multiply Operator *
Prototype template
< class T >
valarray<T> operator*
(const valarray<T>&,
const T&);
template
< class T >
valarray<T> operator*
(const T&, const
valarray<T>&);
Divide Operator /
Prototype template
< class T >
valarray<T> operator/
(const valarray<T>&,
const T&);
template
< class T>
valarray<T> operator/
(const T&,
const valarray<T>&);
Remainder Operator %
Prototype template
< class T >
valarray<T >operator%
(const valarray<T>&,
const T&);
template
< class T >
valarray<T> operator%
(const T&,
const valarray<T>&);
Add Operator +
Prototype template
< class T >
valarray<T> operator+
(const valarray<T>&,
const T&);
template
< class T>
valarray<T> operator+
(const T&,
const valarray<T>&);
Minus Operator -
Prototype template
< class T >
valarray<T> operator-
(const valarray<T>&,
const T&);
template
< class T > v
alarray<T> operator-
(const T&,
const valarray<T>&);
Bitwise Or Operator |
Prototype template
< class T >
valarray<T> operator|
(const valarray<T>&,
const T&);
template
< class T >
valarray<T> operator|
(const T&,
const valarray<T>&);
(const valarray<T>&,
const T&);
template
< class T >
valarray<T> operator&&
(const T&,
const valarray<T>&);
Logical Or Operator ||
Prototype template
< class T >
valarray<T> operator||
(const valarray<T>&,
const T&);
template
< class T >
valarray<T> operator||
(const T&,
const valarray<T>&);
Equality Operator ==
Prototype template
< class T >
valarray<bool> operator==
(const valarray<T>&,
const valarray<T>&);
template
< class T>
valarray<bool> operator!=
(const valarray<T>&,
const valarray<T>&);
Equality Operator ==
Prototype template
< class T >
valarray<bool> operator==
(const valarray&,
const T&);
template
< class T>
valarray<bool> operator==
(const T&,
const valarray&);
valarray::length
Description This function returns the number of elements in the array.
Pointer Conversion
Description A non-constant array may be converted to a pointer to the instanti-
ating type. A constant array may be converted to a pointer to the in-
stantiating type, qualified by const. It is guaranteed that &a[0] ==
(T*)a for any non-constant valarray<T> a. The pointer returned for a
non-constant array (whether or not it points to a type qualified by
const) is valid for the same duration as a reference returned by the
size_t subscript operator. The pointer returned for a constant array
is valid for the lifetime of the array.
valarray::sum
Description This function may only be instantiated for a type T to which opera-
tor+= can be applied. This function returns the sum of all the ele-
ments of the array. If the array has length 0, the behavior is unde-
fined. If the array has length 1, sum returns the value of element 0.
Otherwise, the returned value is calculated by applying operator+=
to a copy of an element of the array and all other elements of the
array in an unspecified order.
valarray::fill
Description This function assigns the value of the argument to all the elements
of the array. The length of the array is not changed, nor are any
pointers or references to the elements of the array invalidated.
valarray::shift
Prototype valarray<T> shift(int) const;
Description This function returns an array whose length is identical to the array,
but whose element values are shifted the number of places indi-
cated by the argument. A positive argument value results in a left
shift, a negative value in a right shift, and a zero value in no shift.
valarray::cshift
Description This function returns an array whose length is identical to the array,
but whose element values are shifted in a circular fashion the num-
ber of places indicated by the argument. A positive argument value
results in a left shift, a negative value in a right shift, and a zero
value in no shift.
valarray::apply
Description These functions return an array whose length is equal to the array.
Each element of the returned array is assigned the value returned by
applying the argument function to the corresponding element of the
array.
valarray::free
Description This function sets the length of an array to zero.
valarray::min
Description This function may only be instantiated for a type T to which opera-
tor> and operator< may be applied and for which operator> and
operator< return a value which is of type bool or which can be un-
ambiguously converted to type bool. This function returns the mini-
mum (a.min()) value found in the argument array a. The value re-
turned for an array of length 0 is undefined. For an array of length 1,
the value of element 0 is returned. For all other array lengths, the
determination is made using operator> and operator<, in a
manner analogous to the application of operator+= for the sum
function.
Prototype template
< class T >
T min(const valarray<T>& a);
valarray::max
Description This function may only be instantiated for a type T to which opera-
tor> and operator< may be applied and for which operator> and
operator< return a value which is of type bool or which can be un-
ambiguously converted to type bool. These functions return the
maximum (a.max()) value found in the argument array a. The
value returned for an array of length 0 is undefined. For an array of
length 1, the value of element 0 is returned. For all other array
lengths, the determination is made using operator> and opera-
tor<, in a manner analogous to the application of operator+= for
the sum function.
Prototype template
< class T>
T max(const valarray<T>& a);
Transcendentals valarray
Description Each of these functions may only be instantiated for a type T to
which a unique function with the indicated name can be applied.
This function must return a value which is of type T or which can be
unambiguously converted to type T.
valarray::abs
Prototype template
< class T >
valarray<T> abs(const valarray<T>&);
valarray::acos
Prototype template
< class T>
valarray<T> acos(const valarray<T>&);
valarray::asin
Prototype template
< class T >
valarray<T> asin(const valarray<T>&);
valarray::atan
Prototype template
< class T >
valarray<T> atan(const valarray<T>&);
valarray::atan2
Prototype template
< class T >
valarray<T> atan2
(const valarray<T>&,
const valarray<T>&);
Prototype template
< class T >
valarray<T> atan2
(const valarray<T>&,
const T&);
Prototype template
< class T >
valarray<T> atan2
(const T&,
const valarray<T>&);
valarray::cos
Prototype template
< class T >
valarray<T> cos (const valarray<T>&);
valarray::cosh
Prototype template
< class T >
valarray<T> cosh(const valarray<T>&);
valarray::exp
Prototype template
< class T>
valarray<T> exp(const valarray<T>&);
valarray::log
Prototype template
< class T >
valarray<T> log(const valarray<T>&);
valarray::log10
Prototype template
< class T >
valarray<T> log10(const valarray<T>&);
valarray::pow
Prototype template
< class T >
valarray<T> pow
(const valarray<T>&,
const valarray<T>&);
Prototype template
< class T >
valarray<T> pow
(const valarray<T>&,
const T&);
Prototype template
< class T >
valarray<T> pow
(const T&,
const valarray<T>&);
valarray::sin
Prototype template
< class T >
valarray<T> sin(const valarray<T>&);
valarray::sinh
Prototype template
< class T >
valarray<T> sinh(const valarray<T>&);
valarray::sqrt
Prototype template
< class T >
valarray<T> sqrt (const valarray<T>&);
valarray::tan
Prototype template
< class T >
valarray<T> tan(const valarray<T>&);
valarray::tanh
Prototype template
< class T >
valarray<T> tanh(const valarray<T>&);
Class slice
Description The slice class represents a BLAS-like slice from an array. Such a
slice is specified by a starting index, a length, and a stride.
Constructors slice
Default Constructor
Description The default constructor for slice creates a slice which specifies no el-
ements. A default constructor is provided only to permit the decla-
ration of arrays of slices.
Prototype slice();
Prototype slice(
size_t start,
size_t length,
size_t stride);
slice(const slice&);
slice::start
Prototype size_t start() const;
slice::length
Prototype size_t length() const;
slice::stride
Prototype size_t stride() const;
Constructors slice_array
Prototype slice_array();
Assignment Operator =
Description The second of these two assignment operators is declared private
and need not be defined. The first has reference semantics, assign-
ing the values of the argument array elements to selected elements
of the valarray<T> object to which the slice_array object re-
fers.
slice_array::fill
Description This function has reference semantics, assigning the value of its ar-
gument to the elements of the valarray<T> object to which the
slice_array object refers.
Class gslice
Description This class represents a generalized slice out of an array. A gslice is
defined by a starting offset (s), a set of lengths (lj), and a set of
strides (dj). The number of lengths must equal the number of
strides. A gslice represents a mapping from a set of indices (ij), equal
in number to the number of strides, to a single index k. It is useful
for building multidimensional array classes using the valarray tem-
plate, which is one-dimensional. The set of one-dimensional index
values specified by a gslice arek = s + Σijdj where the multidimen-
sional indices ij range in value from 0 to lij-1.It is possible to have de-
generate generalized slices in which an address is repeated. If a de-
generate slice is used as the argument to the non-const version of
operator[](const gslice&), the resulting behavior is unde-
fined.
Constructors gslice
Default Constructor
Description The default constructor creates a gslice which specifies no elements.
Overloaded Constructors
Description The constructor with arguments builds a gslice based on a specifica-
tion of start, lengths, and strides, as explained in the previous sec-
tion.
gslice::start
Prototype size_t start() const;
gslice::length
Prototype valarray<size_t> length() const;
gslice::stride
Prototype valarray<size_t> stride() const;
Constructors gslice_array
Prototype gslice_array();
gslice_array(const gslice_array&);
Assignment gslice_array
Assignment Operator =
Description The second of these two assignment operators is declared private
and need not be defined. The first has reference semantics, assign-
ing the values of the argument array elements to selected elements
of the valarray<T> object to which the gslice_array refers.
gslice_array::fill
Description This function has reference semantics, assigning the value of its ar-
gument to the elements of the valarray<T> object to which the
gslice_array object refers.
Constructors mask_array
Constructors
Description The mask_array template has no public constructors. It declares
the above constructors to be private. These constructors need not
be defined.
Prototype mask_array();
mask_array(const mask_array&);
Assignment mask_array
Assignment Operator =
Description The second of these two assignment operators is declared private
and need not be defined. The first has reference semantics, assign-
ing the values of the argument array elements to selected elements
of the valarray<T> object to which it refers.
mask_array::fill
Prototype void fill(const T&);
Description This function has reference semantics, assigning the value of its ar-
gument to the elements of the valarray<T> object to which the
mask_array object refers.
Constructors indirect_array
Prototype indirect_array();
indirect_array(const indirect_array&);
Assignment indirect_array
Assignment Operator =
Description The second of these two assignment operators is declared private
and need not be defined. The first has reference semantics, assign-
ing the values of the argument array elements to selected elements
of the valarray<T> object to which it refers. If the
indirect_array specifies an element in the valarray<T> object
to which it refers more than once, the behavior is undefined.
indirect_array::fill
Description This function has reference semantics, assigning the value of its ar-
gument to the elements of the valarray<T> object to which the
indirect_array object refers.
Prototype template
< class InputIterator,
class T >
T accumulate
(InputIterator first,
InputIterator last,
T init);
template
< class InputIterator,
class T,
class BinaryOperation >
T accumulate
(InputIterator first,
InputIterator last,
T init,
BinaryOperation binary_op);
Prototype template
< class InputIterator1,
class InputIterator2,
class T >
T inner_product
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
T init);
template
< class InputIterator1,
class InputIterator2,
class T,
class BinaryOperation1,
class BinaryOperation2 >
T inner_product
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2, T init,
BinaryOperation1 binary_op1,
BinaryOperation2 binary_op2);
Prototype template
< class InputIterator,
class OutputIterator >
OutputIterator partial_sum
(InputIterator first,
InputIterator last,
OutputIterator result);
template
< class InputIterator,
class OutputIterator,
class BinaryOperation >
OutputIterator partial_sum
(InputIterator first,
InputIterator last,
OutputIterator result,
BinaryOperation binary_op);
Prototype template
< class InputIterator,
class OutputIterator >
OutputIterator adjacent_difference
(InputIterator first,
InputIterator last,
OutputIterator result);
template
< class InputIterator,
class OutputIterator,
class BinaryOperation >
OutputIterator adjacent_difference
(InputIterator first,
InputIterator last,
OutputIterator result,
BinaryOperation binary_op);
_MSL_CX_LIMITED_RANGE
This flag effects the * and / operators of complex.
Header <complex>
The header <complex> defines classes, operators, and functions for
representing and manipulating complex numbers
26.2.6 operators:
template<class T> complex<T> operator+
const complex<T>&, const complex<T>&);
template<class T> complex<T> operator+
(const complex<T>&, const T&);
template<class T> complex<T> operator+
(const T&, const complex<T>&);
template<class T> complex<T> operator-
(const complex<T>&, const complex<T>&);
template<class T> complex<T> operator-
(const complex<T>&, const T&);
template<class T> complex<T> operator-
(const T&, const complex<T>&);
template<class T> complex<T> operator*
(const complex<T>&, const complex<T>&);
template<class T> complex<T> operator*
(const complex<T>&, const T&);
template<class T> complex<T> operator*
(const T&, const complex<T>&);
26.2.7 values:
template<class T> T real(const complex<T>&);
template<class T> T imag(const complex<T>&);
template<class T> T abs(const complex<T>&);
template<class T> T arg(const complex<T>&);
template<class T> T norm(const complex<T>&);
template<class T> complex<T> conj(const complex<T>&);
template<class T> complex<T> polar(const T&, const T&);
26.2.8 transcendentals:
template<class T> complex<T> cos (const complex<T>&);
template<class T> complex<T> cosh (const complex<T>&);
template<class T> complex<T> exp (const complex<T>&);
template<class T> complex<T> log (const complex<T>&);
template<class T> complex<T> log10(const complex<T>&);
template<class T> complex<T> pow(const complex<T>&, int);
template<class T> complex<T> pow(const complex<T>&, const T&);
template<class T> complex<T> pow
(const complex<T>&, const complex<T>&);
template<class T> complex<T> pow(const T&, const complex<T>&);
template<class T> complex<T> sin (const complex<T>&);
template<class T> complex<T> sinh (const complex<T>&);
template<class T> complex<T> sqrt (const complex<T>&);
template<class T> complex<T> tan (const complex<T>&);
template<class T> complex<T> tanh (const complex<T>&);
}
(const complex<X>&);
template<class X> complex<long double>& operator+=
(const complex<X>&);
template<class X> complex<long double>& operator-=
(const complex<X>&);
template<class X> complex<long double>& operator*=
(const complex<X>&);
template<class X> complex<long double>& operator/=
(const complex<X>&);
};
Remarks The effect of instantiating the template complex for any type other
than float, double or long double is unspecified.
Constructors
Assignment Operator
real
imag
Operators
Several assignment operators are overloaded for the complex class
manipulations.
• “operator +=” on page 428
operator +=
Remarks The first operator with a scalar argument adds the scalar value of
the right hand side to the real component and stores the result in the
object. The imaginary component is left alone.
The second operator with a complex type, adds the complex value
of the right hand side to the object and stores the resultant in the ob-
ject.
operator -=
Remarks The first operator with a scalar argument subtracts the scalar value
of the right hand side from the real component and stores the result
in the object. The imaginary component is left alone.
operator *=
Remarks The first operator with a scalar argument multiplies the scalar value
of the right hand side to class object and stores result in the object.
operator /=
Remarks The first operator with a scalar argument divides the scalar value of
the right hand side to class object and stores result in the object.
Complex Operators
The overloaded complex operators consists of:
• “operator +” on page 430
• “operator -” on page 430
• “operator /” on page 431
• “operator !=” on page 432
• “operator >>” on page 432
• “operator <<” on page 433
operator +
operator -
operator *
operator /
operator ==
Remarks Returns true if the real and the imaginary components are equal.
operator !=
Remarks Returns true if the real or the imaginary components are not equal.
operator >>
Remarks Extracts in the form of u, (u), or (u,v) where u is the real part and v is
the imaginary part.
Any failure in extraction will set the failbit and result in undefined
behavior.
operator <<
real
imag
T imag(const complex<T>&);
abs
arg
norm
conj
polar
Complex Transcendentals
The complex transcendentals consists of:
• “cos” on page 435
• “cosh” on page 436
• “exp” on page 436
• “log” on page 436
• “log10” on page 436
• “pow” on page 437
• “sin” on page 437
• “sinh” on page 437
• “sqrt” on page 437
• “tan” on page 438
• “tanh” on page 438
cos
cosh
exp
log
Remarks Returns the natural base logarithm of the complex class argument,
in the range of a strip mathematically unbounded along the real axis
and in the interval of [i*pi, i*pi] along the imaginary
axis.Where the argument is a negative real number,
imag(log(cpx)), is pi.
log10
pow
Remarks Returns the complex class raised to the power of second argument
defined as the exponent of (the second argument times the log of the
first argument).
sin
sinh
sqrt
Remarks Returns the square root of the complex class argument in the range
of right half plane. If the argument is a negative real number, the
value returned lies on the positive imaginary axis.
tan
tanh
Include Purpose
<cstdlib>
<fstream> File Streams
<cstdio>
<cwchar>
27.1.1 Definitions
Additional definitions are:
• character - A unit that can represent text
• character container type - A class or type used to rep-
resent a character.
• iostream class templates - A templates that take two
arguments: charT and traits. The argument charT is a char-
acter container type. The argument traits is a structure
which defines characteristics and functions of the charT
type.
• narrow-oriented iostream classes - These classes are
template instantiation classes. The traditional iostream
classes are narrow-oriented iostream classes.
• wide-oriented iostream classes - These classes are
template instantiation classes. They are used for the character
container class wchar_t.
• repositional streams and arbitrary-positional
streams - A repositional stream can seek to only a pre-
Header <iosfwd>
Prototype namespace std {
template<class charT> class basic_ios;
template<class charT> class basic_istream;
template<class charT> class basic_ostream;
Header <iostream>
Description Declaration of standard objects
istream cin
Description An unbuffered input stream.
Remarks The object cin controls input from an unbuffered stream buffer as-
sociated with stdin declared in <cstdio>. After cin is initial-
ized cin.tie() returns cout.
ostream cout
Description An unbuffered output stream.
Remarks The object cout controls output to an unbuffered stream buffer as-
sociated with stdout declared in <cstdio>.
ostream cerr
Description Controls output to an unbuffered stream.
Remarks The object cerr controls output to an unbuffered stream buffer as-
sociated with stderr declared in <cstdio>. After err is initialized,
err.flags() and unitbuf is nonzero.
ostream clog
Description Controls output to a stream buffer.
Remarks The object clog controls output to a stream buffer associated with
cerr declared in <cstdio>.
istream win
Description An unbuffered input stream.
Remarks The object win controls input from an unbuffered stream buffer as-
sociated with stdin declared in <cstdio>. After cin is initial-
ized win.tie() returns wout.
ostream wout
Description An unbuffered output stream.
Remarks The object cout controls output to an unbuffered stream buffer as-
sociated with stdout declared in <cstdio>.
wostream werr
Description Controls output to an unbuffered stream.
Remarks The object werr controls output to an unbuffered stream buffer as-
sociated with stderr declared in <cstdio>. After werr is initial-
ized, werr.flags() and unitbuf is nonzero.
wostream wlog
Description Controls output to a stream buffer.
Remarks The object wlog controls output to a stream buffer associated with
cerr declared in <cstdio>.
Header <ios>
Description The header file <ios> provides for implementation of stream objects
for standard input and output.
class ios_base;
template <class charT, class traits =
ios_traits<charT> >
class basic_ios
Prototype
namespace std{
class ios_base{
public: class failure;
typedef T1 fmtflags;
static const fmtflags boolalpha;
static const fmtflags dec;
static const fmtflags fixed;
static const fmtflags hex;
static const fmtflags internal;
typedef T2 iostate;
static const iostate badbit;
static const iostate eofbit;
static const iostate failbit;
static const iostate goodbit;
typedef T3 openmode;
static const openmode app;
static const openmode ate;
static const openmode binary;
static const openmode in;
static const openmode out;
static const openmode trunc;
typedef T4 seekdir;
static const seekdir beg;
static const seekdir cur;
static const seekdir end;
class Init;
fmtflags flags() const;
fmtflags flags(fmtflags fmtfl);
fmtflags setf(fmtflags fmtfl);
fmtflags setf(fmtflags fmtfl, fmtflags mask);
void unsetf(fmtflags mask);
streamsize precision() const;
~ios_base();
protected:
ios_base();
private:
// static int index; exposition only
// long* iarray; exposition only
// void** parray; exposition only
};
}
Remarks The ios_base class is a base class and includes many enumera-
tions and mechanisms necessary for input and output operations.
27.4.3.1.1 failure
Description Define a base class for types of object thrown as exceptions.
public:
explicit failure(const string&)
virtual ~failure();
virtual const char* what() const;
};
}
27.4.3.1.1.1 failure
Description Construct a class failure.
failure::what
Description To return the exception message.
Returns Returns the message with which the exception was created.
Prototype Init();
Destructor
Prototype ~Init();
Remarks The destructor subtracts one from init_cnt and if the result is one
calls cout.flush(), cerr.flush() and clog.flush().
flags
Description To alter formatting flags using a mask.
Remarks Use flags() when you would like to use a mask of several flags, or
would like to save the current format configuration. The return
value of flags() returns the current fmtflags. The overloaded
flags(fmtflags) alters the format flags but will return the value
prior to the flags being changed.
#include <iostream>
int main()
{
using namespace std;
showf(); // show format flags
cout.setf(ios::right|ios::showpoint|ios::fixed);
showf();
return 0;
}
char fflags[][12] = {
"boolalpha",
"dec",
"fixed",
"hex",
"internal",
"left",
"oct",
"right",
"scientific",
"showbase",
"showpoint",
"showpos",
"skipws",
"unitbuf",
"uppercase"
};
boolalpha is off
dec is on
fixed is on
hex is off
internal is off
left is off
oct is off
right is on
scientific is off
showbase is off
showpoint is on
showpos is off
skipws is on
unitbuf is off
uppercase is off
setf
Description Set the stream format flags.
Remarks You should use the function setf() to set the formatting flags for
input/output. It is overloaded. The single argument form of
setf() sets the flags in the mask. The two argument form of
setf() clears the flags in the first argument before setting the flags
with the second argument.
int main()
{
using namespace std;
double d = 10.01;
cout.setf(ios::showpos | ios::showpoint);
return 0;
}
Result:
+10.01
10.01
unsetf
Description To un-set previously set formatting flags.
Remarks Use the unsetf() function to reset any format flags to a previous
condition. You would normally store the return value of setf() in
order to achieve this task.
int main()
{
using namespace std;
double d = 10.01;
cout.setf(ios::showpos | ios::showpoint);
cout << d << endl;
cout.unsetf(ios::showpoint);
cout << d << endl;
return 0;
Result:
+10.01
+10.01
precision
Description Set and return the current format precision.
Remarks Use the precision() function with floating point numbers to limit
the number of digits in the output. You may use precision()
with scientific or non-scientific floating point numbers. You may
use the overloaded precision() to retrieve the current precision
that is set.
int main()
{
using namespace std;
cout.precision(5);
cout.setf(0, ios::floatfield);
cout << "floatfield:\t" << TenPi << endl;
cout.setf(ios::scientific, ios::floatfield);
cout << "scientific:\t" << TenPi << endl;
cout.setf(ios::fixed, ios::floatfield);
cout << "fixed:\t\t" << TenPi << endl;
return 0;
}
Result:
floatfield: 31.416
scientific: 3.14159e+01
fixed: 31.41593
width
Description To set the width of the output field.
Remarks Use the width() function to set the field size for output. The func-
tion is overloaded to return just the current width setting if there is
no parameter or to store and then return the previous setting before
changing the fields width to the new parameter.
#include <iostream>
int main()
{
using namespace std;
int width;
cout.width(8);
width = cout.width();
cout.fill('*');
cout << "Hi!" << '\n';
cout.width(width);
cout<< "Hi!" << endl;
return 0;
}
Result:
Hi!*****
Hi!
Hi!*****
imbue
Description Stores a value representing the locale.
getloc
Description Determined the imbued locale for input output operations.
Return The global C++ locale if no locale has been imbued. Otherwise it re-
turns the locale of the input and output operations.
xalloc
Description Allocation function.
Return index++.
iword
Description Allocate an array of int and store a pointer.
NOTE: After a subsequent call to iword() for the same object the
return value may be invalid.
Return irray[idx]
pword
Description Allocate an array of pointers.
NOTE: After a subsequent call to pword() for the same object the
return value may be invalid.
Return parray[idx].
register_callback
Description Registers functions when an event occurs.
Remarks Registers the pair (fn, index) such that during calls to
imbue(), copyfmt() or ~ios_base() the function fn is
called with argument index. Function registered are called when
an event occurs, in opposite order of registration. Functions regis-
tered while a callback function is active are not called until the next
event.
sync_with_stdio
Description Synchronizes stream input output with ’C’ input and output func-
tions.
Returns Always returns true indicating that the MSLstreams are always
synchronized with the C streams.
Prototype protected:
ios_base();
Destructor
Prototype ~ios_base();
explicit basic_ios
(basic_streambuf<charT, traits>,
traits *sb);
virtual ~basic_ios();
char_type fill()const;
char_type fill(char_type ch);
protected:
basic_ios();
void init(basic_streambuf<charT, traits>* sb);
};
}
Remarks The basic_ios template class is a base class and includes many
enumerations and mechanisms necessary for input and output op-
erations.
Prototype public:
explicit basic_ios
(basic_streambuf<charT,traits>* sb);
protected:
basic_ios();
Destructor
Remarks The conditions of the member functions after init() are shown in the
following table.
tie
Description To tie an ostream to the calling stream.
Remarks Any stream can have an ostream tied to it to ensure that the os-
tream is flushed before any operation. The standard input and out-
put objects cin and cout are tied to ensure that cout is flushed be-
fore any cin operation. The function tie() is overloaded the
parameterless version returns the current ostream that is tied if any.
The tie() function with an argument ties the new object to the os-
tream and returns a pointer if any from the first. The postcondition
of tie() function that takes the argument tiestr is that tiestr
is equal to tie();
int main()
{
using namespace std;
if(inOut.tie())
cout << "The streams are tied\n";
else cout << "The streams are not tied\n";
inOut.tie(&Out);
inOut.rdbuf()->pubseekoff(0, ios::end);
if(inOut.tie())
cout << "The streams are tied\n";
inOut.close();
return 0;
}
Result:
The streams are not tied
The streams are tied
rdbuf
Description To retrieve a pointer to the stream buffer.
struct address {
int number;
char street[40];
} addbook;
int main()
{
using namespace std;
return 0;
}
Result:
Enter your street number: 2201
Enter your street name: Donley Drive
Your address is: 2201 Donley Drive
imbue
Description Stores a value representing the locale.
fill
Description To insert characters into the stream's unused spaces.
int main()
{
using namespace std;
char fill;
cout.width(8);
cout.fill('*');
fill = cout.fill();
cout<< "Hi!" << "\n";
cout << "The filler is a " << fill << endl;
return 0;
}
Result:
Hi!*****
The filler is a *
copyfmt
Description Copies a basic_ios object.
operator bool
Description A bool operator.
Returns !fail()
operator !
Description A bool not operator.
Return fail().
rdstate
Description To retrieve the state of the current formatting flags.
Remarks This member function allows you to read and check the current sta-
tus of the input and output formatting flags. The returned value
may be stored for use in the function ios::setstate() to reset
the flags at a later date.
int main()
{
ifstream in(inFile);
if(!in.is_open())
{
cout << "could not open file for input";
exit(1);
}
int count = 0;
int c;
while((c = in.get()) != EOF)
{
// simulate a bad bit
if(count++ == 12) in.setstate(ios::badbit);
status(in);
}
status(in);
in.close();
return 0;
}
clear
Description Clears iostate field.
Remarks Use clear() to reset the failbit, eofbit or a badbit that may
have been set inadvertently when you wish to override for continu-
ation of your processing. Postcondition of clear is the argument is
equal to rdstate().
int main()
{
ifstream in(inFile);
if(!in.is_open())
{
cout << "could not open file for input";
exit(1);
}
int count = 0;
int c;
while((c = in.get()) != EOF) {
if(count++ == 4)
{
status(in);
in.close();
return 0;
}
setstate
Description To set the state of the format flags.
Returns No Return
good
Description To test for the lasck of error bits being set.
Remarks Use the function good() to test for the lasck of error bits being set.
Returns
True if rdstate() == 0.
eof
Description To test for the eofbit setting.
Remarks Use the eof() function to test for an eofbit setting in a stream being
processed under some conditions. This end of file bit is not set by
stream opening or closing, but only for operations that detects an
end of file condition.
int main()
{
using namespace std;
ifstream in(TheText);
if(!in.is_open())
{
cout << "Couldn't open file for input";
exit(1);
}
int i = 0;
char c;
cout.setf(ios::uppercase);
C 43
D 44
E 45
fail
Description To test for stream reading failure from any cause.
Remarks The member function fail() will test for failbit and badbit .
int main()
{
using namespace std;
char ch = 0;
while(!in.fail())
{
if(ch)cout.put(ch);
in.get(ch);
}
return 0;
}
Result:
float 33.33 double 3.16e+10 integer 789 character C
bad
Description To test for fatal I/O error.
Remarks Use the member function bad() to test if a fatal input or output
error occurred which sets the badbit flag in the stream.
int main()
{
ifstream in(inFile);
if(!in.is_open())
{
cout << "could not open file for input";
exit(1);
}
int count = 0;
int c;
while((c = in.get()) != EOF)
{
// simulate a failed state
if(count++ == 4) in.setstate(ios::failbit);
status(in);
}
status(in);
in.close();
return 0;
}
exceptions
Description To handle basic_ios exceptions.
Return A mask that determines what elements set in rdstate() cause unde-
fined behavior.
Manipulator Definition
ios_base& unitbuf set the unitbuf flag
(ios_base::unitbuf)
ios_base& nounitbuf unset the unitbuf flag
(ios_base::unitbuf)
Remarks Manipulators are used in the stream to alter the formatting of the
stream.
Remarks Manipulators are used in the stream to alter the formatting of the
stream.
Remarks Manipulators are used in the stream to alter the formatting of the
stream.
Remarks Manipulators are used in the stream to alter the formatting of the
stream.
int main()
{
using namespace std;
return 0;
}
Result:
Original Number is 64
Hexadecimal : 0x40
Octal :0100
Decimal : 64
Overloading Manipulators
Description To provide an in line formatting mechanism.
int main()
{
cout << "align right " << rJus << "for column";
return 0;
}
Header <streambuf>
Prototype namespace std {
template <class charT, class traits =
char_traits<charT> >
class basic_streambuf;
typedef basic_streambuf<char> streambuf;
typedef basic_streambuf<wchar_t> wstreambuf;
}
Prototype
namespace std {
template< class charT, class traits = char_traits<charT> >
class basic_streambuf {
public:
virtual ~basic_streambuf();
pos_type pubseekoff
(off_type off,
ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
pos_type pubseekpos
(pos_type sp,
ios_base::openmode which = ios::in | ios::out);
int pubsync();
streamsize in_avail();
int_type snextc();
int_type sbumpc();
int_type sgetc();
protected:
basic_streambuf();
virtual int_type
pbackfail(int_type c = traits::eof());
Prototype protected:
basic_streambuf();
Remarks The constructor sets all pointer member objects to null pointers and
calls getloc() to copy the global locale at the time of construction.
Destructor
27.5.2.2.1 Locales
Locales are used for encapsulation and manipulation of information
to a particular locale.
basic_streambuf::pubimbue
Description To set the locale.
basic_streambuf::getloc
Description To get the locale.
Return If pubimbue has already been called one it returns the last value
of loc supplied otherwise the current one. If pubimbue has been
called but has not returned a value it from imbue, it then returns the
previous value.
basic_streambuf::pubsetbuf
Description To set an allocation after construction.
int main()
{
using namespace std;
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("Metrowerks CodeWarrior",50);
strbuf.sgetn(temp, 50);
cout << temp;
return 0;
}
Result:
Metrowerks CodeWarrior
basic_streambuf::pubseekoff
Description Determines the position of the get pointer.
#include <iostream>
#include <fstream>
#include <stdlib.h>
int main()
{
using namespace std;
inOut.rdbuf()->pubseekoff(0, ios::end);
inOut.close();
return 0;
}
Result:
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark
basic_streambuf::pubseekpos
Description Determine and move to a desired offset.
int main()
{
using namespace std;
aCheck = in.rdbuf()->pubseekpos(spStart,ios::in);
cout << "The offset at the start of the reading"
<< " in bytes is "
<< static_cast<streamoff>(aCheck) << endl;
char ch;
while(spEnd != spStart+10)
{
in.get(ch);
cout << ch;
spEnd = in.rdbuf()->pubseekoff(0, ios::cur);
}
aCheck = in.rdbuf()->pubseekoff(0,ios::cur);
cout << "\nThe final position's offset"
<< " in bytes now is "
<< static_cast<streamoff>(aCheck) << endl;
in.close();
return 0;
}
Result:
The offfset for the start of the reading in bytes is 5
FGHIJKLMNO
The final position's offset in bytes now is 15
basic_streambuf::pubsync
Description To synchronize the streambuf object with its input/output.
struct address {
int number;
char street[40];
}addbook;
int main()
{
using namespace std;
return 0;
}
Result:
Enter your street number: 2201
basic_streambuf::in_avail
Description To test for availability of input stream.
basic_streambuf::snextc
Description To retrieve the next character in a stream.
Remarks The function snextc() calls sbumpc() to extract the next charac-
ter in a stream. After the operation, the get pointer references the
character following the last character extracted.
int main()
{
using namespace std;
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("ABCDE",50);
char ch;
// look ahead at the next character
ch =strbuf.snextc();
cout << ch;
// get pointer was not returned after peeking
ch = strbuf.snextc();
cout << ch;
return 0;
}
Result:
BC
basic_streambuf::sbumpc
Description To move the get pointer.
Remarks The function sbumpc() moves the get pointer one element when
called.
Return The value of the character at the get pointer. It returns uflow()
if it fails to move the pointer.
int main()
{
using namespace std;
stringbuf strbuf(buf);
int ch;
for (int i = 0; i < 23; i++)
{
ch = strbuf.sgetc();
strbuf.sbumpc();
cout.put(ch);
}
cout << endl;
cout << strbuf.str() << endl;
return 0;
}
Result:
Metrowerks CodeWarrior
Metrowerks CodeWarrior --Software at Work--
basic_streambuf::sgetc
Description To extract a character from the stream.
See streambuf::sbumpc()
basic_streambuf::sgetn
Description To extract a series of characters from the stream.
27.5.2.2.4 Putback
Public functions to return a value to a stream.
basic_streambuf::sputback
Description To put a character back into the stream.
#include <iostream>
#include <sstream>
int main()
{
using namespace std;
stringbuf strbuf(buffer);
char ch;
return 0;
}
Result:
AxBC
xBCDEF
basic_streambuf::sungetc
Description To restore a character extracted.
basic_streambuf::sputc
Description To insert a character in the stream.
Remarks The function sputc() inserts a character into the stream. After the
operation, the get pointer references the character following the last
character extracted.
int main()
{
using namespace std;
stringbuf strbuf;
strbuf.sputc('A');
char ch;
ch = strbuf.sgetc();
cout << ch;
return 0;
}
Result:
A
basic_streambuf::sputn
Description To insert a series of characters into a stream.
basic_streambuf::eback
Description Retrieve the beginning pointer for stream input.
basic_streambuf::gptr
Description Retrieve the next pointer for stream input.
basic_streambuf::egptr
Description Retrieve the end pointer for stream input.
basic_streambuf::gbump
Description Advances the next pointer for stream input.
Remarks The function gbump() advances the input pointer by the value of
the int n argument.
basic_streambuf::setg
Description To set the beginning, next and end pointers.
Remarks After the call to setg() the gbeg pointer equals eback(), the
gnext pointer equals gptr(), and the gend pointer equals
egptr().
basic_streambuf::pbase
Description To retrieve the beginning pointer for stream output.
basic_streambuf::pptr
Description To retrieve the next pointer for stream output.
basic_streambuf::epptr
Description To retrieve the end pointer for stream output.
basic_streambuf::pbump
Description To advance the next pointer for stream output.
Remarks The function pbump() advances the next pointer by the value of
the int argument n.
basic_streambuf::setp
Description To set the values for the beginning, next and end pointers.
Remarks After the call to setp(), pbeg equals pbase(), pbeg equals
pptr() and pend equals epptr().
27.5.2.4.1 Locales
Description To get and set the stream locale. These functions should be overrid-
den in derived classes.
basic_streambuf::imbue
Description To change any translations base on locale.
basic_streambuf::setbuf
Description To set a buffer for stream input and output sequences.
basic_streambuf::seekoff
Description To return an offset of the current pointer in an input or output
streams.
basic_streambuf::seekpos
Description To alter an input or output stream position.
basic_streambuf::sync
Description To synchronize the controlled sequences in arrays.
basic_streambuf::showmanc
Description Shows how many characters in an input stream
basic_streambuf::xsgetn
Description To read a number of characters from and input stream buffer.
Remarks The characters are read by repeated calls to sbumpc() until either
n characters have been assigned or EOF is encountered.
basic_streambuf::underflow
Description To show an underflow condition and not increment the get pointer.
Return The first character of the pending sequence and does not increment
the get pointer. If the position is null returns traits::eof()
to indicate failure.
basic_streambuf::uflow
Description To show a underflow condition for a single character and increment
the get pointer.
27.5.2.4.4 Putback
Virtual functions for replacing data to a stream. These functions
should be overridden in derived classes.
basic_streambuf::pbackfail
Description To show a failure in a put back operation.
Remarks The resulting conditions are the same as the function under-
flow().
Return The function pbackfail() is only called when a put back operation re-
ally has failed and returns traits::eof. If success occurs the return is
undefined.
basic_streambuf::xsputn
Description Write a number of characters to an output buffer.
Remarks The function xsputn() writes to the output character by using re-
peated calls to sputc(c). Write stops when n characters have
been written or EOF is encountered.
basic_streambuf::overflow
Description Consumes the pending characters of an output sequence.
Headers
This section lists the header for istream, ostream, and iomanip.
Header <istream>
Prototype
#include <ios>
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_istream;
template
<class charT, class traits>
basic_istream<charT, traits> &ws
(basic_istream<charT,traits> (is);
}
Header <ostream>
#include <ios>
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_ostream;
template
<class charT, class traits>
basic_ostream<charT, traits> &endl
(basic_ostream<charT,traits>& os);
template
<class charT, class traits>
basic_ostream<charT, traits> &ends
(basic_ostream<charT,traits>& os);
template
<class charT, class traits>
basic_ostream<charT, traits> &flush
(basic_ostream<charT,traits>& os);
}
Header <iomanip>
#include <ios>
namespace std {
// return types are unspecified
T1 resetiosflags(ios_base::fmtflags mask);
T2 setiosflags (ios_base::fmtflag mask);
T3 setbase(int base);
T4 setfill(int c);
T5 setprecision(int n);
T6 setw(int n);
}
Prototype
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_istream : virtual public basic_ios<charT, traits> {
public:
typedef charT
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
explicit basic_istream
(basic_streambuf<charT, traits>* sb);
virtual ~basic_istream();
class sentry;
int_type peek();
int sync();
pos_type tellg();
basic_istream<charT, traits>& seekg
(pos_type);
basic_istream<charT, traits>& seekg
(off_type, ios_base::seekdir);
};
}
Destructor
int main()
{
using namespace std;
istream inOut(out.rdbuf());
char c;
while(inOut.get(c)) cout.put(c);
return 0;
}
Result:
Ask the teacher anything you want to know
(basic_istream<charT,
traits>& is,
bool noskipws = false);
~sentry();
operator bool() {return ok_;}
};
}
Remarks If after the operation is.good() is true ok_ equals true oth-
erwise ok_ equals false. The constructor may call set-
state(failbit) which may throw an exception.
Destructor
Prototype ~sentry();
sentry::Operator bool
Description To return the value of the data member ok_.
Remarks The Arithmetic extractors extract a specific type from the input
stream and store it in the address provided
NOTE: The white space character is not extracted and is not dis-
carded, but simply ignored. Be careful when mixing unformatted
input operations with the formatted extractor operators. Such as
when using console input.
int main()
{
using namespace std;
ifstream in(ioFile);
if(!in.is_open())
{cout << "cannot open file for input"; exit(1);}
char type[20];
double d;
int i;
char ch;
cout << i << " " << type << " "
<< ch << " " << d << endl;
in.close();
return 0;
}
Result:
float 33.33
double 3.16e+10
Integer 789
character C
Overloading Extractors:
Description To provide custom formatted data retrieval.
Remarks You may overload the extractor operator to tailor the specific
needs of a particular class.
class phonebook {
friend std::ostream &operator<<(std::ostream &stream,
phonebook o);
friend std::istream &operator>>(std::istream &stream,
phonebook &o);
private:
char name[80];
int areacode;
int exchange;
int num;
public:
void putname() {std::cout << num;}
phonebook() {}; // default constructor
phonebook(char *n, int a, int p, int nm)
{std::strcpy(name, n); areacode = a;
exchange = p; num = nm;}
};
int main()
{
using namespace std;
phonebook a;
cin >> a;
cout << a;
return 0;
}
char buf[5];
cout << "Enter the name: ";
stream >> o.name;
basic_istream::gcount
Description To obtain the number of bytes read.
Remarks Use the function gcount() to obtain the number of bytes read by
the last unformatted input function called by that object.
const SIZE = 4;
struct stArray {
int index;
double dNum;
};
int main()
{
using namespace std;
ofstream fOut("test");
if(!fOut.is_open())
{cout << "can't open out file"; return 1;}
stArray arr;
short i;
stArray aIn[SIZE];
ifstream fIn("test");
if(!fIn.is_open())
{cout << "can't open in file"; return 2;}
count+=fIn.gcount();
}
cout << count << " bytes read " << endl;
cout << "The size of the structure is "
<< sizeof(stArray) << endl;
for(i = 0; i < SIZE; i++)
cout << aIn[i].index << " " << aIn[i].dNum
<< endl;
fIn.close();
return 0;
}
Result:
48 bytes read
The size of the structure is 12
1 3.14
2 6.28
3 9.42
4 12.56
basic_istream::get
Description Overloaded functions to retrieve a char or a char sequence from
an input stream.
(char_type* s,
streamsize n,
char_type delim = traits::newline());
Remarks Extracts characters and stores them in a char array
at an address pointed to by s, until
• A limit (the second argument minus one) or the number of
characters to be stored is reached
• A delimiter (the default value is the newline character) is
met. In which case, the delimiter is not extracted.
• If end_of_file is encountered in which case set-
state(eofbit) is called.
Returns An integer when used with no argument. When used with an argu-
ment if a character is extracted the get() function returns The
this pointer. If no character is extracted setstate(failbit) is called.
In any case a null char is appended to the array.
int main()
{
using namespace std;
char ch;
while(in.get(ch)) cout << ch;
return 0;
}
Result:
float 33.33 double 3.16e+10 Integer 789 character C
#include <iostream>
#include <iostream>
int main()
{
using namespace std;
return 0;
}
Result:
Enter your name: Metrowerks CodeWarrior <enter>
Metrowerks CodeWarrior
basic_istream::getline
Description To obtain a delimiter terminated character sequence from an input
stream.
In any case it stores a null char into the next successive location of
the array.
char compiler[size];
return 0;
}
Result:
Enter your compiler:Metrowerks CodeWarrior <enter>
You use Metrowerks CodeWarrior
#include <iostream>
int main()
{
using namespace std;
cin.getline(compiler, size,TAB);
cout << compiler;
cout << "\nsecond input not needed\n";
return 0;
}
Result:
What kind of Compiler do you use:
Metrowerks CodeWarrior<tab>Why?
Metrowerks CodeWarrior
second input not needed
Why?
basic_istream::ignore
Description To extract and discard a number of characters.
Remarks The function ignore() will extract and discard characters until
• A limit is met (the first argument)
• end-of-file is encountered (in which case setstate(eofbit)
is called.)
• The next character c is equal to the delimiter delim, in
which case it is extracted except when c is equal to
traits::eof();
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "file not opened"; exit(1);}
char ch;
while((ch = in.get()) != EOF)
{
if(ch == bslash && in.peek() == bslash)
{
in.ignore(100, '\n');
cout << '\n';
}
else cout << ch;
}
return 0;
}
Result:
char ch;
/*This C comment will remain */
while((ch = in.get())!= EOF) cout.put(ch);
basic_istream::peek
Description To view at the next character to be extracted.
Remarks The function peek() allows you to look ahead at the next character
in a stream to be extracted without extracting it.
basic_istream::read
Description To obtain a block of binary data from and input stream.
Remarks The function read() will attempt to extract a block of binary data
until the following conditions are met.
• A limit of n number of characters are stored.
• end-of-file is encountered on the input (in which case
setstate(failbit) is called.
#include <cstdlib>
#include <cstring>
struct stock {
char name[80];
double price;
long trades;
};
int main()
{
using namespace std;
strcpy(Opening.name, Company);
Opening.price = 180.25;
Opening.trades = 581300;
<< "The closing price is: $" << Closing.price << endl;
Market2.close();
return 0;
}
Result:
Big Bucks Inc.
The number of trades was: 581300
The closing price is: $180.25
basic_istream::readsome
Description Extracts characters and stores them in an array.
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
int main()
{
using namespace std;
in.close();
return 0;
}
Result:
Metrowerks CodeWarrior
Software at Work
Registered Trademark
basic_istream::putback
Description To replace a previously extracted character.
Remarks The function putback() allows you to replace the last character ex-
tracted by calling rdbuf()->sungetc(). If the buffer is empty, or
if sungetc() returns eof, setstate(failbit) may be called.
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "file not opened"; exit(1);}
if(tmp != bslash)
in.putback(tmp);
else continue;
}
cout << ch;
}
return 0;
}
Result:
char ch; to save char
/* comment will remain */
while((ch = in.get())!= EOF) cout.put(ch);
read until failure
basic_istream::unget
Description To replace a previously extracted character.
Remarks Use the function unget() to return the previously extracted charac-
ter. If rdbuf() is null or if end-of-file is encountered set-
state(badbit) is called.
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "file not opened"; exit(1);}
return 0;
}
Result:
char ch; to save char
/* comment will remain */
read until failure
while((ch = in.get()) != EOF) cout.put(ch);
basic_istream::sync
Description To synchronize input and output
Remarks This functions attempts to make the input source consistent with the
stream being extracted.
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "could not open file"; exit(1);}
char str[10];
if(in.sync())// return 0 if successful
{ cout << "cannot sync"; exit(1); }
while (in.good())
{
in.get(str, 10, EOF);
cout <<str;
}
return 0;
}
Result:
This functions attempts to make the input source
consistent with the stream being extracted.
--
Metrowerks CodeWarrior "Software at Work"
basic_istream::tellg
Description To determine the offset of the get pointer in a stream
basic_istream::seekg
Description To move to a variable position in a stream.
int main()
{
using namespace std;
in.seekg(spStart);
aCheck = in.tellg();
cout << "The offfset at the start of the reading in bytes is "
<< aCheck.offset() << endl;
char ch;
while(spEnd != spStart+10)
{
in.get(ch);
cout << ch;
spEnd = in.tellg();
aCheck = in.tellg();
cout << "\nThe current position's offset in bytes now is "
<< aCheck.offset() << endl;
streamoff gSet = 0;
in.seekg(gSet, ios::beg);
aCheck = in.tellg();
cout << "The final position's offset in bytes now is "
<< aCheck.offset() << endl;
in.close();
return 0;
}
Result:
The offfset at the start of the reading in bytes is 5
FGHIJKLMNO
The current position's offset in bytes now is 15
The final position's offset in bytes now is 0
basic_ifstream::ws
Description To provide inline style formatting.
Prototype template
<class charT, class traits>
basic_istream<charT, traits> &ws
(basic_istream<charT,traits>& is);
int main()
{
char * inFileName = "MW Reference";
ifstream in(inFileName);
if (!in.is_open())
{cout << "Couldn’t open for input\n"; exit(1);}
char ch;
in.unsetf(ios::skipws);
if (in.good())
in.close();
return(0);
}
Result:
Does not skip whitespace
| a b c|
Destructor
Prototype
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_ostream : virtual public basic_ios<charT, traits>{
public:
// Types:
typedef charTchar_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
class sentry;
pos_type tellp();
basic_ostream<charT, traits>& seekp(pos_type);
basic_ostream<charT, traits>& seekp
(off_type, ios_base::seekdir);
};
}
Destructor
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
inOut.rdbuf()->pubseekoff(0, ios::end);
inOut.close();
return 0;
}
Result:
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark
Remarks If after the operation os.good() is true ok_ equals true oth-
erwise ok_ equals false. The constructor may call set-
state(failbit) which may throw an exception.
Destructor
Prototype ~sentry();
sentry::Operator bool
Description To return the value of the data member ok_.
If the function fails for any for any reason the function calls set-
state(failbit).
(long double f)
Remarks The ostream insertion operators are overloaded to provide for in-
sertion of most predefined types into and output stream. They re-
turn a reference to the basic stream object so they may be used in
a chain of statements to input various types to the same stream.
Returns In most cases *this is returned unless failure in which case set-
state(failbit) is called.
27.6.2.4.3 basic_ostream::operator<<
Prototype basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>&
(*pf)(basic_ostream<charT, traits>&));
Remarks Returns pf(*this).
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>&
(*pf)(basic_ios<charT, traits>&));
Remarks Calls pf(*this) return *this.
basic_ostream<charT, traits>& operator<<
(const char_type *s)
Remarks The formatted output functions insert the values into the appropri-
ate argument type.
int main()
{
using namespace std;
ofstream out(oFile);
return 0;
}
Result:
Output: to MWReference
float 33.33 double 3.16e+10 Integer 789 character C
Output to console
float 33.33
double 3.16e+10
Integer 789
character C
Overloading Inserters
Description To provide specialized output mechanisms for an object.
Remarks You may overload the inserter operator to tailor it to the specific
needs of a particular class.
class phonebook {
friend ostream &operator<<
(ostream &stream, phonebook o);
protected:
char *name;
int areacode;
int exchange;
int num;
public:
phonebook(char *n, int a, int p, int nm) :
areacode(a),
exchange(p),
num(nm),
name(n) {}
};
int main()
{
using namespace std;
return 0;
}
basic_ostream::tellp
Description To return the offset of the put pointer in an output stream.
basic_ostream::seekp
Description Randomly move to a position in an output stream.
int main()
{
using namespace std;
ostringstream ostr(motto);
streampos cur_pos, start_pos;
cur_pos = ostr.tellp();
cout << "The current position is "
<< cur_pos.offset()
<< " from the beginning\n";
ostr.seekp(str_off);
cur_pos = ostr.tellp();
cout << "The current position is "
<< cur_pos.offset()
<< " from the beginning\n";
strbuf->sputc('\0');
return 0;
}
Results:
The original array was :
Metrowerks CodeWarrior - Software at Work
basic_ostream::put
Description To place a single character in the output stream.
Remarks The unformatted function put() inserts one character in the output
stream. If the operation fails calls setstate(badbit).
int main()
{
using namespace std;
basic_ostream::write
Description To insert a block of binary data into an output stream.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
struct stock {
char name[80];
double price;
long trades;
};
int main()
{
using namespace std;
strcpy(Opening.name, Company);
Opening.price = 180.25;
Opening.trades = 581300;
Market2.close();
return 0;
}
Result:
Big Bucks Inc.
The number of trades was: 581300
The closing price is: $180.25
basic_ostream::flush
Description To force the output buffer to release its contents.
Remarks The function flush() is an output only function in C++. You may
use it for an immediate expulsion of the output buffer. This is useful
when you have critical data or you need to ensure that a sequence of
events occurs in a particular order. If the operation fails calls set-
state(badbit).
class stopwatch {
private:
double begin, set, end;
public:
stopwatch();
~stopwatch();
void start();
void stop();
};
stopwatch::stopwatch()
{
using namespace std;
stopwatch::~stopwatch()
{
using namespace std;
set = double(clock()/CLOCKS_PER_SEC);
}
void stopwatch::stop()
{
using namespace std;
end = double(clock()/CLOCKS_PER_SEC);
}
int main()
{
using namespace std;
basic_ostream:: endl
Description To insert a newline and flush the output stream.
Prototype template
< class charT, class traits >
basic_ostream<charT, traits> & endl
(basic_ostream<charT,traits>& os);
basic_ostream::ends
Description To insert a NULL character.
Prototype template
< class charT, class traits >
basic_ostream<charT, traits> &ends
(basic_ostream<charT,traits>& os);
#include <iostream>
#include <sstream>
int main()
{
using namespace std;
basic_ostream::flush
Description To flush the stream for output.
class stopwatch {
private:
double begin, set, end;
public:
stopwatch();
~stopwatch();
void start();
void stop();
};
stopwatch::stopwatch()
{
using namespace std;
stopwatch::~stopwatch()
{
using namespace std;
set = double(clock()/CLOCKS_PER_SEC);
}
void stopwatch::stop()
{
using namespace std;
end = double(clock()/CLOCKS_PER_SEC);
}
int main()
{
using namespace std;
Results:
Note: comment out the flush and both lines display simultaneously at the end of the
program.
begin time the timer:
< short pause >
The Object lasted: 3.78 seconds
resetiosflags
Description To unset previously set formatting flags.
int main()
{
using namespace std;
double d = 2933.51;
long flags;
flags = ios::scientific | ios::showpos | ios::showpoint;
return 0;
}
Result:
Original: 2933.51
Flags set: +2.933510e+03
Flags reset to original: 2933.51
setiosflags
Description Set the stream format flags.
Remarks Use the manipulator setiosflags() to set the input and output
formatting flags directly in the stream.
:setbase
Description To set the numeric base of an output.
Remarks The manipulator setbase() directly sets the numeric base of inte-
gral output to the stream. The arguments are in the form of 8, 10, 16,
or 0. 8 octal, 10 decimal and 16 hexadecimal. Zero represents
ios::basefield, a combination of all three.
int main()
{
using namespace std;
return 0;
}
Result:
Hexadecimal c4
Decimal 196
Octal 304
Reset to Hex c4
Reset basefield setting 196
setfill
Description To specify the characters to used to insert in unused spaces in the
output.
Remarks Use the manipulator setfill() directly in the output to fill blank
spaces with character c.
int main()
{
using namespace std;
cout.width(8);
cout << setfill('*') << "Hi!" << "\n";
char fill = cout.fill();
cout << "The filler is a " << fill << endl;
return 0;
}
Result:
Hi!*****
The filler is a *
setprecision
Description Set and return the current format precision.
int main()
{
using namespace std;
Result:
Original: 321.123
Precision set: 321.12346
setw
Description To set the width of the output field.
Remarks Use the manipulator setw() directly in a stream to set the field size
for output.
int main()
{
using namespace std;
Overloaded Manipulator
Description To store a function pointer and object type for input.
char buffer[80];
int main()
{
using namespace std;
return 0;
}
short attempts = 3;
do {
cout << "Enter password: ";
stream >> buffer;
StrUpr(buffer);
if (! strcmp(check, buffer)) return stream;
cout << "\a\a";
attempts--;
} while(attempts > 0);
return stream;
}
Header <sstream>
Overview The header <sstream> includes classes and typed that associate
stream buffers with string objects for input and output manipula-
tions.
Prototype
namespace std{
template
<class charT, class traits = char_traits<charT> >
class basic_stringbuf;
typedef basic_stringbuf<char>stringbuf;
typedef basic_strngbuf<wchar>wstringbuf;
template
<class charT, class traits = char_traits<charT> >
class basic_istringstream;
typedef basic_istringstream<char> istringstream;
typedef basic_istringstream<wchar> wistringstream;
template
<class charT, class traits = char_traits<charT> >
class basic_ostringstream;
typedef basic_ostringstream<char> ostringstream;
typedef basic_ostringstream<wchar> wostringstream;
};
}
Prototype
template
<class charT, class traits = char_traits<charT> >
class basic_stringbuf: public basic_streambuf<charT, traits> > {
public:
explicit basic_stringbuf
(ios_base::openmode which = ios_base::in | ios_base:out);
explicit basic_stringbuf
(const basic_string<char_type> &str,
ios_base::openmode which = ios_base::in | ios_base:out);
protected
virtual int_type underflow();
virtual int_type pbackfail
(int_type c = traits::eof());
virtual int_type overflow
(int_type c = traits::eof());
private:
ios_base::openmode mode; exposition only
};
}
• explicit basic_stringbuf(ios_base::openmode);
• explicit basic_stringbuf(const basic_string,
ios_base::openmode);
Constructor
int main()
{
using namespace std;
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("ABCDE",50);
char ch;
// look ahead at the next character
ch =strbuf.snextc();
cout << ch;
// get pointer was not returned after peeking
ch = strbuf.snextc();
cout << ch;
return 0;
}
Result:
BC
basic_stringbuf::str
Description To return the basic_string object stored in the buffer.
int main()
{
using namespace std;
string buf;
stringbuf strbuf(buf, ios::out);
int size;
size = strlen(CW);
strbuf.sputn(CW, size);
size = strlen(AW);
strbuf.sputn(AW, size);
return 0;
}
Result
Metrowerks CodeWarrior - "Software at Work"
basic_stringbuf::underflow
Description To show an underflow condition and not increment the get pointer.
Returns The first character of the pending sequence and does not increment
the get pointer. If the position is null returns traits::eof()
to indicate failure.
basic_stringbuf::pbackfail
Description To show a failure in a put back operation.
Returns The function pbackfail() is only called when a put back operation re-
ally has failed and returns traits::eof. If success occurs the return is
undefined.
basic_stringbuf::overflow
Description Consumes the pending characters of an output sequence.
basic_stringbuf::seekoff
Description To return an offset of the current pointer in an input or output
streams.
basic_stringbuf::seekpos
Description To alter an input or output stream position.
The prototype is listed below. The other topics in this section are:
• “27.7.2.1 basic_istringstream constructors” on page 598
• “27.7.2.2 Member functions” on page 599
Prototype
namespace std {
template
<class charT, class traits = char_traits<charT> >
class basic_istringstream : public basic_istream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
explicit basic_istringstream
(ios_base::openmode which = ios_base::in);
explicit basic_istringstream
(const basic_string<charT> &str,
ios_base::openmode which = ios_base::in);
private:
basic_stringbuf<charT,traits> sb; exposition only
};
}
basic_stringstream, basic_filebuf.
Constructor
int main()
{
using namespace std;
cout << num << " " << flt << " "
<< szArr << endl;
return 0;
}
Result
3 12.3 line
basic_istringstream::rdbuf
Description To retrieve a pointer to the stream buffer.
int main()
{
using namespace std;
istringstream ist(buf);
istream in(ist.rdbuf());
in.seekg(25);
in.get(words,50);
cout << words;
return 0
}
Result
"Software at work"
basic_istringstream::str
Description To return the basic_string object stored in the buffer.
basic_stringstream::str()
int main()
{
using namespace std;
istringstream istr(buf);
cout << istr.str();
return 0;
}
Result:
Metrowerks CodeWarrior - "Software at Work"
The prototype is listed below. The other topics in this section are:
• 27.7.2.4 basic_ostringstream constructors
• 27.7.2.5 Member functions
Prototype
namespace std {
template
<class charT, class traits = char_traits<charT> >
class basic_ostringstream : public basic_ostream<charT, traits>{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
explicit basic_ostringstream
(ios_base::openmode which = ios_base::out);
explicit basic_ostringstream
(const basic_string<charT> &str,
ios_base::openmode which = ios_base::out);
private:
basic_stringbuf<charT,traits> sb; exposition only
};
}
• basic_ostringstream
(ios_base::openmode)
• basic_ostringstream
(const basic_string, ios_base::openmode
Constructor
int main()
{
using namespace std;
ostringstream Paragraph;
char ch ='\0';
in.close();
return 0;
}
Result:
Metrowerks CodeWarrior - “Software at Work”
Registered Trademark
basic_ostringstream::rdbuf
Description To retrieve a pointer to the stream buffer.
int main()
{
using namespace std;
ostringstream ostr(motto);
streampos cur_pos(0), start_pos(0);
ostr.seekp(str_off);
cur_pos = ostr.tellp();
cout << "The current position is "
<< static_cast<streamoff>(cur_pos);
<< " from the beginning\n";
strbuf->sputc('\0');
return 0;
}
Results:
The original array was :
Metrowerks CodeWarrior - "Software at Work"
basic_ostringstream::str
Description To return the basic_string object stored in the buffer.
basic_stringstream::str()
int main()
{
using namespace std;
ostringstream out;
out << "Ask the teacher anything\n";
out << "OK, what is 2 + 2?\n";
out << 2 << " plus " << 2 << " equals "
<< 4 << ends;
The prototype is listed below. The other topics in this section are:
• 27.7.3.4 basic_stringstream constructors
• 27.7.3.5 Member functions
Prototype
namespace std {
template
<class charT, class traits = char_traits<charT> >
class basic_stringstream : public basic_iostream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
explicit basic_stringstream
(ios_base::openmode which = ios_base::out | ios_base::out);
explicit basic_stringstream
(const basic_string<charT> &str,
ios_base::openmode which = ios_base::out | ios_base::out);
private:
basic_stringbuf<charT,traits> sb; exposition only
};
}
Constructor
int main()
{
using namespace std;
stringstream iost;
char word[20];
long num;
double real;
return 0;
}
Result
ABCD 22 33.33
basic_stringstream::rdbuf
Description To retrieve a pointer to the stream buffer.
int main()
{
using namespace std;
in.get(words,50);
cout << words;
return 0;
}
Result
“Software at Work”
basic_stringstream::str
Description To return the basic_string object stored in the buffer.
basic_istringstream::str()
int main()
{
using namespace std;
return 0;
}
Result
Metrowerks CodeWarrior - "Software at Work"
Header <fstream>
Description The header <fstream> defines template classes and types to assist in
reading and writing of files.
template
<class charT, class traits = ios_traits<charT> >
class basic_ifstream;
typedef basic_ifstream<char> ifstream;
typedef basic_ifstream<wchar_t> wifstream;
template
<class charT, class traits = ios_traits<charT> >
class basic_ofstream;
typedef basic_ofstream<char> ofstream;
typedef basic_ofstream<wchar_t> wofstream;
}
Prototype
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_filebuf : public basic_streambuf <charT, traits>
{
public:
basic_filebuf();
virtual ~basic_filebuf();
protected:
};
}
Remarks The filebuf class is derived from the streambuf class and pro-
vides a buffer for file output and or input.
Prototype basic_filebuf()
Destructor
basic_filebuf::is_open
Description Test to ensure filebuf stream is open for reading or writing.
basic_filebuf::open
Description Open a basic_filebuf object and associate it with a file.
Remarks You would use the function open() to open a filebuf object and
associate it with a file. You may use open() to reopen a buffer and
associate it if the object was closed but not destroyed.
int main(){
using namespace std;
filebuf in;
in.open(inFile, ios::out | ios::app);
if(!in.is_open())
{cout << "could not open file"; exit(1);}
char str[] = "\n\tregistered trademark";
in.sputn(str, strlen(str));
in.close();
return 0;
}
Result:
The file MW Reference now contains:
Metrowerks CodeWarrior "Software at Work"
registered trademark
basic_filebuf::close
Description To close a filebuf stream without destroying it.
Remarks The function close() would remove the stream from memory but
will not remove the filebuf object. You may re-open a filebuf
stream that was closed using the close() function.
basic_filebuf::showmanyc
Description Overrides basic_streambuf::showmanyc().
basic_filebuf::underflow
Description Overrides basic_streambu::underflow();
basic_filebuf::pbackfail
Description Overrides basic_streambuf::pbackfail().
Remarks This function puts back the characters designated by c to the input
sequence if possible.
Returns traits::eof() if failure and returns either the character put back
or traits::not_eof(c) for success.
basic_filebuf::overflow
Description Overrides basic_streambuf::overflow()
basic_filebuf::seekoff
Description Overrides basic_streambuf::seekoff()
Remarks Sets the offset position of the stream as if using the C standard li-
brary function fseek(file, off, whence).
basic_filebuf::seekpos
Description Overrides basic_streambuf::seekpos()
basic_filebuf::setbuf
Description Overrides basic_streambuf::setbuf()
basic_filebuf::sync
Description Overrides basic_streambuf::sync
basic_filebuf::imbue
Description Overrides basic_streambuf::imbue
Prototype
namespace std{
template
<class charT, class traits = ios_traits<charT> > {
class basic_ifstream : public basic_istream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits:int_type int_type;
typedef typename traits:pos_type pos_type;
typedef typename traits:off_type off_type;
basic_ifstream();
explicit basic_ifstream
(const char *s, openmode mode = in);
private:
basic_filebuf<charT, traits> sb; exposition only
};
}
Prototype basic_ifstream();
explicit basic_ifstream
(const char *s, openmode mode = in);
Remarks The constructor creates a stream for file input; it is overloaded to ei-
ther create and initialize when called or to simply create a class and
be opened using the open() member function.he default opening
mode is ios::in.see basic_filebuf::open() for valid open mode
settings.
int main()
{
using namespace std;
char c ='\0';
while(in.good())
{
if(c) cout << c;
in.get(c);
in.close();
return 0;
}
Result:
Metrowerks CodeWarrior "Software at Work"
basic_ifstream::rdbuf
Description The rdbuf() function retrieves a pointer to a filebuf type
buffer.
int main()
{
using namespace std;
ostream Out(inOut.rdbuf());
inOut.rdbuf()->pubseekoff(0, ios::end);
inOut.close();
return 0;
}
Result:
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark
basic_ifstream::is_open
Description Test for open stream.
Remarks Use is_open() to test that a stream is indeed open and ready for
input from the file.
basic_ifstream::open
Description Open is used to open a file or reopen a file after closing it.
Remarks The default open mode is ios::in, but can be one of several
modes. (see below) A stream is opened and prepared for input or
output as selected.
Returns No return
int main()
{
using namespace std;
ifstream in;
in.open(inFile);
if(!in.is_open())
{cout << "can’t open input file"; exit(1);}
char c = NULL;
while((c = in.get()) != EOF)
{
cout << c;
}
in.close();
return 0;
}
Result:
Metrowerks CodeWarrior "Software at Work"
basic_ifstream::close
Description Closes the file stream.
Remarks The close() function closes the stream for operation but does not
destroy the ifstream object so it may be re-opened at a later time.
If the function fails calls setstate(failbit) which may throw and ex-
ception.
Returns: No return.
Prototype
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_ofstream : public basic_ostream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits:int_type int_type;
typedef typename traits:pos_type pos_type;
typedef typename traits:off_type off_type;
basic_ofstream();
explicit basic_ofstream
(const char *s, openmode mode = out | trunc);
private:
basic_filebuf<charT, traits> sb; exposition only
};
}
Prototype basic_ofstream();
explicit basic_ofstream
(const char *s, openmode mode = out | trunc);
Remarks The class basic_ofstream creates an object for handling file output.
It may be opened later using the ofstream:: open() member
function. It may also be associated with a file when the object is de-
clared. The default open mode is ios::out.
NOTE: There are only certain valid file opening modes for an of-
stream object see basic_ofstream::open() for a list of valid
opening modes.
int main()
{
using namespace std;
ofstream out(outFile);
if(!out.is_open())
{cout << "file not opened"; exit(1);}
out.close();
return 0;
}
Result:
This is an annotated reference that contains a description
of the Working ANSI C++ Standard Library and other
facilities of the Metrowerks Standard Library.
basic_ofstream::rdbuf
Description To retrieve a pointer to the stream buffer.
int main()
{
using namespace std;
char ch;
while((ch = inOut.get()) != EOF)
{
cout.put(ch);
}
out.close();
return 0;
}
Result:
This is an annotated reference that contains a description
of the Working ANSI C++ Standard Library and other
facilities of the Metrowerks Standard Library.
basic_ofstream::is_open
Description To test whether the file was opened.
Remarks The is_open() function is used to check that a file stream was in-
deed opened and ready for output. You should always test with this
function after using the constructor or the open() function to open
a stream.
basic_ofstream::open
Description To open or re-open a file stream for output.
Remarks The function open() opens a file stream for output. The default
mode is ios::out, but may be any valid open mode (see below.) If
failure occurs open() calls setstate(failbit) which may
throw an exception.
Returns No return
int main()
{
using namespace std;
ofstream out;
out.open(outFile, ios::out | ios::app);
if(!out.is_open())
{cout << "file not opened"; exit(1);}
out.close();
return 0;
}
Result:
After the operation MW Reference contained
Chapter One
This is an annotated reference that contains a description
of the Working ANSI C++ Standard Library and other
facilities of the Metrowerks Standard Library.
basic_ofstream::close
Description The member function closes the stream but does not destroy it.
Returns No return.
basic_ofstream()
The prototype is listed below. The other topic in this section is:
• “27.8.1.12 basic_fstream Constructor” on page 637
• “27.8.1.13 Member Functions” on page 638
Prototype
namespace std {
template
<class charT, class traits=ios_traits<charT> >
class basic_fstream : public basic_iostream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
basic_fstream();
explicit basic_fstream
(const char *s,
ios_base::openmode = ios_base::in | ios_base::out);
bool is_open();
void open
(const char* s,
ios_base::openmode = ios_base::in | ios_base::out);
void close();
private:
Remarks The template class basic_fstream is used for both reading and writ-
ing from files.
Prototypes basic_fstream();
explicit basic_fstream
(const char *s,
ios_base::openmode =
ios_base::in | ios_base::out);
int main()
{
using namespace std;
char ch;
while((ch = inOut.get())!= EOF)
{
cout << ch;
}
inOut.clear();
inOut << str;
inOut.close();
return 0;
}
Result:
Metrowerks CodeWarrior "Software at Work"
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark
basic_fstream::rdbuf
Description The rdbuf() function retrieves a pointer to a filebuf type
buffer.
int main()
{
using namespace std;
fstream inOut;
inOut.open(inFile, ios::in | ios::out);
if(!inOut.is_open())
{cout << "Could not open file"; exit(1);}
inOut.rdbuf()->pubseekoff(0,ios::end);
inOut << str;
inOut.close();
return 0;
}
Result:
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark
basic_fstream::is_open
Description Test to ensure basic_fstream file is open and available for read-
ing or writing.
basic_fstream::open
Description To open or re-open a file stream for input or output.
Returns No return.
basic_fstream::close
Description The member function closes the stream but does not destroy it.
Returns No return.
<cstdio> Types
Types:
FILE fpos_t size_t
<cstdio> Functions
Functions:
clearerr fclose feof
ferror fflush fgetc
fgetpos fgets fopen
fprintf fputc fputs
fread freopen fscanf
fseek fsetpos ftell
fwrite getc getchar
gets perror printf
putc putchar puts
remove rename rewind
scanf setbuf setvbuf
sprintf scanf tmpnam
ugetc vprintf vfprintf
vsprintf tmpfile
Header <strstream>
The include file strstream includes three classes, for in memory
character array based stream input and output.
class strstreambuf
: public streambuf
{
public:
explicit strstreambuf(streamsize alsize_arg = 0);
strstreambuf(void* (*palloc_arg)(size_t),
void (*pfree_arg)(void*));
strstreambuf(char* gnext_arg, streamsize n, char* pbeg_arg = 0);
strstreambuf(const char* gnext_arg, streamsize n);
strstreambuf(signed char* gnext_arg, streamsize n,
signed char* pbeg_arg = 0);
strstreambuf(const signed char* gnext_arg, streamsize n);
strstreambuf(unsigned char* gnext_arg, streamsize n,
unsigned char* pbeg_arg = 0);
strstreambuf(const unsigned char* gnext_arg, streamsize n);
virtual ~strstreambuf();
void freeze(bool freezefl = true);
char* str();
int pcount() const;
protected:
virtual int_type overflow (int_type c = EOF);
virtual int_type pbackfail(int_type c = EOF);
virtual int_type underflow();
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual pos_type seekpos(pos_type sp,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual streambuf* setbuf(char* s, streamsize n);
private:
typedef unsigned char strstate;
static const strstate allocated = 1 << 0;
static const strstate constant = 1 << 1;
static const strstate dynamic = 1 << 2;
static const strstate frozen = 1 << 3;
static const streamsize default_alsize = 128;
streamsize alsize_;
void* (*palloc_)(size_t);
void (*pfree_)(void*);
strstate strmode_;
Strstreambuf Class
The class strstreambuf is derived from streambuf to associate a
stream with an in memory character array.
class strstreambuf
: public streambuf
{
public:
explicit strstreambuf(streamsize alsize_arg = 0);
strstreambuf(void* (*palloc_arg)(size_t),
void (*pfree_arg)(void*));
strstreambuf(char* gnext_arg, streamsize n, char* pbeg_arg = 0);
strstreambuf(const char* gnext_arg, streamsize n);
strstreambuf(signed char* gnext_arg, streamsize n,
signed char* pbeg_arg = 0);
strstreambuf(const signed char* gnext_arg, streamsize n);
strstreambuf(unsigned char* gnext_arg, streamsize n,
unsigned char* pbeg_arg = 0);
strstreambuf(const unsigned char* gnext_arg, streamsize n);
virtual ~strstreambuf();
void freeze(bool freezefl = true);
char* str();
int pcount() const;
protected:
virtual int_type overflow (int_type c = EOF);
virtual int_type pbackfail(int_type c = EOF);
virtual int_type underflow();
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual pos_type seekpos(pos_type sp,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual streambuf* setbuf(char* s, streamsize n);
private:
typedef unsigned char strstate;
static const strstate allocated = 1 << 0;
static const strstate constant = 1 << 1;
static const strstate dynamic = 1 << 2;
static const strstate frozen = 1 << 3;
static const streamsize default_alsize = 128;
streamsize alsize_;
void* (*palloc_)(size_t);
void (*pfree_)(void*);
strstate strmode_;
Remarks The constructor sets all pointer member objects to null pointers.
Destructor
freeze
Description To freeze the allocation of strstreambuf.
Return No return
int main()
{
Result:
The size of the stream is: 11
The size of the stream is: 22
The size of the stream is: 23
The buffer contains:
Metrowerks CodeWarrior
pcount
Description To determine the effective length of the buffer,
Remarks The function pcount() is used to determine the offset of the next
character position from the beginning of the buffer.
str
Description To return the char array stored in the buffer.
Remarks The function str() freezes the buffer and appends a null character
then returns the array. The user is responsible for destruction of any
dynamically allocated buffer.
int main()
{
ostrstream ostr(buf, size);
ostr << arr;
// associate buffer
strstreambuf *strbuf(ostr.rdbuf());
// do some manipulations
strbuf->pubseekoff(10,ios::beg);
strbuf->sputc('\0');
strbuf->pubseekoff(0, ios::beg);
cout << "The original array was\n" << arr << "\n\n";
cout << "The strstreambuf array is\n"
<< strbuf->str() << "\n\n";
cout << "The ostrstream array is now\n" << buf;
return 0;
}
Result:
The original array was
Metrowerks CodeWarrior - Software at Work
setbuf
Description To set a buffer for stream input and output sequences.
seekoff
Description To return an offset of the current pointer in an input or output
streams.
seekpos
Description To alter an input or output stream position.
underflow
Description To show an underflow condition and not increment the get pointer.
Return The first character of the pending sequence and does not increment
the get pointer. If the position is null returns traits::eof()
to indicate failure.
pbackfail
Description To show a failure in a put back operation.
Remarks The resulting conditions are the same as the function under-
flow().
Return The function pbackfail() is only called when a put back operation re-
ally has failed and returns traits::eof. If success occurs the return is
undefined.
overflow
Description Consumes the pending characters of an output sequence.
Istrstream Class
The class istrstream is used to create and associate a stream
with an array for input.
private:
strstreambuf strbuf_;
};
Constructors
Description Create an array based stream for input
int main()
{
char arr[4][20];
double d;
long i;
istrstream istr(buf);
istr >> arr[0] >> d >> arr[1] >> arr[2] >> arr[3] >> i;
return 0;
}
Result:
double is 3.21
string is array
int is 321
Destructor
Description To destroy an istrstream object.
rdbuf
Description Returns a pointer to the strsteambuf
See: strstreambuf::str()
str
Description Return a pointer to the stored array.
Remarks The function str() freezes and terminates the character array stored
in the buffer with a null character. It then returns the null termi-
nated character array.
int main()
{
istrstream istr(buf, size);
cout << istr.str();
return 0;
}
Result:
Metrowerks CodeWarrior - Software at Work
Ostrstream Class
The class strstreambuf is derived from streambuf to associ-
ate a stream with an array buffer for output.
Constructors
Description Creates a stream and associates it with a char array for output.
Prototype ostrstream();
ostrstream(char* s, int n,
ios_base::openmode mode = ios_base::out);
#include <iostream>
#include <strstream>
int main()
{
ostrstream out;
out << "Ask the teacher anything you want to know" << ends;
istream inOut(out.rdbuf() );
har c;
while( inOut.get(c) ) cout.put(c);
return 0;
}
Result:
Ask the teacher anything you want to know
Destructor
Description Destroys an oststream object.
freeze
Description Freezes the dynamic allocation or destruction of a buffer.
int main()
{
ostrstream out;
out << "Metowerks " << 1234;
out << "the size of the array so far is "
<< out.pcount() << " characters \n";
return 0;
}
Result:
the size of the array so far is 14 characters
he final size of the array is 24 characters
Metowerks 1234 Software
pcount
Description Determines the number of bytes offset of the current stream position
to the beginning of the array.
Remarks The function pcount() is used to determine the offset of the array.
This may not equal to the number of characters inserted due to pos-
sible positioning operations.
int main()
{
ostrstream out;
out << "Metowerks " << 1234 << ends;
out << "the size of the array so far is "
<< out.pcount() << " characters \n";
return 0;
}
Result:
the size of the array so far is 15 characters
the final size of the array is 33 characters
Metowerks 1234
rdbuf
Description To retrieve a pointer to the streams buffer.
str
Description Returns a pointer to a character array.
Strstream Class
The class strstream is derived from streambuf to associate a
stream with an array buffer for output
Strstream Types
The strstream class typedefines a char_type, int_type,
pos_type and off_type, for stream positioning and storage.
Constructors
Description Creates a stream and associates it with a char array for input and
output.
Prototype strstream();
strstream(char* s, int n, ios_base::openmode mode =
ios_base::in|ios_base::out);
Destructor
Description Destroys a ststream object.
freeze
Description Freezes the dynamic allocation or destruction of a buffer.
pcount
Description Determines the number of bytes offset of the current stream position
to the beginning of the array.
Remarks The function pcount() is used to determine the offset of the array.
This may not equal to the number of characters inserted due to pos-
sible positioning operations.
rdbuf
Description Retrieves a pointer to the streams buffer
str
Description Returns a pointer to a character array.
Header <mutex.h>
Description The header <mutex.h> defines
Prototype
namespace std{
class null_mutex {
public:
inline null_mutex ();
inline ~null_mutex ();
inline int remove () const;
inline int acquire (int = 0) const;
inline int release () const;
};
class mutex {
private:
mutex_type _lock;
public:
inline mutex ();
inline ~mutex ();
inline int remove () const;
inline int acquire (int = 0) const;
inline int release () const;
bool try_lock ();
};
MUTEX _lock;
public:
inline mutex_arith ();
inline mutex_arith (TYPE i);
inline TYPE operator++ ();
inline TYPE operator++ (int);
inline TYPE operator+= (const TYPE i);
inline TYPE operator-- ();
inline TYPE operator-- (int);
inline TYPE operator-= (const TYPE i);
inline bool operator== (const TYPE i);
inline bool operator!= (const TYPE i);
inline bool operator>= (const TYPE i);
inline bool operator> (const TYPE i);
inline bool operator<= (const TYPE i);
inline bool operator< (const TYPE i);
inline void operator= (const TYPE i);
inline operator TYPE ();
};
class rw_mutex {
private:
mutex_type _lock;
public:
inline rw_mutex ();
inline ~rw_mutex ();
inline int remove () const;
inline int acquire (int) const;
inline int release () const;
bool try_rdlock ();
bool try_wrlock ();
};
private:
thread_id get_tid () const;
MUTEX lock;
thread_id thr_id;
mutex_arith<unsigned int,mutex> nest_count
};
null_mutex
Description The null mutex provides a method for defining during program de-
velopment a code sequence that will need to be protected against
simultaneous access by more than one thread. The null mutex pro-
vides no actual protection but serves as a marker that can be re-
placed by actual mutex objects later in the development process.
Constructor
Description Constructs a null_mutex object.
Destructor
Description Removes a null_mutex object.
remove
Description Explicit null_mutex destruction.
acquire
Description Acquire the _lock. (Wait if necessary).
Returns Null
release
Description Release the _lock.
Returns Null
mutex
Description This provides for the basic mutual exclusion mechanism.
Constructor
Description Initialize the mutex.
Destructor
Description Implicit mutex destruction.
remove
Description Explicit mutex destruction.
acquire
Description Acquire the _lock. (Wait if necessary).
release
Description Release the _lock.
try_lock
Description Attempt to lock the mutex, but don't wait.
mutex_block
Description This template provides the mutex mechanism for a complete block
of code.
Constructor
Description Implicit lock acquisition
Destructor
Description Implicit lock release
remove
Description Explicit lock release
Return _lock.remove().
release
Description Explicit lock release
acquire
Description Explicit lock acquisition
Return _lock.acquire(type).
mutex_arith
Description This template provides inline mutual exclusion for arithmetic oper-
ations that will protect against multiple thread access during the
evaluation of an expression with side effects.
TYPE _count;
MUTEX _lock;
public:
inline mutex_arith ();
inline mutex_arith (TYPE i);
inline TYPE operator++ ();
inline TYPE operator++ (int);
inline TYPE operator+= (const TYPE i);
inline TYPE operator-- ();
inline TYPE operator-- (int);
inline TYPE operator-= (const TYPE i);
inline bool operator== (const TYPE i);
inline bool operator!= (const TYPE i);
inline bool operator>= (const TYPE i);
inline bool operator> (const TYPE i);
inline bool operator<= (const TYPE i);
inline bool operator< (const TYPE i);
inline void operator= (const TYPE i);
inline operator TYPE ();
};
Constructors
Description Initialize the mutex_arith object.
Prefix operator++
Description Increment _count by unit.
Postfix operator++
Description Increment _count by unit.
operator+=
Description Increment _count by i.
Prefix operator--
Description Decrement _count by unit.
Postfix operator--
Description Decrement _count by unit.
operator-=
Description Decrement _count by i.
Return _count -= i;
operator==
Description Compare _count with i.
Return _count == i;
Remarks
operator!=
Description Compare _count with i.
Return _count != i;
operator>=
Description Check if _count >= i.
operator>
Description Check if _count > i.
operator<=
Description Check if _count <= i.
operator<
Description Check if _count < i.
operator=
Description Assign i to count_
operator TYPE
Description Return count_.
Return _count
rw_mutex
Description This template provides mutual exclusion for input and output oper-
ations.
Constructor
Description Initialize the readers/writer mutex.
Destructor
Description Implicit mutex destruction.
remove
Description Explicit rw_mutex destruction.
acquire
Description Acquire the _lock. Wait if necessary.
release
Description Release the _lock.
try_rdlock
Description Attempt to lock the mutex for reading, but don't wait.
try_wrlock
Description Attempt to lock the mutex for writing, but don't wait.
mutex_rec
Description This template provides mutual exclusion mechanism for protecting
against simultaneous access to a data record.
Constructor
Description Creates a mutex_rec class.
Prototype mutex_rec()
acquire
Description Acquire the _lock. Wait if necessary.
release
Description Release the _lock.
remove
Description Explicit mutex_rec destruction.
U W
uflow 517 werr 448
underflow 516 Wide-oriented Iostream Classes 47
basic_filebuf 620 width 464
basic_streambuf 594 win 447
strstreambuf 655 wlog 448
unget 549 wostream werr 448
unsetf 462 wostream wlog 448
uppercase 487 wout 447
Using the library 52 write 571
ws 554
V
vector X
Comparison Operations 208 xalloc 466
Constructors 206 xsgetn 516
Element Access Member Functions 208
Credits
writing lead: Ron Liechty
other writers: Portions copyright © 1995 by Modena
Software Inc.
engineering: Vicki Scott, Howard Hinnant and all
other Libraries team members
frontline warriors: MPTP testers
Guide to CodeWarrior Documentation
CodeWarrior documentation is modular, like the underlying tools. There are manuals
for the core tools, languages, libraries, and targets. The exact documentation provided
with any CodeWarrior product is tailored to the tools included with the product. Your
product will not have every manual listed here. However, you will probably have addi-
tional manuals (not listed here) for utilities or other software specific to your product.
Core Documentation
IDE User Guide How to use the CodeWarrior IDE
Debugger User Guide How to use the CodeWarrior debugger
CodeWarrior Core Tutorials Step-by-step introduction to IDE components
Language/Compiler Documentation
C Compilers Reference Information on the C/C++ front-end compiler
Pascal Compilers Reference Information on the Pascal front-end compiler
Error Reference Comprehensive list of compiler/linker error messages, with many fixes
Pascal Language Reference The Metrowerks implementation of ANS Pascal
Assembler Guide Stand-alone assembler syntax
Command-Line Tools Reference Command-line options for Mac OS and Be compilers
Plugin API Manual The CodeWarrior plugin compiler/linker API
Library Documentation
MSL C Reference Function reference for the Metrowerks ANSI standard C library
MSL C++ Reference Function reference for the Metrowerks ANSI standard C++ library
Pascal Library Reference Function reference for the Metrowerks ANS Pascal library
MFC Reference Reference for the Microsoft Foundation Classes for Win32
Win32 SDK Reference Microsoft’s Reference for the Win32 API
The PowerPlant Book Introductory guide to the Metrowerks application framework for Mac OS
PowerPlant Advanced Topics Advanced topics in PowerPlant programming for Mac OS
Targeting Manuals
Targeting BeOS How to use CodeWarrior to program for BeOS
Targeting Java VM How to use CodeWarrior to program for the Java Virtual Machine
Targeting Mac OS How to use CodeWarrior to program for Mac OS
Targeting MIPS How to use CodeWarrior to program for MIPS embedded processors
Targeting NEC V810/830 How to use CodeWarrior to program for NEC V810/830 processors
Targeting Net Yaroze How to use CodeWarrior to program for Net Yaroze game console
Targeting Nucleus How to use CodeWarrior to program for the Nucleus RTOS
Targeting OS-9 How to use CodeWarrior to program for the OS-9 RTOS
Targeting Palm OS How to use CodeWarrior to program for PalmPilot
Targeting PlayStation OS How to use CodeWarrior to program for the PlayStation game console
Targeting PowerPC Embedded Systems How to use CodeWarrior to program for PPC embedded processors
Targeting VxWorks How to use CodeWarrior to program for the VxWorks RTOS
Targeting Win32 How to use CodeWarrior to program for Windows