file:///D|/97/c++_1/LIBREF.
TXT
Standard C++ Library Reference Page 1 of 619
Visual C++
Standard C++ Library Reference
Standard C++ Library Contents
Standard C++ Library Overview
STL Conventions
Containers
Interesting home pages
Visual C++ Home The entire Visual C++ product.
MFC Reference The framework library for creating
Windows programs.
Run-Time Library Reference The standard C library.
Standard C++ Library
A C++ program can call on a large number of functions from the
Standard C++ library. These functions perform essential services
such as input and output. They also provide efficient
implementations of frequently used operations. Numerous function
and class definitions accompany these functions to help you to make
better use of the library. Most of the information about the
Standard C++ library can be found in the descriptions of the
Standard C++ headers that declare or define library entities for
the program.
Table of Contents
<algorithm> . <bitset> . <complex> . <deque> . <exception> .
<fstream> . <functional> . <iomanip> . <ios> . <iosfwd> .
<iostream> . <istream> . <iterator> . <limits> . <list> . <locale>
. <map> . <memory> .
<numeric> . <ostream> . <queue> . <set> .
<sstream> . <stack> . <stdexcept> . <streambuf> . <string> .
<strstream> . <utility> . <valarray> . <vector>
file:///D|/97/c++_1/LIBREF.TXT (1 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 2 of 619
<cassert> . <cctype> . <cerrno>. <cfloat> . <ciso646> . <climits> .
<clocale> . <
cmath> . <csetjmp> . <csignal> . <cstdarg> . <cstddef>
. <cstdio> . <cstdlib> . <cstring> . <ctime> . <cwchar>
. <iso646.h> . <wchar.h>
C++ Library Overview . . Files and Streams . STL Conventions .
Containers
Of the Standard C++ library headers listed below, 13 constitute the
Standard Template Library, or STL. These are indicated below with
the notation (STL):
<algorithm> -- (STL) for defining numerous templates that implement
useful algorithms
<bitset> -- for defining a template class that administers sets of
bits
<cassert> -- for enforcing assertions when functions execute
<cctype> -- for classifying characters
<cerrno> -- for testing error codes reported by library functions
<cfloat> -- for testing floating-point type properties
<ciso646> -- for programming in ISO 646 variant character sets
<climits> -- for testing integer type properties
<clocale> -- for adapting to different cultural conventions
<cmath> -- for computing common mathematical functions
<complex> -- for defining a template class that supports complex
arithmetic
<csetjmp> -- for executing nonlocal goto
<csignal> -- for controlling various exceptional conditions
<cstdarg> -- for accessing a varying number of arguments
<cstddef> -- for defining several useful types and macros
<cstdio> -- for performing input and output
<cstdlib> -- for performing a variety of operations
<cstring> -- for manipulating several kinds of strings
<ctime> -- for converting between various time and date formats
<cwchar> -- for manipulating wide streams and several kinds of
strings
<cwctype> -- for classifying wide characters
<deque> -- (STL) for defining a template class that implements a
deque container
<exception> -- for defining several functions that control
exception handling
<fstream> -- for defining several iostreams template classes that
manipulate external files
<functional> -- (STL) for defining several templates that help
construct predicates for the templates defined in <algorithm> and
<numeric>
<iomanip> -- for declaring several iostreams manipulators that take
an argument
<ios> -- for defining the template class that serves as the base
for many iostreams classes
<iosfwd> -- for declaring several iostreams template classes before
they are necessarily defined
<iostream> -- for declaring the iostreams objects that manipulate
the standard streams
<istream> -- for defining the template class that performs
file:///D|/97/c++_1/LIBREF.TXT (2 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 3 of 619
extractions
<iterator> -- (STL) for defining several templates that help define
and manipulate iterators
<limits> -- for testing numeric type properties
<list> -- (STL) for defining a template class that implements a
list container
<locale> -- for defining several classes and templates that control
locale-specific behavior, as in the iostreams classes
<map> -- (STL) for defining template classes that implement
associative containers
<memory> -- (STL) for defining several templates that allocate and
free storage for various container classes
<numeric> -- (STL) for defining several templates that implement
useful numeric functions
<ostream> -- for defining the template class that performs
insertions
<queue> -- (STL) for defining a template class that implements a
queue container
<set> -- (STL) for defining template classes that implement
associative containers with unique elements
<sstream> -- for defining several iostreams template classes that
manipulate string containers
<stack> -- (STL) for defining a template class that implements a
stack container
<stdexcept> -- for defining several classes useful for reporting
exceptions
<streambuf> -- for defining template classes that buffer iostreams
operations
<string> -- for defining a template class that implements a string
container
<strstream> -- for defining several iostreams classes that
manipulate in-memory character sequences
<utility> -- (STL) for defining several templates of general
utility
<valarray> -- for defining several classes and template classes
that support value-oriented arrays
<vector> -- (STL) for defining a template class that implements a
vector container
The Standard C++ library also includes the 18 headers from the
Standard C library, sometimes with small alterations. Most of the
functions in the header files below are documented in the Run-Time
Library Reference, so they are not discussed in this Standard C++
Library reference.
<assert.h> -- for enforcing assertions when functions execute
<ctype.h> -- for classifying characters
<errno.h> -- for testing error codes reported by library functions
<float.h> -- for testing floating-point type properties
<iso646.h> -- for programming in ISO 646 variant character sets
<limits.h> -- for testing integer type properties
<locale.h> -- for adapting to different cultural conventions
<math.h> -- for computing common mathematical functions
<setjmp.h> -- for executing nonlocal goto
<signal.h> -- for controlling various exceptional conditions
<stdarg.h> -- for accessing a varying number of arguments
<stddef.h> -- for defining several useful types and macros
file:///D|/97/c++_1/LIBREF.TXT (3 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 4 of 619
<stdio.h> -- for performing input and output
<stdlib.h> -- for performing a variety of operations
<string.h> -- for manipulating several kinds of strings
<time.h> -- for converting between various time and date formats
<wchar.h> -- for manipulating wide streams and several kinds of
strings
<wctype.h> -- for classifying wide characters
Other information on the Standard C++ library includes:
C++ Library Overview -- how to use the Standard C++ library
Files and Streams -- how to read and write data between the program
and files
STL Conventions -- how to read the descriptions of STL template
classes and functions
Containers -- how to use an arbitrary STL container template class
A few special conventions are introduced into this document
specifically for this particular implementation of the Standard C++
library. Because the draft C++ Standard is still changing, not all
implementations support all the features described here. Hence,
this implementation introduces macros, or alternative declarations,
where necessary to provide reasonable substitutes for the
capabilities required by the current draft C++ Standard.
C++ Library Overview
Using Standard C++ Headers | C++ Library Conventions | Iostreams
Conventions | Program Startup and Termination
All Standard C++ library entities are declared or defined in one or
more standard headers. To use a library entity in a program, write
an include directive that names the relevant standard header. The
full set of Standard C++ headers (along with the 18 additional
Standard C headers) constitutes a hosted implementation of Standard
C++: <algorithm>, <bitset>, <cassert>, <cctype>, <cerrno>,
<cfloat>, <ciso646>, <climits>, <clocale>, <cmath>, <complex>,
<csetjmp>, <csignal>, <cstdarg>, <cstddef>, <cstdio>, <cstdlib>,
<cstring>, <ctime>, <cwchar>, <cwctype>, <deque>, <exception>,
<fstream>, <functional>, <iomanip>, <ios>, <iosfwd>, <iostream>,
<istream>, <iterator> <limits>,
, <list>, <locale>, <map>, <memory>,
<numeric>, <ostream>, <queue>, <set>, <sstream>, <stack>,
<stdexcept>, <streambuf>, <string>, <strstream>, <utility>,
<valarray>, and <vector>.
A freestanding implementation of Standard C++ provides only a
subset of these headers: <cstddef>, <cstdlib> (declaring at least
the functions abort, atexit, and exit), <exception>, <limits>, and
<cstdarg>.
The Standard C++ headers have two broader subdivisions, iostreams
headers and STL headers.
Using Standard C++ Headers
file:///D|/97/c++_1/LIBREF.TXT (4 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 5 of 619
You include the contents of a standard header by naming it in an
include directive, as in:
#include <iostream> /* include I/O facilities */
You can include the standard headers in any order, a standard
header more than once, or two or more standard headers that define
the same macro or the same type. Do not include a standard header
within a declaration. Do not define macros that have the same names
as keywords before you include a standard header.
A Standard C++ header includes any other Standard C++ headers it
needs to define needed types. (Always include explicitly any
Standard C++ headers needed in a translation unit, however, lest
you guess wrong about its actual dependencies.) A Standard C header
never includes another standard header. A standard header declares
or defines only the entities described for it in this document.
Every function in the library is declared in a standard header.
Unlike in Standard C, the standard header never provides a masking
macro, with the same name as the function, that masks the function
declaration and achieves the same effect.
If an implementation supports namespaces, all names in the Standard
C++ headers are defined in the std namespace. You refer to the name
cin, for example, as std::cin. Alternatively, you can write the
declaration:
using namespace std;
which promotes all library names into the current namespace. If you
include one of the C standard headers, such as <stdio.h>, the
individual names declared or defined in that header are promoted
for you. Note that macro names are not subject to the rules for
nesting namespaces.
C++ Library Conventions
The Standard C++ library obeys much the same conventions as the
Standard C library, plus a few more outlined here.
Except for macro names, which obey no scoping rules, all names in
the Standard C++ library are declared in the std namespace.
Including a Standard C++ header does not introduce any library
names into the current namespace. You must, for example, refer to
the standard input stream cin as std::cin, even after including the
header <iostream> that declares it. Alternatively, you can
incorporate all members of the std namespace into the current
namespace by writing:
using namespace std;
immediately after all include directives that name the standard
headers. Note that the Standard C headers behave mostly as if they
include no namespace declarations. If you include, for example,
<cstdlib>, you call std::abort() to cause abnormal termination, but
file:///D|/97/c++_1/LIBREF.TXT (5 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 6 of 619
if you include <stdlib.h>, you call abort().
An implementation has certain latitude in how it declares types and
functions in the Standard C++ library:
lNames of functions in the Standard C library may have either
extern "C++" or extern "C" linkage. Include the appropriate
Standard C header rather than declare a library entity inline.
lA member function name in a library class may have additional
function signatures beyond those listed in this document. You
can be sure that a function call described here behaves as
expected, but you cannot reliably take the address of a library
member function. (The type may not be what you expect.)
lA library class may have undocumented (nonvirtual) base
classes. A class documented as derived from another class may,
in fact, be derived from that class through other undocumented
classes.
lA type defined as a synonym for some integer type may be the
same as one of several different integer types.
lA library function that has no exception specification can
throw an arbitrary exception, unless its definition clearly
restricts such a possibility.
On the other hand, there are some restrictions you can count on:
lThe Standard C library uses no masking macros. Only specific
function signatures are reserved, not the names of the
functions themselves.
lA library function name outside a class will not have
additional, undocumented function signatures. You can reliably
take its address.
lBase classes and member functions described as virtual are
assuredly virtual, while those described as nonvirtual are
assuredly nonvirtual.
lTwo types defined by the Standard C++ library are always
different unless this document explicitly suggests otherwise.
lFunctions supplied by the library, including the default
versions of replaceable functions, can throw at most those
exceptions listed in any exception specification. (Functions in
the Standard C library may propagate an exception, as when
qsort calls a comparison function that throws an exception, but
they do not otherwise throw exceptions.)
Iostreams Conventions
The iostreams headers support conversions between text and encoded
forms, and input and output to external files: <fstream>,
<iomanip>, <ios>, <iosfwd>, <iostream>, <istream>, <ostream>,
<sstream>, <streambuf>, and <strstream>.
The simplest use of iostreams requires only that you include the
header <iostream>. You can then extract values from cin, to read
the standard input. The rules for doing so are outlined in the
description of the class basic_istream. You can also insert values
to cout, to write the standard output. The rules for doing so are
outlined in the description of the class basic_ostream. Format
control common to both extractors and insertors is managed by the
file:///D|/97/c++_1/LIBREF.TXT (6 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 7 of 619
class basic_ios. Manipulating this format information in the guise
of extracting and inserting objects is the province of several
manipulators.
You can perform the same iostreams operations on files that you
open by name, using the classes declared in <fstream>. To convert
between iostreams and objects of class basic_string, use the
classes declared in <sstream>. And to do the same with C strings,
use the classes declared in <strstream>.
The remaining headers provide support services, typically of direct
interest to only the most advanced users of the iostreams classes.
C++ Program Startup and Termination
A C++ program performs the same operations as does a C program at
program startup and at program termination, plus a few more
outlined here.
Before the target environment calls the function main, and after it
stores any constant initial values you specify in all objects that
have static duration, the program executes any remaining
constructors for such static objects. The order of execution is not
specified between translation units, but you can nevertheless
assume that four iostreams objects are properly initialized for use
by these static constructors. These control several text streams:
lcin -- for standard input
lcout -- for standard output
lcerr -- for unbuffered standard error output
lclog -- for buffered standard error output
During program termination, you can also use these objects within
the destructors called for static objects.
As with C, returning from main or calling exit calls all functions
registered with atexit in reverse order of registry. An exception
thrown from such a registered function calls terminate().
STL Conventions
Iterator Conventions | Algorithm Conventions
The Standard Template Library, or STL, establishes uniform
standards for the application of iterators to STL containers or
other sequences that you define, by STL algorithms or other
functions that you define. This document summarizes many of the
conventions used widely throughout the Standard Template Library.
Iterator Conventions
The STL facilities make widespread use of iterators, to mediate
between the various algorithms and the sequences upon which they
act. For brevity in the remainder of this document, the name of an
iterator type (or its prefix) indicates the category of iterators
file:///D|/97/c++_1/LIBREF.TXT (7 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 8 of 619
required for that type. In order of increasing power, the
categories are summarized here as:
lOutIt -- An output iterator X can only have a value V stored
indirectly on it, after which it must be incremented before the
next store, as in (*X++ = V), (*X = V, ++X), or (*X = V, X++).
lInIt -- An input iterator X can represent a singular value that
indicates end-of-sequence. If such an iterator does not compare
equal to its end-of-sequence value, it can have a value V
accessed indirectly on it any number of times, as in (V = *X).
To progress to the next value, or end-of-sequence, you
increment it, as in ++X, X++, or (V = *X++). Once you increment
any copy of an input iterator, none of the other copies can
safely be compared, dereferenced, or incremented.
lFwdIt -- A forward iterator X can take the place of an output
iterator (for writing) or an input iterator (for reading). You
can, however, read (via V = *X) what you just wrote (via *X =
V) through a forward iterator. And you can make multiple copies
of a forward iterator, each of which can be dereferenced and
incremented independently.
lBidIt -- A bidirectional iterator X can take the place of a
forward iterator. You can, however, also decrement a
bidirectional iterator, as in --X, X--, or (V = *X--).
lRanIt -- A random-access iterator X can take the place of a
bidirectional iterator. You can also perform much the same
integer arithmetic on a random-access iterator that you can on
an object pointer. For N, an integer object, you can write x
[N], x + N, x - N, and N + X.
Note that an object pointer can take the place of a random-access
iterator, or any other iterator for that matter.
The hierarchy of iterator categories can be summarized by showing
three sequences. For write-only access to a sequence, you can use
any of:
output iterator ->
forward iterator ->
bidirectional iterator ->
random-access iterator
The right arrow means "can be replaced by." So any algorithm that
calls for an output iterator should work well with a forward
iterator, for example, but not the other way around.
For read-only access to a sequence, you can use any of:
input iterator ->
forward iterator ->
bidirectional iterator ->
random-access iterator
An input iterator is the weakest of all categories, in this case.
Finally, for read/write access to a sequence, you can use any of:
forward iterator ->
file:///D|/97/c++_1/LIBREF.TXT (8 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 9 of 619
bidirectional iterator ->
random-access iterator
Remember that an object pointer can always serve as a random-access
iterator. Therefore, it can serve as any category of iterator, as
long as it supports the proper read/write access to the sequence it
designates.
This "algebra" of iterators is fundamental to practically
everything else in the Standard Template Library. It is important
to understand the capabilities, and limitations, of each iterator
category to see how iterators are used by containers and algorithms
in STL.
Algorithm Conventions
The descriptions of the algorithm template functions employ several
shorthand phrases:
lThe phrase "in the range [A, B)" means the sequence of zero or
more discrete values beginning with A up to but not including
B. A range is valid only if B is reachable from A: You can
store A in an object N (N = A), increment the object zero or
more times (++N), and have the object compare equal to B after
a finite number of increments (N == B).
lThe phrase "each N in the range [A, B)" means that N begins
with the value A and is incremented zero or more times until it
equals the value B. The case N == B is not in the range.
lThe phrase "the lowest value of N in the range [A, B) such that
X" means that the condition X is determined for each N in the
range [A, B) until the condition X is met.
lThe phrase "the highest value of N in the range [A, B) such
that X" usually means that X is determined for each N in the
range [A, B). The function stores in K a copy of N each time
the condition X is met. If any such store occurs, the function
replaces the final value of N (which equals B) with the value
of K. For a bidirectional or random-access iterator, however,
it can also mean that N begins with the highest value in the
range and is decremented over the range until the condition X
is met.
lExpressions such as X - Y, where X and Y can be iterators other
than random-access iterators, are intended in the mathematical
sense. The function does not necessarily evaluate operator- if
it must determine such a value. The same is true for
expressions such as X + N and X - N, where N is an integer
type.
Several algorithms use a predicate that must impose a strict weak
ordering on pairs of elements from a sequence. For the predicate pr
(X, Y):
l"strict" means that pr(X, X) is false
l"weak" means that X and Y have an equivalent ordering if !pr(X,
Y) && !pr(Y, X) (X == Y need not be defined)
l"ordering" means that pr(X, Y) && pr(Y, Z) implies pr(X, Z)
Some of these algorithms implicitly use the predicate X < Y. Other
file:///D|/97/c++_1/LIBREF.TXT (9 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 10 of 619
predicates that typically satisfy the "strict weak ordering"
requirement are X > Y, less(X, Y), and greater(X, Y). Note,
however, that predicates such as X <= Y and X >= Y do not satisfy
this requirement.
A sequence of elements designated by iterators in the range [first,
last) is "a sequence ordered by operator<" if, for each N in the
range [0, last - first) and for each M in the range (N, last -
first) the predicate !(*(first + M) < *(first + N)) is true. (Note
that the elements are sorted in ascending order.) The predicate
operator<, or any replacement for it, must not alter either of its
operands. Moreover, it must impose a strict weak ordering on the
operands it compares.
A sequence of elements designated by iterators in the range [first,
last) is "a heap ordered by operator<" if, for each N in the range
[1, last - first) the predicate !(*first < *(first + N)) is true.
(The first element is the largest.) Its internal structure is
otherwise known only to the template functions make_heap, pop_heap,
and push_heap. As with an ordered sequence, the predicate function
operator<, or any replacement for it, must not alter either of its
operands, and it must impose a strict weak ordering on the operands
it compares.
Files and Streams
Text and Binary Streams | Byte and Wide Streams | Controlling
Streams | Stream States
A program communicates with the target environment by reading and
writing files (ordered sequences of bytes). A file can be, for
example, a data set that you can read and write repeatedly (such as
a disk file), a stream of bytes generated by a program (such as a
pipeline), or a stream of bytes received from or sent to a
peripheral device (such as the keyboard or display). The latter two
are interactive files. Files are typically the principal means by
which to interact with a program.
You manipulate all these kinds of files in much the same way -- by
calling library functions. You include the standard header
<stdio.h> to declare most of these functions.
Before you can perform many of the operations on a file, the file
must be opened. Opening a file associates it with a stream, a data
structure within the Standard C library that glosses over many
differences among files of various kinds. The library maintains the
state of each stream in an object of type FILE.
The target environment opens three files prior to program startup.
You can open a file by calling the library function fopen with two
arguments. The first argument is a filename, a multibyte string
that the target environment uses to identify which file you want to
read or write. The second argument is a C string that specifies:
lWhether you intend to read data from the file or write data to
it, or both.
lWhether you intend to generate new contents for the file (or
file:///D|/97/c++_1/LIBREF.TXT (10 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 11 of 619
create a file if it did not previously exist) or leave the
existing contents in place.
lWhether writes to a file can alter existing contents or should
only append bytes at the end of the file.
lWhether you want to manipulate a text stream or a binary
stream.
Once the file is successfully opened, you can determine whether the
stream is byte-oriented (a byte stream) or wide-oriented (a wide
stream). Wide-oriented streams are supported only with Amendment 1.
A stream is initially unbound. Calling certain functions to operate
on the stream makes it byte oriented, while certain other functions
make it wide oriented. Once established, a stream maintains its
orientation until it is closed by a call to fclose or freopen.
Text and Binary Streams
A text stream consists of one or more lines of text that can be
written to a text-oriented display so that they can be read. When
reading from a text stream, the program reads an NL (newline) at the
end of each line. When writing to a text stream, the program writes
an NL to signal the end of a line. To match differing conventions
among target environments for representing text in files, the
library functions can alter the number and representations of
characters transmitted between the program and a text stream.
Thus, positioning within a text stream is limited. You can obtain
the current file-position indicator by calling fgetpos or ftell.
You can place a text stream at a position obtained this way, or at
the beginning or end of the stream, by calling fsetpos or fseek.
Any other change of position might well be unsupported.
For maximum portability, the program should not write:
lEmpty files
lSpace characters at the end of a
lPartial lines (by omitting the NL at the end of a file)
lCharacters other than the printable characters, NL, and
(horizontal tab)
If you follow these rules, the sequence of characters you read from
a text stream (either as byte or multibyte characters) will match
the sequence of characters you wrote to the text stream when you
created the file. Otherwise, the library functions can remove a
file you create if the file is empty when you close it. Or they can
alter or delete characters you write to the file.
A binary stream consists of one or more bytes of arbitrary
information. You can write the value stored in an arbitrary object
to a (byte-oriented) binary stream and read exactly what was stored
in the object when you wrote it. The library functions do not alter
the bytes you transmit between the program and a binary stream.
They can, however, append an arbitrary number of null bytes to the
file that you write with a binary stream. The program must deal
with these additional null bytes at the end of any binary stream.
Thus, positioning within a binary stream is well defined, except
file:///D|/97/c++_1/LIBREF.TXT (11 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 12 of 619
for positioning relative to the end of the stream. You can obtain
and alter the current file-position indicator the same as for a
text stream. Moreover, the offsets used by ftell and fseek count
bytes from the beginning of the stream (which is byte zero), so
integer arithmetic on these offsets yields predictable results.
Byte and Wide Streams
A byte stream treats a file as a sequence of bytes. Within the
program, the stream looks like the same sequence of bytes, except
for the possible alterations described above.
By contrast, a wide stream treats a file as a sequence of
generalized multibyte characters, which can have a broad range of
encoding rules. (Text and binary files are still read and written
as described above.) Within the program, the stream looks like the
corresponding sequence of wide characters. Conversions between the
two representations occur within the Standard C library. The
conversion rules can, in principle, be altered by a call to
setlocale that changes the category LC_CTYPE. Each wide stream
determines its conversion rules at the time it becomes wide-
oriented, and retains these rules even if the category LC_CTYPE
subsequently changes.
Positioning within a wide stream is subject to the same limitations
as for text streams. Moreover, the file-position indicator may well
have to deal with a state-dependent encoding. Typically, it
includes both a byte offset within the stream and an object of type
mbstate_t. Thus, the only reliable way to obtain a file position
within a wide stream is by calling fgetpos, and the only reliable
way to restore a position obtained this way is by calling fsetpos.
Controlling Streams
The fopen function returns the address of an object of type FILE.
You use this address as the stream argument to several library
functions to perform various operations on an open file. For a byte
stream, all input takes place as if each character is read by
calling fgetc, and all output takes place as if each character is
written by calling fputc. For a wide stream (with Amendment 1), all
input takes place as if each character is read by calling fgetwc,
and all output takes place as if each character is written by
calling fputwc.
You can close a file by calling fclose, after which the address of
the FILE object is invalid.
A FILE object stores the state of a stream, including:
lAn error indicator -- set nonzero by a function that encounters
a read or write error
lAn end-of-file indicator -- set nonzero by a function that
encounters the end of the file while reading
lA file-position indicator -- specifies the next byte in the
stream to read or write, if the file can support positioning
requests
lA stream state -- specifies whether the stream will accept
file:///D|/97/c++_1/LIBREF.TXT (12 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 13 of 619
reads and/or writes and, with Amendment 1, whether the stream
is unbound, byte-oriented, or wide-oriented
lA conversion state -- remembers the state of any partly
assembled or generated generalized multibyte character, as well
as any shift state for the sequence of bytes in the file
lA file buffer -- specifies the address and size of an array
object that library functions can use to improve the
performance of read and write operations to the stream
Do not alter any value stored in a FILE object or in a file buffer
that you specify for use with that object. You cannot copy a FILE
object and portably use the address of the copy as a stream
argument to a library function.
Stream States
The valid states, and state transitions, for a stream are:
Each of the circles denotes a stable state. Each of the lines
denotes a transition that can occur as the result of a function
call that operates on the stream. Five groups of functions can
cause state transitions.
Functions in the first three groups are declared in <stdio.h>:
lThe byte read functions fgetc
-- , fgets, fread, fscanf, getc,
getchar, gets, scanf, and ungetc
lThe byte write functions -- fprintf, fputc, fputs, fwrite,
printf, putc, putchar, puts, vfprintf, and vprintf
lThe position functions -- fflush, fseek, fsetpos, and rewind
Functions in the remaining two groups are declared in <wchar.h>:
lThe wide read functions -- fgetwc, fgetws, fwscanf, getwc,
getwchar, ungetwc, and wscanf,
lThe wide write functions -- fwprintf, fputwc, fputws, putwc,
putwchar, vfwprintf, vwprintf, and wprintf
For the stream s, the call fwide(s, 0) is always valid and never
causes a change of state. Any other call to fwide, or to any of the
five groups of functions described above, causes the state
transition shown in the state diagram. If no such transition is
shown, the function call is invalid.
The state diagram shows how to establish the orientation of a
stream:
lThe call fwide(s, -1), or to a byte read or byte write
function, establishes the stream as byte-oriented.
lThe call fwide(s, 1), or to a wide read or wide write function,
establishes the stream as wide-oriented.
The state diagram also shows that you must call one of the position
functions between most write and read operations:
file:///D|/97/c++_1/LIBREF.TXT (13 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 14 of 619
lYou cannot call a read function if the last operation on the
stream was a write.
lYou cannot call a write function if the last operation on the
stream was a read, unless that read operation set the end-of-
file indicator.
Finally, the state diagram shows that a position operation never
decreases the number of valid function calls that can follow.
Containers
namespace std {
template<class T, class A>
class Cont;
// TEMPLATE FUNCTIONS
template<class T, class A>
bool operator==(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
bool operator!=(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
bool operator<(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
bool operator>(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
bool operator<=(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
bool operator>=(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
template<class T, class A>
void swap(
const Cont<T, A>& lhs,
const Cont<T, A>& rhs);
};
A container is an STL template class that manages a sequence of
elements. Such elements can be of any object type that supplies a
default constructor, a destructor, and an assignment operator. This
document describes the properties required of all such containers,
in terms of a generic template class Cont. An actual container
template class may have additional template parameters. It will
certainly have additional member functions.
The STL template container classes are:
deque
file:///D|/97/c++_1/LIBREF.TXT (14 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 15 of 619
list
map
multimap
multiset
set
vector
(The Standard C++ library template class basic_string also meets
the requirements for a template container class.)
Cont
allocator_type . begin . clear . const_iterator . const_reference .
const_reverse_iterator . difference_type .
empty . end . erase .
get_allocator . iterator . max_size . rbegin . reference . rend .
reverse_iterator .
size . size_type . swap . value_type
template<class T, class A = allocator<T> >
class Cont {
public:
typedef A allocator_type;
typedef T0 size_type;
typedef T1 difference_type;
typedef T2 reference;
typedef T3 const_reference;
typedef T4 value_type;
typedef T5 iterator;
typedef T6 const_iterator;
typedef T7 reverse_iterator;
typedef T8 const_reverse_iterator;
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 size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
void swap(Cont x);
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements, typically of type T. The sequence is
stored in different ways, depending on the actual container.
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
file:///D|/97/c++_1/LIBREF.TXT (15 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 16 of 619
of template class allocator. Note that allocator is not copied when
the object is assigned. All constructors store an allocator
argument (or, for the copy constructor, x.get_allocator()) in
allocator and initialize the controlled sequence.
Cont::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
Cont::begin
const_iterator begin() const;
iterator begin();
The member function returns an iterator that points at the first
element of the sequence (or just beyond the end of an empty
sequence).
Cont::clear
void clear() const;
The member function calls erase( begin(), end()).
Cont::const_iterator
typedef T6 const_iterator;
The type describes an object that can serve as a constant iterator
for the controlled sequence. It is described here as a synonym for
the unspecified type T6.
Cont::const_reference
typedef T3 const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence. It is described here as a
synonym for the unspecified type T3 (typically A::const_reference).
Cont::const_reverse_iterator
typedef T8 const_reverse_iterator;
The type describes an object that can serve as a constant reverse
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T8 (typically reverse_iterator or
reverse_bidirectional_iterator).
Cont::difference_type
typedef T1 difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
file:///D|/97/c++_1/LIBREF.TXT (16 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 17 of 619
controlled sequence. It is described here as a synonym for the
unspecified type T1 (typically A::difference_type).
Cont::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
Cont::end
const_iterator end() const;
iterator end();
The member function returns an iterator that points just beyond the
end of the sequence.
Cont::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements of the controlled sequence in the range [first, last).
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
Cont::get_allocator
A get_allocator() const;
The member function returns allocator.
Cont::iterator
typedef T5 iterator;
The type describes an object that can serve as an iterator for the
controlled sequence. It is described here as a synonym for the
unspecified type T5.
Cont::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
Cont::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse iterator that points just
beyond the end of the controlled sequence. Hence, it designates the
beginning of the reverse sequence.
file:///D|/97/c++_1/LIBREF.TXT (17 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 18 of 619
Cont::reference
typedef T2 reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence. It is described here as a
synonym for the unspecified type T2 (typically A::reference).
Cont::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse iterator that points at the
first element of the sequence (or just beyond the end of an empty
sequence). Hence, it designates the end of the reverse sequence.
Cont::reverse_iterator
typedef T7 reverse_iterator;
The type describes an object that can serve as a reverse iterator
for the controlled sequence. It is described here as a synonym for
the unspecified type T7 (typically reverse_iterator or
reverse_bidirectional_iterator).
The required pointer type is described here as the unspecified type
T7 (typically A::pointer).
Cont::size
size_type size() const;
The member function returns the length of the controlled sequence.
Cont::size_type
typedef T0 size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence. It is described here as a
synonym for the unspecified type T0 (typically A::size_type).
Cont::swap
void swap(Cont& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
Cont::value_type
typedef T4 value_type;
file:///D|/97/c++_1/LIBREF.TXT (18 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 19 of 619
The type is a synonym for the template parameter T. It is described
here as a synonym for the unspecified type T4 (typically
A::value_type).
operator!=
template<class T, class A>
bool operator!=(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class T, class A>
bool operator==(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function overloads operator== to compare two objects
of template class Cont. The function returns lhs.size() == rhs.size
() && equal(lhs. begin(), lhs. end(), rhs.begin()).
operator<
template<class T, class A>
bool operator<(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function overloads operator< to compare two objects of
template class Cont. The function returns lexicographical_compare
(lhs. begin(), lhs. end(), rhs.begin(), rhs.end()).
operator<=
template<class T, class A>
bool operator<=(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class A>
bool operator>(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class A>
file:///D|/97/c++_1/LIBREF.TXT (19 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 20 of 619
bool operator>=(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function returns !(lhs < rhs).
swap
template<class T, class A>
void swap(
const Cont <T, A>& lhs,
const Cont <T, A>& rhs);
The template function executes lhs.swap(rhs).
<algorithm>
adjacent_find . binary_search . copy . copy_backward . count .
count_if . equal . equal_range . fill . fill_n . find . find_end .
find_first_of . find_if .
for_each . generate . generate_n .
includes . inplace_merge . iter_swap . lexicographical_compare .
lower_bound . make_heap . max . max_element . merge . min .
min_element . mismatch . next_permutation . nth_element .
partial_sort . partial_sort_copy . partition . pop_heap .
prev_permutation . push_heap . random_shuffle . remove .
remove_copy . remove_copy_if .
remove_if . replace . replace_copy .
replace_copy_if . .
replace_if reverse . reverse_copy . rotate .
rotate_copy . search . search_n . ; set_difference .
set_intersection . set_symmetric_difference . set_union . sort .
sort_heap . .
stable_partition stable_sort . swap . swap_ranges .
transform . unique . unique_copy . upper_bound
namespace std {
template<class InIt, class Fun>
Fun for_each(InIt first, InIt last, Fun f);
template<class InIt, class T>
InIt find(InIt first, InIt last, const T& val);
template<class InIt, class Pred>
InIt find_if(InIt first, InIt last, Pred pr);
template<class FwdIt1, class FwdIt2>
FwdIt1 find_end(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 find_end(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
template<class FwdIt1, class FwdIt2>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
template<class FwdIt>
FwdIt adjacent_find(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt adjacent_find(FwdIt first, FwdIt last, Pred pr);
size_t count(InIt first, InIt last,
file:///D|/97/c++_1/LIBREF.TXT (20 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
const T& val, Dist& n);
file:///D|/97/c++_1/LIBREF.TXT (21 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 21 of 619
template<class InIt, class Pred, class Dist>
size_t count_if(InIt first, InIt last,
Pred pr);
template<class InIt1, class InIt2>
pair<InIt1, InIt2> mismatch(InIt1 first, InIt1 last, InIt2 x);
template<class InIt1, class InIt2, class Pred>
pair<InIt1, InIt2> mismatch(InIt1 first, InIt1 last,
InIt2 x, Pred pr);
template<class InIt1, class InIt2>
bool equal(InIt1 first, InIt1 last, InIt2 x);
template<class InIt1, class InIt2, class Pred>
bool equal(InIt1 first, InIt1 last, InIt2 x, Pred pr);
template<class FwdIt1, class FwdIt2>
FwdIt1 search(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 search(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
template<class FwdIt, class Dist, class T>
FwdIt search_n(FwdIt first, FwdIt last,
Dist n, const T& val);
template<class FwdIt, class Dist, class T, class Pred>
FwdIt search_n(FwdIt first, FwdIt last,
Dist n, const T& val, Pred pr);
template<class InIt, class OutIt>
OutIt copy(InIt first, InIt last, OutIt x);
template<class BidIt1, class BidIt2>
BidIt2 copy_backward(BidIt1 first, BidIt1 last, BidIt2 x);
template<class T>
void swap(T& x, T& y);
template<class FwdIt1, class FwdIt2>
FwdIt2 swap_ranges(FwdIt1 first, FwdIt1 last, FwdIt2 x);
template<class FwdIt1, class FwdIt2>
void iter_swap(FwdIt1 x, FwdIt2 y);
template<class InIt, class OutIt, class Unop>
OutIt transform(InIt first, InIt last, OutIt x, Unop uop);
template<class InIt1, class InIt2, class OutIt, class Binop>
OutIt transform(InIt1 first1, InIt1 last1, InIt2 first2,
OutIt x, Binop bop);
template<class FwdIt, class T>
void replace(FwdIt first, FwdIt last,
const T& vold, const T& vnew);
template<class FwdIt, class Pred, class T>
void replace_if(FwdIt first, FwdIt last,
Pred pr, const T& val);
template<class InIt, class OutIt, class T>
OutIt replace_copy(InIt first, InIt last, OutIt x,
const T& vold, const T& vnew);
template<class InIt, class OutIt, class Pred, class T>
OutIt replace_copy_if(InIt first, InIt last, OutIt x,
Pred pr, const T& val);
template<class FwdIt, class T>
void fill(FwdIt first, FwdIt last, const T& x);
template<class OutIt, class Size, class T>
void fill_n(OutIt first, Size n, const T& x);
template<class FwdIt, class Gen>
void generate(FwdIt first, FwdIt last, Gen g);
file:///D|/97/c++_1/LIBREF.TXT (22 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 22 of 619
template<class OutIt, class Pred, class Gen>
void generate_n(OutIt first, Dist n, Gen g);
template<class FwdIt, class T>
FwdIt remove(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class Pred>
FwdIt remove_if(FwdIt first, FwdIt last, Pred pr);
template<class InIt, class OutIt, class T>
OutIt remove_copy(InIt first, InIt last, OutIt x, const T& val);
template<class InIt, class OutIt, class Pred>
OutIt remove_copy_if(InIt first, InIt last, OutIt x, Pred pr);
template<class FwdIt>
FwdIt unique(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt unique(FwdIt first, FwdIt last, Pred pr);
template<class InIt, class OutIt>
OutIt unique_copy(InIt first, InIt last, OutIt x);
template<class InIt, class OutIt, class Pred>
OutIt unique_copy(InIt first, InIt last, OutIt x, Pred pr);
template<class BidIt>
void reverse(BidIt first, BidIt last);
template<class BidIt, class OutIt>
OutIt reverse_copy(BidIt first, BidIt last, OutIt x);
template<class FwdIt>
void rotate(FwdIt first, FwdIt middle, FwdIt last);
template<class FwdIt, class OutIt>
OutIt rotate_copy(FwdIt first, FwdIt middle, FwdIt last, OutIt x
template<class RanIt>
void random_shuffle(RanIt first, RanIt last);
template<class RanIt, class Fun>
void random_shuffle(RanIt first, RanIt last, Fun& f);
template<class BidIt, class Pred>
BidIt partition(BidIt first, BidIt last, Pred pr);
template<class FwdIt, class Pred>
FwdIt stable_partition(FwdIt first, FwdIt last, Pred pr);
template<class RanIt>
void sort(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr);
template<class BidIt>
void stable_sort(BidIt first, BidIt last);
template<class BidIt, class Pred>
void stable_sort(BidIt first, BidIt last, Pred pr);
template<class RanIt>
void partial_sort(RanIt first, RanIt middle, RanIt last);
template<class RanIt, class Pred>
void partial_sort(RanIt first, RanIt middle, RanIt last, Pred pr
template<class InIt, class RanIt>
RanIt partial_sort_copy(InIt first1, InIt last1,
RanIt first2, RanIt last2);
template<class InIt, class RanIt, class Pred>
RanIt partial_sort_copy(InIt first1, InIt last1,
RanIt first2, RanIt last2, Pred pr);
template<class RanIt>
void nth_element(RanIt first, RanIt nth, RanIt last);
template<class RanIt, class Pred>
void nth_element(RanIt first, RanIt nth, RanIt last, Pred pr);
template<class FwdIt, class T>
file:///D|/97/c++_1/LIBREF.TXT (23 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 23 of 619
FwdIt lower_bound(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
FwdIt lower_bound(FwdIt first, FwdIt last, const T& val, Pred pr
template<class FwdIt, class T>
FwdIt upper_bound(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
FwdIt upper_bound(FwdIt first, FwdIt last, const T& val, Pred pr
template<class FwdIt, class T>
pair<FwdIt, FwdIt> equal_range(FwdIt first, FwdIt last,
const T& val);
template<class FwdIt, class T, class Pred>
pair<FwdIt, FwdIt> equal_range(FwdIt first, FwdIt last,
const T& val, Pred pr);
template<class FwdIt, class T>
bool binary_search(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
bool binary_search(FwdIt first, FwdIt last, const T& val,
Pred pr);
template<class InIt1, class InIt2, class OutIt>
OutIt merge(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt merge(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
template<class BidIt>
void inplace_merge(BidIt first, BidIt middle, BidIt last);
template<class BidIt, class Pred>
void inplace_merge(BidIt first, BidIt middle, BidIt last, Pred p
template<class InIt1, class InIt2>
bool includes(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2);
template<class InIt1, class InIt2, class Pred>
bool includes(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, Pred pr);
template<class InIt1, class InIt2, class OutIt>
OutIt set_union(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_union(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
template<class InIt1, class InIt2, class OutIt>
OutIt set_intersection(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_intersection(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
template<class InIt1, class InIt2, class OutIt>
OutIt set_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
template<class InIt1, class InIt2, class OutIt>
OutIt set_symmetric_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_symmetric_difference(InIt1 first1, InIt1 last1,
file:///D|/97/c++_1/LIBREF.TXT (24 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 24 of 619
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
template<class RanIt>
void push_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void push_heap(RanIt first, RanIt last, Pred pr);
template<class RanIt>
void pop_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void pop_heap(RanIt first, RanIt last, Pred pr);
template<class RanIt>
void make_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void make_heap(RanIt first, RanIt last, Pred pr);
template<class RanIt>
void sort_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort_heap(RanIt first, RanIt last, Pred pr);
template<class T>
const T& max(const T& x, const T& y);
template<class T, class Pred>
const T& max(const T& x, const T& y, Pred pr);
template<class T>
const T& min(const T& x, const T& y);
template<class T, class Pred>
const T& min(const T& x, const T& y, Pred pr);
template<class FwdIt>
FwdIt max_element(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt max_element(FwdIt first, FwdIt last, Pred pr);
template<class FwdIt>
FwdIt min_element(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt min_element(FwdIt first, FwdIt last, Pred pr);
template<class InIt1, class InIt2>
bool lexicographical_compare(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2);
template<class InIt1, class InIt2, class Pred>
bool lexicographical_compare(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, Pred pr);
template<class BidIt>
bool next_permutation(BidIt first, BidIt last);
template<class BidIt, class Pred>
bool next_permutation(BidIt first, BidIt last, Pred pr);
template<class BidIt>
bool prev_permutation(BidIt first, BidIt last);
template<class BidIt, class Pred>
bool prev_permutation(BidIt first, BidIt last, Pred pr);
};
Include the STL standard header <algorithm> to define numerous
template functions that perform useful algorithms. The descriptions
that follow make extensive use of common template parameter names
(or prefixes) to indicate the least powerful category of iterator
permitted as an actual argument type:
lOutIt -- to indicate an output iterator
lInIt -- to indicate an input iterator
file:///D|/97/c++_1/LIBREF.TXT (25 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 25 of 619
lFwdIt -- to indicate a forward iterator
lBidIt -- to indicate a bidirectional iterator
lRanIt -- to indicate a random-access iterator
The descriptions of these templates employ a number of conventions
common to all algorithms.
adjacent_find
template<class FwdIt>
FwdIt adjacent_find(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt adjacent_find(FwdIt first, FwdIt last, Pred pr);
The first template function determines the lowest N in the range
[0, last - first) for which N + 1 != last - first and the predicate
*(first + N) == *(first + N + 1) is true. It then returns first +
N. If no such value exists, the function returns last. It evaluates
the predicate exactly N + 1 times.
The second template function behaves the same, except that the
predicate is pr(*(first + N), *(first + N + 1)).
Sample programs: adjacent_find and adjacent_find (predicate
version).
binary_search
template<class FwdIt, class T>
bool binary_search(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
bool binary_search(FwdIt first, FwdIt last, const T& val,
Pred pr);
The first template function determines whether a value of N exists
in the range [0, last - first) for which *(first + N) has
equivalent ordering to val, where the elements designated by
iterators in the range [first, last) form a sequence ordered by
operator<. If so, the function returns true. If no such value
exists, it returns false.
If FwdIt is a random-access iterator type, the function evaluates
the ordering predicate X < Y at most ceil(log(last - first)) + 2
times. Otherwise, the function evaluates the predicate a number of
times proportional to last - first.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
copy
template<class InIt, class OutIt>
OutIt copy(InIt first, InIt last, OutIt x);
The template function evaluates *(x + N) = *(first + N)) once for
each N in the range [0, last - first), for strictly increasing
values of N beginning with the lowest value. It then returns x + N.
file:///D|/97/c++_1/LIBREF.TXT (26 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 26 of 619
If x and first designate regions of storage, x must not be in the
range [first, last).
copy_backward
template<class BidIt1, class BidIt2>
BidIt2 copy_backward(BidIt1 first, BidIt1 last, BidIt2 x);
The template function evaluates *(x - N - 1) = *(last - N - 1))
once for each N in the range [0, last - first), for strictly
decreasing values of N beginning with the highest value. It then
returns x - (last - first). If x and first designate regions of
storage, x must not be in the range [first, last).
count
template<class InIt, class T>
size_t count(InIt first, InIt last,
const T& val);
The template function sets a count n to zero. It then executes ++n
for each N in the range [0, last - first) for which the predicate *
(first + N) == val is true. The function returns n. It evaluates
the predicate exactly last - first times.
In this implementation, if a translator does not support partial
specialization of templates, the return type is size_t instead of
iterator_traits<InIt>::distance_type.
See the related sample program.
count_if
template<class InIt, class Pred, class Dist>
size_t count_if(InIt first, InIt last,
Pred pr);
The template function sets a count n to zero. It then executes ++n
for each N in the range [0, last - first) for which the predicate
pr(*(first + N)) is true. It evaluates the predicate exactly last -
first times.
In this implementation, if a translator does not support partial
specialization of templates, the return type is size_t instead of
iterator_traits<InIt>::distance_type.
See the related sample program.
equal
template<class InIt1, class InIt2>
bool equal(InIt1 first, InIt1 last, InIt2 x);
template<class InIt1, class InIt2, class Pred>
bool equal(InIt1 first, InIt1 last, InIt2 x, Pred pr);
The first template function returns true only if, for each N in the
range [0, last1 - first1), the predicate *(first1 + N) == *(first2
file:///D|/97/c++_1/LIBREF.TXT (27 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 27 of 619
+ N) is true. The function evaluates the predicate once, at most,
for each N.
The second template function behaves the same, except that the
predicate is pr(*(first1 + N), *(first2 + N)).
equal_range
template<class FwdIt, class T>
pair<FwdIt, FwdIt> equal_range(FwdIt first, FwdIt last,
const T& val);
template<class FwdIt, class T, class Pred>
pair<FwdIt, FwdIt> equal_range(FwdIt first, FwdIt last,
const T& val, Pred pr);
The first template function effectively returns pair( lower_bound
(first, last, val), upper_bound(first, last, val)), where the
elements designated by iterators in the range [first, last) form a
sequence ordered by operator<. Thus, the function determines the
largest range of positions over which val can be inserted in the
sequence and still preserve its ordering.
If FwdIt is a random-access iterator type, the function evaluates
the ordering predicate X < Y at most ceil(2 * log(last - first)) +
1 times. Otherwise, the function evaluates the predicate a number
of times proportional to last - first.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
fill
template<class FwdIt, class T>
void fill(FwdIt first, FwdIt last, const T& x);
The template function evaluates *(first + N) = x once for each N in
the range [0, last - first).
fill_n
template<class OutIt, class Size, class T>
void fill_n(OutIt first, Size n, const T& x);
The template function evaluates *(first + N) = x once for each N in
the range [0, n).
find
template<class InIt, class T>
InIt find(InIt first, InIt last, const T& val);
The template function determines the lowest value of N in the range
[0, last - first) for which the predicate *(first + N) == val is
true. It then returns first + N. If no such value exists, the
function returns last. It evaluates the predicate once, at most,
for each N.
file:///D|/97/c++_1/LIBREF.TXT (28 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 28 of 619
See the related sample program.
find_end
template<class FwdIt1, class FwdIt2>
FwdIt1 find_end(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 find_end(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
The first template function determines the highest value of N in
the range [0, last1 - first1 - (last2 - first2)) such that for each
M in the range [0, last2 - first2), the predicate *(first1 + N + M)
== *(first2 + N + M) is true. It then returns first1 + N. If no
such value exists, the function returns last1. It evaluates the
predicate (last2 - first2) * (last1 - first1 - (last2 - first2) +
1) times, at most.
The second template function behaves the same, except that the
predicate is pr(*(first1 + N + M), *(first2 + N + M)).
find_first_of
template<class FwdIt1, class FwdIt2>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
The first template function determines the lowest value of N in the
range [0, last1 - first1) such that for some M in the range [0,
last2 - first2), the predicate *(first1 + N) == *(first2 + M) is
true. It then returns first1 + N. If no such value exists, the
function returns last1. It evaluates the predicate (last1 - first1)
* (last2 - first2) times, at most.
The second template function behaves the same, except that the
predicate is pr(*(first1 + N), *(first2 + M)).
find_if
template<class InIt, class Pred>
InIt find_if(InIt first, InIt last, Pred pr);
The template function determines the lowest value of N in the range
[0, last - first) for which the predicate pred(*(first + N)) is
true. It then returns first + N. If no such value exists, the
function returns last. It evaluates the predicate once, at most,
for each N.
See the related sample program.
for_each
file:///D|/97/c++_1/LIBREF.TXT (29 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 29 of 619
template<class InIt, class Fun>
Fun for_each(InIt first, InIt last, Fun f);
The template function evaluates f(*(first + N)) once for each N in
the range [0, last - first). It then returns f. The call f(*(first
+ N)) must not alter *(first + N).
See the related sample program.
generate
template<class FwdIt, class Gen>
void generate(FwdIt first, FwdIt last, Gen g);
The template function evaluates *(first + N) = g() once for each N
in the range [0, last - first).
See the related sample program.
generate_n
template<class OutIt, class Pred, class Gen>
void generate_n(OutIt first, Dist n, Gen g);
The template function evaluates *(first + N) = g() once for each N
in the range [0, n).
See the related sample program.
includes
template<class InIt1, class InIt2>
bool includes(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2);
template<class InIt1, class InIt2, class Pred>
bool includes(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, Pred pr);
The first template function determines whether a value of N exists
in the range [0, last2 - first2) such that, for each M in the range
[0, last1 - first1), *(first + M) and *(first + N) do not have
equivalent ordering, where the elements designated by iterators in
the ranges [first1, last1) and [first2, last2) each form a sequence
ordered by operator<. If so, the function returns false. If no such
value exists, it returns true. Thus, the function determines
whether the ordered sequence designated by iterators in the range
[first2, last2) has equivalent ordering with some element
designated by iterators in the range [first1, last1).
The function evaluates the predicate 2 * ((last1 - first1) + (last2
- first2)) - 1 times, at most.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: includes and includes (predicate version).
file:///D|/97/c++_1/LIBREF.TXT (30 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 30 of 619
inplace_merge
template<class BidIt>
void inplace_merge(BidIt first, BidIt middle, BidIt last);
template<class BidIt, class Pred>
void inplace_merge(BidIt first, BidIt middle, BidIt last, Pred p
The first template function reorders the sequences designated by
iterators in the ranges [first, middle) and [middle, last), each
ordered by operator<, to form a merged sequence of length last -
first beginning at first, also ordered by operator<. The merge
occurs without altering the relative order of elements within
either original sequence. Moreover, for any two elements from
different original sequences that have equivalent ordering, the
element from the ordered range [first, middle) precedes the other.
The function evaluates the ordering predicate X < Y at most ceil
((last - first) * log(last - first)) times. (Given enough temporary
storage, it can evaluate the predicate (last - first) - 1 times, at
most.)
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: inplace_merge and inplace_merge (predicate
version).
iter_swap
template<class FwdIt1, class FwdIt2>
void iter_swap(FwdIt1 x, FwdIt2 y);
The template function leaves the value originally stored in *y
subsequently stored in *x, and the value originally stored in *x
subsequently stored in *y.
See the related sample program.
lexicographical_compare
template<class InIt1, class InIt2>
bool lexicographical_compare(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2);
template<class InIt1, class InIt2, class Pred>
bool lexicographical_compare(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, Pred pr);
The first template function determines K, the number of elements to
compare as the smaller of last1 - first1 and last2 - first2. It
then determines the lowest value of N in the range [0, K) for which
*(first1 + N) and *(first2 + N) do not have equivalent ordering. If
no such value exists, the function returns true only if K < (last2
- first2). Otherwise, it returns true only if *(first1 + N) < *
(first2 + N). Thus, the function returns true only if the sequence
designated by iterators in the range [first1, last1) is
lexicographically less than the other sequence.
file:///D|/97/c++_1/LIBREF.TXT (31 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 31 of 619
The function evaluates the ordering predicate X < Y at most 2 * K
times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
lower_bound
template<class FwdIt, class T>
FwdIt lower_bound(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
FwdIt lower_bound(FwdIt first, FwdIt last, const T& val, Pred pr
The first template function determines the lowest value of N in the
range [0, last - first) such that, for each M in the range [0, N),
the predicate *(first + M) < val is true, where the elements
designated by iterators in the range [first, last) form a sequence
ordered by operator<. It then returns first + N. If no such value
exists, the function returns last. Thus, the function determines
the lowest position before which val can be inserted in the
sequence and still preserve its ordering.
If FwdIt is a random-access iterator type, the function evaluates
the ordering predicate X < Y ceil(log(last - first)) + 1 times, at
most. Otherwise, the function evaluates the predicate a number of
times proportional to last - first.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: lower_bound and lower_bound (predicate version).
make_heap
template<class RanIt>
void make_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void make_heap(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a heap ordered by
operator<.
The function evaluates the ordering predicate X < Y at most 3 *
(last - first) times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: heap and heap (predicate version).
max
template<class T>
const T& max(const T& x, const T& y);
template<class T, class Pred>
file:///D|/97/c++_1/LIBREF.TXT (32 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 32 of 619
const T& max(const T& x, const T& y, Pred pr);
The first template function returns y if x < y. Otherwise, it
returns x. T need supply only a single-argument constructor and a
destructor.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Microsoft-Specific:
To avoid conflicts with min and max in WINDEF.H, use _MIN and _MAX
instead. These macros evaluate to _cpp_min and _cpp_max,
respectively.
END Microsoft-Specific
max_element
template<class FwdIt>
FwdIt max_element(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt max_element(FwdIt first, FwdIt last, Pred pr);
The first template function determines the lowest value of N in the
range [0, last - first) such that, for each M in the range [0, last
- first), the predicate *(first + N) < *(first + M) is false. It
then returns first + N. Thus, the function determines the lowest
position that contains the largest value in the sequence.
The function evaluates the ordering predicate X < Y exactly max
((last - first) - 1, 0) times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: max_element and max_element (predicate version).
merge
template<class InIt1, class InIt2, class OutIt>
OutIt merge(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt merge(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
The first template function determines K, the number of elements to
copy as (last1 - first1) + (last2 - first2). It then alternately
copies two sequences, designated by iterators in the ranges
[first1, last1) and [first2, last2) and each ordered by operator<,
to form a merged sequence of length K beginning at x, also ordered
by operator<. The function then returns x + K.
The merge occurs without altering the relative order of elements
within either sequence. Moreover, for any two elements from
different sequences that have equivalent ordering, the element from
the ordered range [first1, last1) precedes the other. Thus, the
function merges two ordered sequences to form another ordered
file:///D|/97/c++_1/LIBREF.TXT (33 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 33 of 619
sequence.
If x and first1 designate regions of storage, the range [x, x + K)
must not overlap the range [first1, last1). If x and first2
designate regions of storage, the range [x, x + K) must not overlap
the range [first2, last2). The function evaluates the ordering
predicate X < Y at most K - 1 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: merge and merge (predicate version).
min
template<class T>
const T& min(const T& x, const T& y);
template<class T, class Pred>
const T& min(const T& x, const T& y, Pred pr);
The first template function returns y if y < x. Otherwise it
returns x. T need supply only a single-argument constructor and a
destructor.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Microsoft-Specific:
To avoid conflicts with min and max in WINDEF.H, use _MIN and _MAX
instead. These macros evaluate to _cpp_min and _cpp_max,
respectively.
END Microsoft-Specific
min_element
template<class FwdIt>
FwdIt min_element(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt min_element(FwdIt first, FwdIt last, Pred pr);
The first template function determines the lowest value of N in the
range [0, last - first) such that, for each M in the range [0, last
- first), the predicate *(first + M) < *(first + N) is false. It
then returns first + N. Thus, the function determines the lowest
position that contains the smallest value in the sequence.
The function evaluates the ordering predicate X < Y exactly max
((last - first) - 1, 0) times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: min_element and min_element (predicate version).
mismatch
template<class InIt1, class InIt2>
file:///D|/97/c++_1/LIBREF.TXT (34 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 34 of 619
pair<InIt1, InIt2> mismatch(InIt1 first, InIt1 last, InIt2 x);
template<class InIt1, class InIt2, class Pred>
pair<InIt1, InIt2> mismatch(InIt1 first, InIt1 last,
InIt2 x, Pred pr);
The first template function determines the lowest value of N in the
range [0, last1 - first1) for which the predicate !(*(first1 + N)
== *(first2 + N)) is true. It then returns pair(first1 + N, first2
+ N). If no such value exists, N has the value last1 - first1. The
function evaluates the predicate once, at most, for each N.
The second template function behaves the same, except that the
predicate is pr(*(first1 + N), *(first2 + N)).
next_permutation
template<class BidIt>
bool next_permutation(BidIt first, BidIt last);
template<class BidIt, class Pred>
bool next_permutation(BidIt first, BidIt last, Pred pr);
The first template function determines a repeating sequence of
permutations, whose initial permutation occurs when the sequence
designated by iterators in the range [first, last) is ordered by
operator<. (The elements are sorted in ascending order.) It then
reorders the elements in the sequence, by evaluating swap(X, Y) for
the elements X and Y zero or more times, to form the next
permutation. The function returns true only if the resulting
sequence is not the initial permutation. Otherwise, the resultant
sequence is the one next larger lexicographically than the original
sequence. No two elements may have equivalent ordering.
The function evaluates swap(X, Y) at most (last - first) / 2 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: next_permutation and next_permutation (predicate
version).
nth_element
template<class RanIt>
void nth_element(RanIt first, RanIt nth, RanIt last);
template<class RanIt, class Pred>
void nth_element(RanIt first, RanIt nth, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) such that for each N in the
range [0, nth - first) and for each M in the range [nth - first,
last - first), the predicate !(*(first + M) < *(first + N)) is
true. Moreover, for N equal to nth - first and for each M in the
range (nth - first, last - first) the predicate !(*(first + M) < *
(first + N)) is true. Thus, if nth != last, the element *nth is in
its proper position if elements of the entire sequence were sorted
in ascending order, ordered by operator<. Any elements before this
one belong before it in the sort sequence, and any elements
file:///D|/97/c++_1/LIBREF.TXT (35 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 35 of 619
following it belong after it.
The function evaluates the ordering predicate X < Y a number of
times proportional to last - first, on average.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: nth_element and nth_element (predicate version).
partial_sort
template<class RanIt>
void partial_sort(RanIt first, RanIt middle, RanIt last);
template<class RanIt, class Pred>
void partial_sort(RanIt first, RanIt middle, RanIt last, Pred pr
The first template function reorders the sequence designated by
iterators in the range [first, last) such that for each N in the
range [0, middle - first) and for each M in the range (N, last -
first), the predicate !(*(first + M) < *(first + N)) is true. Thus,
the smallest middle - first elements of the entire sequence are
sorted in ascending order, ordered by operator<. The order of
remaining elements is otherwise unspecified.
The function evaluates the ordering predicate X < Y ceil((last -
first) * log(middle - first)) times, at most.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: partial_sort and partial_sort (predicate version).
partial_sort_copy
template<class InIt, class RanIt>
RanIt partial_sort_copy(InIt first1, InIt last1,
RanIt first2, RanIt last2);
template<class InIt, class RanIt, class Pred>
RanIt partial_sort_copy(InIt first1, InIt last1,
RanIt first2, RanIt last2, Pred pr);
The first template function determines K, the number of elements to
copy as the smaller of last1 - first1 and last2 - first2. It then
copies and reorders K of the sequence designated by iterators in
the range [first1, last1) such that the K elements copied to first2
are ordered by operator<. Moreover, for each N in the range [0, K)
and for each M in the range (0, last1 - first1) corresponding to an
uncopied element, the predicate !(*(first2 + M) < *(first1 + N)) is
true. Thus, the smallest K elements of the entire sequence
designated by iterators in the range [first1, last1) are copied and
sorted in ascending order to the range [first2, first2 +
The function evaluates the ordering predicate X < Y ceil((last -
first) * log(K)) times, at most.
The second template function behaves the same, except that it
file:///D|/97/c++_1/LIBREF.TXT (36 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 36 of 619
replaces operator<(X, Y) with pr(X, Y).
Sample programs: one and one (predicate version).
partition
template<class BidIt, class Pred>
BidIt partition(BidIt first, BidIt last, Pred pr);
The template function reorders the sequence designated by iterators
in the range [first, last) and determines the value K such that for
each N in the range [0, K), the predicate pr(*(first + N)) is true,
and for each N in the range [K, last - first), the predicate pr(*
(first + N)) is false. The function then returns first + K.
The predicate must not alter its operand. The function evaluates pr
(*(first + N)) exactly last - first times, and swaps (last -
first) / 2 pairs of elements, at most.
See the related sample program.
pop_heap
template<class RanIt>
void pop_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void pop_heap(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a new heap, ordered by
operator< and designated by iterators in the range [first, last -
1), leaving the original element at *first subsequently at *(last -
1). The original sequence must designate an existing heap, also
ordered by operator<. Thus, first != last must be true and *(last -
1) is the element to remove from (pop off) the heap.
The function evaluates the ordering predicate X < Y ceil(2 * log
(last - first)) times, at most.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: heap and heap (predicate version).
prev_permutation
template<class BidIt>
bool prev_permutation(BidIt first, BidIt last);
template<class BidIt, class Pred>
bool prev_permutation(BidIt first, BidIt last, Pred pr);
The first template function determines a repeating sequence of
permutations, whose initial permutation occurs when the sequence
designated by iterators in the range [first, last) is the reverse
of one ordered by operator<. (The elements are sorted in descending
order.) It then reorders the elements in the sequence, by
evaluating swap(X, Y) for the elements X and Y zero or more times,
file:///D|/97/c++_1/LIBREF.TXT (37 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 37 of 619
to form the next permutation. The function returns true only if the
resulting sequence is not the initial permutation. Otherwise, the
resultant sequence is the one next smaller lexicographically than
the original sequence. No two elements may have equivalent
ordering.
The function evaluates swap(X, Y) (last - first) / 2 times, at
most.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
See the related sample program.
push_heap
template<class RanIt>
void push_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void push_heap(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a new heap ordered by
operator<. Iterators in the range [first, last - 1) must designate
an existing heap, also ordered by operator<. Thus, first != last
must be true and *(last - 1) is the element to add to (push on) the
heap.
The function evaluates the ordering predicate X < Y ceil(log(last -
first)) times, at most.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: heap and heap (predicate version).
random_shuffle
template<class RanIt>
void random_shuffle(RanIt first, RanIt last);
template<class RanIt, class Fun>
void random_shuffle(RanIt first, RanIt last, Fun& f);
The first template function evaluates swap(*(first + N), *(first +
M)) once for each N in the range [1, last - first), where M is a
value from some uniform random distribution over the range [0, N).
Thus, the function randomly shuffles the order of elements in the
sequence.
The second template function behaves the same, except that M is
(Dist)f((Dist)N), where Dist is the type
iterator_traits::distance_type.
Sample programs: random_shuffle and random_shuffle (predicate
version).
remove
file:///D|/97/c++_1/LIBREF.TXT (38 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 38 of 619
template<class FwdIt, class T>
FwdIt remove(FwdIt first, FwdIt last, const T& val);
The template function effectively assigns first to X, then executes
the statement:
if (!(*(first + N) == val))
*X++ = *(first + N);
once for each N in the range [0, last - first). It then returns X.
Thus, the function removes from the sequence all elements for which
the predicate *(first + N) == val is true, without altering the
relative order of remaining elements, and returns the iterator
value that designates the end of the revised sequence.
See the related sample program.
remove_copy
template<class InIt, class OutIt, class T>
OutIt remove_copy(InIt first, InIt last, OutIt x, const T& val);
The template function effectively executes the statement:
if (!(*(first + N) == val))
*x++ = *(first + N);
once for each N in the range [0, last - first). It then returns x.
Thus, the function removes from the sequence all elements for which
the predicate *(first + N) == val is true, without altering the
relative order of remaining elements, and returns the iterator
value that designates the end of the revised sequence.
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
See the related sample program.
remove_copy_if
template<class InIt, class OutIt, class Pred>
OutIt remove_copy_if(InIt first, InIt last, OutIt x, Pred pr);
The template function effectively executes the statement:
if (!pr(*(first + N)))
*x++ = *(first + N);
once for each N in the range [0, last - first). It then returns x.
Thus, the function removes from the sequence all elements for which
the predicate pr(*(first + N)) is true, without altering the
relative order of remaining elements, and returns the iterator
value that designates the end of the revised sequence.
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
file:///D|/97/c++_1/LIBREF.TXT (39 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 39 of 619
See the related sample program.
remove_if
template<class FwdIt, class Pred>
FwdIt remove_if(FwdIt first, FwdIt last, Pred pr);
The template function effectively assigns first to X, then executes
the statement:
if (!pr(*(first + N)))
*X++ = *(first + N);
once for each N in the range [0, last - first). It then returns X.
Thus, the function removes from the sequence all elements for which
the predicate pr(*(first + N)) is true, without altering the
relative order of remaining elements, and returns the iterator
value that designates the end of the revised sequence.
See the related sample program.
replace
template<caass FwdIt, class T>
void replace(FwdIt first, FwdIt last,
const T& vold, const T& vnew);
The template function executes the statement:
if (*(first + N) == vold)
*(first + N) = vnew;
once for each N in the range [0, last - first).
See the related sample program.
replace_copy
template<class InIt, class OutIt, class T>
OutIt replace_copy(InIt first, InIt last, OutIt x,
const T& vold, const T& vnew);
The template function executes the statement:
if (*(first + N) == vold)
*(x + N) = vnew;
else
*(x + N) = *(first + N)
once for each N in the range [0, last - first).
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
See the related sample program.
file:///D|/97/c++_1/LIBREF.TXT (40 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 40 of 619
replace_copy_if
template<class InIt, class OutIt, class Pred, class T>
OutIt replace_copy_if(InIt first, InIt last, OutIt x,
Pred pr, const T& val);
The template function executes the statement:
if (pr(*(first + N)))
*(x + N) = val;
else
*(x + N) = *(first + N)
once for each N in the range [0, last - first).
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
See the related sample program.
replace_if
template<class FwdIt, class Pred, class T>
void replace_if(FwdIt first, FwdIt last,
Pred pr, const T& val);
The template function executes the statement:
if (pr(*(first + N)))
*(first + N) = val;
once for each N in the range [0, last - first).
See the related sample program.
reverse
template<class BidIt>
void reverse(BidIt first, BidIt last);
The template function evaluates swap(*(first + N), *(last - 1 - N)
once for each N in the range [0, (last - first) / 2). Thus, the
function reverses the order of elements in the sequence.
See the related sample program.
reverse_copy
template<class BidIt, class OutIt>
OutIt reverse_copy(BidIt first, BidIt last, OutIt x);
The template function evaluates *(x + N) = *(last - 1 - N) once for
each N in the range [0, last - first). It then returns x + (last -
first). Thus, the function reverses the order of elements in the
sequence that it copies.
file:///D|/97/c++_1/LIBREF.TXT (41 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 41 of 619
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
See the related sample program.
rotate
template<class FwdIt>
void rotate(FwdIt first, FwdIt middle, FwdIt last);
The template function leaves the value originally stored in *(first
+ (N + (middle - last)) % (last - first)) subsequently stored in *
(first + N) for each N in the range [0, last - first). Thus, if a
''left'' shift by one element leaves the element originally stored
in *(first + (N + 1) % (last - first)) subsequently stored in *
(first + N), then the function can be said to rotate the sequence
either left by middle - first elements or right by last - middle
elements. Both [first, middle) and [middle, last) must be valid
ranges. The function swaps at most last - first pairs of elements.
See the related sample program.
rotate_copy
template<class FwdIt, class OutIt>
OutIt rotate_copy(FwdIt first, FwdIt middle, FwdIt last, OutIt x
The template function evaluates *(x + N) = *(first + (N + (middle -
first)) % (last - first)) once for each N in the range [0, last -
first). Thus, if a ''left'' shift by one element leaves the element
originally stored in *(first + (N + 1) % (last - first))
subsequently stored in *(first + N), then the function can be said
to rotate the sequence either left by middle - first elements or
right by last - middle elements as it copies. Both [first, middle)
and [middle, last) must be valid ranges.
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
See the related sample program.
search
template<class FwdIt1, class FwdIt2>
FwdIt1 search(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 search(FwdIt1 first1, FwdIt1 last1,
FwdIt2 first2, FwdIt2 last2, Pred pr);
The first template function determines the lowest value of N in the
range [0, (last1 - first1) - (last2 - first2)) such that for each M
in the range [0, last2 - first2), the predicate *(first1 + N + M)
== *(first2 + M) is true. It then returns first1 + N. If no such
value exists, the function returns last1. It evaluates the
predicate (last2 - first2) * (last1 - first1) times, at most.
file:///D|/97/c++_1/LIBREF.TXT (42 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 42 of 619
The second template function behaves the same, except that the
predicate is pr(*(first1 + N + M), *(first2 + M)).
search_n
template<class FwdIt, class Dist, class T>
FwdIt search_n(FwdIt first, FwdIt last,
Dist n, const T& val);
template<class FwdIt, class Dist, class T, class Pred>
FwdIt search_n(FwdIt first, FwdIt last,
Dist n, const T& val, Pred pr);
The first template function determines the lowest value of N in the
range [0, (last - first) - n) such that for each M in the range [0,
n), the predicate *(first + N + M) == val is true. It then returns
first + N. If no such value exists, the function returns last. It
evaluates the predicate n * (last - first) times, at most.
The second template function behaves the same, except that the
predicate is pr(*(first + N + M), val).
set_difference
template<class InIt1, class InIt2, class OutIt>
OutIt set_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
The first template function alternately copies values from two
sequences designated by iterators in the ranges [first1, last1) and
[first2, last2), both ordered by operator<, to form a merged
sequence of length K beginning at x, also ordered by operator<. The
function then returns x + K.
The merge occurs without altering the relative order of elements
within either sequence. Moreover, for two elements from different
sequences that have equivalent ordering that would otherwise be
copied to adjacent elements, the function copies only the element
from the ordered range [first1, last1) and skips the other. An
element from one sequence that has equivalent ordering with no
element from the other sequence is copied from the ordered range
[first1, last1) and skipped from the other. Thus, the function
merges two ordered sequences to form another ordered sequence that
is effectively the difference of two sets.
If x and first1 designate regions of storage, the range [x, x + K)
must not overlap the range [first1, last1). If x and first2
designate regions of storage, the range [x, x + K) must not overlap
the range [first2, last2). The function evaluates the ordering
predicate X < Y at most 2 * ((last1 - first1) + (last2 - first2)) -
1 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
file:///D|/97/c++_1/LIBREF.TXT (43 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 43 of 619
set_intersection
template<class InIt1, class InIt2, class OutIt>
OutIt set_intersection(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_intersection(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
The first template function alternately copies values from two
sequences designated by iterators in the ranges [first1, last1) and
[first2, last2), both ordered by operator<, to form a merged
sequence of length K beginning at x, also ordered by operator<. The
function then returns x + K.
The merge occurs without altering the relative order of elements
within either sequence. Moreover, for two elements from different
sequences that have equivalent ordering that would otherwise be
copied to adjacent elements, the function copies only the element
from the ordered range [first1, last1) and skips the other. An
element from one sequence that has equivalent ordering with no
element from the other sequence is also skipped. Thus, the function
merges two ordered sequences to form another ordered sequence that
is effectively the intersection of two sets.
If x and first1 designate regions of storage, the range [x, x + K)
must not overlap the range [first1, last1). If x and first2
designate regions of storage, the range [x, x + K) must not overlap
the range [first2, last2). The function evaluates the ordering
predicate X < Y at most 2 * ((last1 - first1) + (last2 - first2)) -
1 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
set_symmetric_difference
template<class InIt1, class InIt2, class OutIt>
OutIt set_symmetric_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_symmetric_difference(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
The first template function alternately copies values from two
sequences designated by iterators in the ranges [first1, last1) and
[first2, last2), both ordered by operator<, to form a merged
sequence of length K beginning at x, also ordered by operator<. The
function then returns x + K.
The merge occurs without altering the relative order of elements
within either sequence. Moreover, for two elements from different
sequences that have equivalent ordering that would otherwise be
copied to adjacent elements, the function copies neither element.
An element from one sequence that has equivalent ordering with no
element from the other sequence is copied. Thus, the function
file:///D|/97/c++_1/LIBREF.TXT (44 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 44 of 619
merges two ordered sequences to form another ordered sequence that
is effectively the symmetric difference of two sets.
If x and first1 designate regions of storage, the range [x, x + K)
must not overlap the range [first1, last1). If x and first2
designate regions of storage, the range [x, x + K) must not overlap
the range [first2, last2). The function evaluates the ordering
predicate X < Y at most 2 * ((last1 - first1) + (last2 - first2)) -
1 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
set_union
template<class InIt1, class InIt2, class OutIt>
OutIt set_union(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x);
template<class InIt1, class InIt2, class OutIt, class Pred>
OutIt set_union(InIt1 first1, InIt1 last1,
InIt2 first2, InIt2 last2, OutIt x, Pred pr);
The first template function alternately copies values from two
sequences designated by iterators in the ranges [first1, last1) and
[first2, last2), both ordered by operator<, to form a merged
sequence of length K beginning at x, also ordered by operator<. The
function then returns x + K.
The merge occurs without altering the relative order of elements
within either sequence. Moreover, for two elements from different
sequences that have equivalent ordering that would otherwise be
copied to adjacent elements, the function copies only the element
from the ordered range [first1, last1) and skips the other. Thus,
the function merges two ordered sequences to form another ordered
sequence that is effectively the union of two sets.
If x and first1 designate regions of storage, the range [x, x + K)
must not overlap the range [first1, last1). If x and first2
designate regions of storage, the range [x, x + K) must not overlap
the range [first2, last2). The function evaluates the ordering
predicate X < Y at most 2 * ((last1 - first1) + (last2 - first2)) -
1 times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
sort
template<class RanIt>
void sort(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a sequence ordered by
operator<. Thus, the elements are sorted in ascending order.
file:///D|/97/c++_1/LIBREF.TXT (45 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 45 of 619
The function evaluates the ordering predicate X < Y at most ceil
((last - first) * log(last - first)) times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
sort_heap
template<class RanIt>
void sort_heap(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort_heap(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a sequence that is
ordered by operator<. The original sequence must designate a heap,
also ordered by operator<. Thus, the elements are sorted in
ascending order.
The function evaluates the ordering predicate X < Y at most ceil
((last - first) * log(last - first)) times.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: heap and heap (predicate version).
stable_partition
template<class FwdIt, class Pred>
FwdIt stable_partition(FwdIt first, FwdIt last, Pred pr);
The template function reorders the sequence designated by iterators
in the range [first, last) and determines the value K such that for
each N in the range [0, K) the predicate pr(*(first + N)) is true,
and for each N in the range [K, last - first) the predicate pr(*
(first + N)) is false. It does so without altering the relative
order of either the elements designated by indexes in the range [0,
K) or the elements designated by indexes in the range [K, last -
first). The function then returns first + K.
The predicate must not alter its operand. The function evaluates pr
(*(first + N)) exactly last - first times, and swaps at most ceil
((last - first) * log(last - first)) pairs of elements. (Given
enough temporary storage, it can replace the swaps with 2 * (last -
first) assignments, at most.)
stable_sort
template<class RanIt>
void stable_sort(RanIt first, RanIt last);
template<class RanIt, class Pred>
void stable_sort(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by
iterators in the range [first, last) to form a sequence ordered by
file:///D|/97/c++_1/LIBREF.TXT (46 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 46 of 619
operator<. It does so without altering the relative order of
elements that have equivalent ordering. Thus, the elements are
sorted in ascending order.
The function evaluates the ordering predicate X < Y at most ceil
((last - first) * log2(last - first)) times. (Given enough
temporary storage, it can evaluate the predicate ceil((last -
first) * log(last - first)) times, at most.)
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
swap
template<class T>
void swap(T& x, T& y);
The template function leaves the value originally stored in y
subsequently stored in x, and the value originally stored in x
subsequently stored in y.
swap_ranges
template<class FwdIt1, class FwdIt2>
FwdIt2 swap_ranges(FwdIt1 first, FwdIt1 last, FwdIt2 x);
The template function evaluates swap(*(first + N), *(x + N)) once
for each N in the range [0, last - first). It then returns x +
(last - first). If x and first designate regions of storage, the
range [x, x + (last - first)) must not overlap the range [first,
last).
transform
template<class InIt, class OutIt, class Unop>
OutIt transform(InIt first, InIt last, OutIt x, Unop uop);
template<class InIt1, class InIt2, class OutIt, class Binop>
OutIt transform(InIt1 first1, InIt1 last1, InIt2 first2,
OutIt x, Binop bop);
The first template function evaluates *(x + N) = uop(*(first + N))
once for each N in the range [0, last - first). It then returns x +
(last - first). The call uop(*(first + N)) must not alter *(first +
N).
The second template function evaluates *(x + N) = bop(*(first1 +
N), *(first2 + N)) once for each N in the range [0, last1 -
first1). It then returns x + (last1 - first1). The call bop(*
(first1 + N), *(first2 + N)) must not alter either *(first1 + N) or
*(first2 + N).
unique
template<class FwdIt>
FwdIt unique(FwdIt first, FwdIt last);
template<class FwdIt, class Pred>
FwdIt unique(FwdIt first, FwdIt last, Pred pr);
file:///D|/97/c++_1/LIBREF.TXT (47 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 47 of 619
The first template function effectively assigns first to X, then
executes the statement:
if (N == 0 || !(*(first + N) == V))
V = *(first + N), *X++ = V;
once for each N in the range [0, last - first). It then returns X.
Thus, the function repeatedly removes from the sequence the second
of a pair of elements for which the predicate *(first + N) == *
(first + N - 1) is true, until only the first of a sequence of
equal elements survives. It does so without altering the relative
order of remaining elements, and returns the iterator value that
designates the end of the revised sequence. The function evaluates
the predicate last - first times, at most.
The second template function behaves the same, except that it
executes the statement:
if (N == 0 || !pr(*(first + N), V))
V = *(first + N), *X++ = V;
unique_copy
template<class InIt, class OutIt>
OutIt unique_copy(InIt first, InIt last, OutIt x);
template<class InIt, class OutIt, class Pred>
OutIt unique_copy(InIt first, InIt last, OutIt x, Pred pr);
The first template function effectively executes the statement:
if (N == 0 || !(*(first + N) == V))
V = *(first + N), *x++ = V;
once for each N in the range [0, last - first). It then returns x.
Thus, the function repeatedly removes from the sequence it copies
the second of a pair of elements for which the predicate *(first +
N) == *(first + N - 1) is true, until only the first of a sequence
of equal elements survives. It does so without altering the
relative order of remaining elements, and returns the iterator
value that designates the end of the copied sequence.
If x and first designate regions of storage, the range [x, x +
(last - first)) must not overlap the range [first, last).
The second template function behaves the same, except that it
executes the statement:
if (N == 0 || !pr(*(first + N), V))
V = *(first + N), *x++ = V;
upper_bound
template<class FwdIt, class T>
FwdIt upper_bound(FwdIt first, FwdIt last, const T& val);
template<class FwdIt, class T, class Pred>
FwdIt upper_bound(FwdIt first, FwdIt last, const T& val, Pred pr
file:///D|/97/c++_1/LIBREF.TXT (48 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 48 of 619
The first template function determines the highest value of N in
the range [0, last - first) such that, for each M in the range [0,
N) the predicate *(first + M) < val is true, where the elements
designated by iterators in the range [first, last) form a sequence
ordered by operator<. It then returns first + N. If no such value
exists, the function returns last. Thus, the function determines
the highest position before which val can be inserted into the
sequence and still preserve its ordering.
If FwdIt is a random-access iterator type, the function evaluates
the ordering predicate X < Y ceil(log(last - first)) + 1 times at
most. Otherwise, the function evaluates the predicate a number of
times proportional to last - first.
The second template function behaves the same, except that it
replaces operator<(X, Y) with pr(X, Y).
Sample programs: upper_bound and upper_bound (predicate version).
<bitset>
namespace std {
template<size_t N>
class bitset;
// TEMPLATE FUNCTIONS
template<class E, class T, size_t N>
basic_istream<E, T>& operator>>(basic_istream<E, T>& is,
bitset<N>& x);
template<class E, class T, size_t N>
basic_ostream<E, T>& operator<<(basic_ostream<E, T>& os,
const bitset<N>& x);
};
Include the standard header <bitset> to define the template class
bitset and two supporting templates.
bitset
any . at . bitset . bitset_size . count . element_type . flip .
none . operator!= . operator&= . operator<< . operator<<= .
operator== . operator>> . operator>>= . operator[] . operator^= .
operator|= . operator~ . reference . reset . set . size . test .
to_string . to_ulong
template<size_t N>
class bitset {
public:
typedef bool element_type;
class reference;
bitset();
bitset(unsigned long val);
template<class E, class T, class A>
explicit bitset(const string<E, T, A>& str,
string<E, T, A>size_type pos = 0,
string<E, T, A>size_type n = string<E, T, A>::npos);
bitset<N>& operator&=(const bitset<N>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (49 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 49 of 619
bitset<N>& operator|=(const bitset<N>& rhs);
bitset<N>& operator^=(const bitset<N>& rhs);
bitset<N>& operator<<=(const bitset<N>& pos);
bitset<N>& operator>>=(const bitset<N>& pos);
bitset<N>& set();
bitset<N>& set(size_t pos, bool val = true);
bitset<N>& reset();
bitset<N>& reset(size_t pos);
bitset<N>& flip();
bitset<N>& flip(size_t pos);
reference operator[](size_t pos);
bool operator[](size_t pos) const;
reference at(size_t pos);
bool at(size_t pos) const;
unsigned long to_ulong() const;
template<class E, class T, class A>
string to_string() const;
size_t count() const;
size_t size() const;
bool operator==(const bitset<N>& rhs) const;
bool operator!=(const bitset<N>& rhs) const;
bool test(size_t pos) const;
bool any() const;
bool none() const;
bitset<N> operator<<(size_t pos) const;
bitset<N> operator>>(size_t pos) const;
bitset<N> operator~();
static const size_t bitset_size = N;
};
The template class describes an object that stores a sequence of N
bits. A bit is set if its value is 1, reset if its value is 0. To
flip a bit is to change its value from 1 to 0 or from 0 to 1. When
converting between an object of class bitset<N> and an object of
some integral type, bit position j corresponds to the bit value 1
<< j. The integral value corresponding to two or more bits is the
sum of their bit values.
bitset::any
bool any() const;
The member function returns true if any bit is set in the bit
sequence.
bitset::at
bool at(size_type pos) const;
reference at(size_type pos);
The member function returns an object of class reference, which
designates the bit at position pos, if the object can be modified.
Otherwise, it returns the value of the bit at position pos in the
bit sequence. If that position is invalid, the function throws an
object of class out_of_range.
bitset::bitset
file:///D|/97/c++_1/LIBREF.TXT (50 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 50 of 619
bitset();
bitset(unsigned long val);
explicit bitset(const string& str,
size_t pos = 0, size_t n = -1);
The first constructor resets all bits in the bit sequence. The
second constructor sets only those bits at position j for which val
& 1 << j is nonzero.
The third constructor determines the initial bit values from
elements of a string determined from str. If str.size() < pos, the
constructor throws out_of_range. Otherwise, the effective length of
the string rlen is the smaller of n and str.size() - pos. If any of
the rlen elements beginning at position pos is other than 0 or 1,
the constructor throws invalid_argument. Otherwise, the constructor
sets only those bits at position j for which the element at
position pos + j is 1.
In this implementation, if a translator does not support member
template functions, the template:
template<class E, class T, class A>
explicit bitset(const string<E, T, A>& str,
string<E, T, A>size_type pos = 0,
string<E, T, A>size_type n = string<E, T, A>::npos);
is replaced by:
explicit bitset(const string& str,
size_t pos = 0, size_t n = -1);
bitset::bitset_size
static const size_t bitset_size = N;
The const static member is initialized to the template parameter N.
bitset::count
size_t count() const;
The member function returns the number of bits set in the bit
sequence.
bitset::element_type
typedef bool element_type;
The type is a synonyn for bool.
bitset::flip
bitset<N>& flip();
bitset<N>& flip(size_t pos);
The first member function flips all bits in the bit sequence, then
file:///D|/97/c++_1/LIBREF.TXT (51 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 51 of 619
returns *this. The second member function throws out_of_range if
size() <= pos. Otherwise, it flips the bit at position pos, then
returns *this.
bitset::none
bool none() const;
The member function returns true if none of the bits are set in the
bit sequence.
bitset::operator!=
bool operator !=(const bitset<N>& rhs) const;
The member operator function returns true only if the bit sequence
stored in *this differs from the one stored in rhs.
bitset::operator&=
bitset<N>& operator&=(const bitset<N>& rhs);
The member operator function replaces each element of the bit
sequence stored in *this with the logical AND of its previous value
and the corresponding bit in rhs. The function returns *this.
bitset::operator<<
bitset<N> operator<<(const bitset<N>& pos);
The member operator function returns bitset(*this) <<= pos.
bitset::operator<<=
bitset<N>& operator<<=(const bitset<N>& pos);
The member operator function replaces each element of the bit
sequence stored in *this with the element pos positions earlier in
the sequence. If no such earlier element exists, the function
clears the bit. The function returns *this.
bitset::operator==
bool operator ==(const bitset<N>& rhs) const;
The member operator function returns true only if the bit sequence
stored in *this is the same as the one stored in rhs.
bitset::operator>>
bitset<N> operator>>(const bitset<N>& pos);
The member operator function returns bitset(*this) >>= pos.
bitset::operator>>=
bitset<N>& operator>>=(const bitset<N>& pos);
file:///D|/97/c++_1/LIBREF.TXT (52 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 52 of 619
The member function replaces each element of the bit sequence
stored in *this with the element pos positions later in the
sequence. If no such later element exists, the function clears the
bit. The function returns *this.
bitset::operator[]
bool operator[](size_type pos) const;
reference operator(size_type pos);
The member function returns an object of class reference, which
designates the bit at position pos, if the object can be modified.
Otherwise, it returns the value of the bit at position pos in the
bit sequence. If that position is invalid, the behavior is
undefined.
bitset::operator^=
bitset<N>& operator^=(const bitset<N>& rhs);
The member operator function replaces each element of the bit
sequence stored in *this with the logical EXCLUSIVE OR of its
previous value and the corresponding bit in rhs. The function
returns *this.
bitset::operator|=
bitset<N>& operator|=(const bitset<N>& rhs);
The member operator function replaces each element of the bit
sequence stored in *this with the logical OR of its previous value
and the corresponding bit in rhs. The function returns *this.
bitset::operator~
bitset<N> operator~();
The member operator function returns bitset(*this).flip().
bitset::reference
class reference {
public:
reference& operator=(bool b};
reference& operator=(const reference& x);
bool operator~() const;
operator bool() const;
reference& flip();
};
The member class describes an object that designates an individual
bit within the bit sequence. Thus, for b an object of type bool, x
and y objects of type bitset<N>, and i and j valid positions within
such an object, the member functions of class reference ensure that
(in order):
file:///D|/97/c++_1/LIBREF.TXT (53 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 53 of 619
lx[i] = b stores b at bit position i in x
lx[i] = y[j] stores the value of the bit y[j] at bit position i
in x
lb = ~x[i] stores the flipped value of the bit x[i] in b
lb = x[i] stores the value of the bit x[i] in b
lx[i].flip() stores the flipped value of the bit x[i] back at
bit position i in x
bitset::reset
bitset<N>& reset();
bitset<N>& reset(size_t pos);
The first member function resets all bits in the bit sequence, then
returns *this. The second member function throws out_of_range if
size() <= pos. Otherwise, it resets the bit at position pos, then
returns *this.
bitset::set
bitset<N>& set();
bitset<N>& set(size_t pos, bool val = true);
The first member function resets all bits in the bit sequence, then
returns *this. The second member function throws out_of_range if
size() <= pos. Otherwise, it stores val in the bit at position pos,
then returns *this.
bitset::size
size_t size() const;
The member function returns N.
bitset::test
bool test(size_t pos, bool val = true);
The member function throws out_of_range if size() <= pos.
Otherwise, it returns true only if the bit at position pos is set.
bitset::to_string
string to_string() const;
The member function constructs str, an object of class string. For
each bit in the bit sequence, the function appends 1 if the bit is
set, otherwise 0. The last element appended to str corresponds to
bit position zero. The function returns str.
In this implementation, if a translator does not support member
template functions, the template:
template<class E, class T, class A>
string to_string() const;
file:///D|/97/c++_1/LIBREF.TXT (54 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 54 of 619
is replaced by:
string to_string() const;
bitset::to_ulong
unsigned long to_ulong() const;
The member function throws overflow_error if any bit in the bit
sequence has a bit value that cannot be represented as a value of
type unsigned long. Otherwise, it returns the sum of the bit values
in the bit sequence.
operator<<
template<class E, class T, size_t N>
basic_ostream<E, T>& operator<<(basic_ostream<E, T>& os,
const bitset<N>& x);
The template function overloads operator<< to insert a text
representation of the bit sequence in os. It effectively executes
os << x.to_string<E, char_traits<E>, allocator<E> >(), then returns
os.
operator>>
template<class E, class T, size_t N>
basic_istream<E, T>& operator>>(basic_istream<E, T>&
is, bitset<N>& x);
The template function overloads operator>> to store in x the value
bitset(str), where str is an object of type basic_string<E, T,
allocator<E> >& extracted from is. The function extracts elements
and appends them to str until:
lN elements have been extracted and stored.
lend-of-file occurs on the input sequence.
lthe next input element is neither 0 nor 1, in which case the
input element is not extracted.
If the function stores no characters in str, it calls is.setstate
(ios_base::failbit). In any case, it returns is.
<cassert>
namespace std {#include <assert.h> };
Include the standard header <cassert> to effectively include the
standard header <assert.h> within the std namespace.
abs
template<class T>
T abs(const complex<T>& x);
The function returns the magnitude of x.
file:///D|/97/c++_1/LIBREF.TXT (55 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 55 of 619
arg
template<class T>
T arg(const complex<T>& x);
The function returns the phase angle of x.
complex
template<class T>
class complex {
public:
typedef T value_type;
T real() const;
T imag() const;
complex(const T& re = 0, const T& im = 0);
complex(const complex& x);
complex& operator=(const complex& rhs);
complex& operator+=(const complex& rhs);
complex& operator-=(const complex& rhs);
complex& operator*=(const complex& rhs);
complex& operator/=(const complex& rhs);
complex& operator=(const T& rhs);
complex& operator=(const T& rhs);
complex& operator+=(const T& rhs);
complex& operator-=(const T& rhs);
complex& operator*=(const T& rhs);
complex& operator/=(const T& rhs);
friend complex<T>
operator+(const complex<T>& lhs, const T& rhs);
friend complex<T>
operator+(const T& lhs, const complex<T>& rhs);
friend complex<T>
operator-(const complex<T>& lhs, const T& rhs);
friend complex<T>
operator-(const T& lhs, const complex<T>& rhs);
friend complex<T>
operator*(const complex<T>& lhs, const T& rhs);
friend complex<T>
operator*(const T& lhs, const complex<T>& rhs);
friend complex<T>
operator/(const complex<T>& lhs, const T& rhs);
friend complex<T>
operator/(const T& lhs, const complex<T>& rhs);
friend bool operator==(const complex<T>& lhs, const T& rhs);
friend bool operator==(const T& lhs, const complex<T>& rhs);
friend bool operator!=(const complex<T>& lhs, const T& rhs);
friend bool operator!=(const T& lhs, const complex<T>& rhs);
};
The template class describes an object that stores two objects of
type T, one that represents the real part of a complex number and
one that represents the imaginary part. An object of class T:
lHas a public default constructor, destructor, copy constructor,
and assignment operator -- with conventional behavior.
file:///D|/97/c++_1/LIBREF.TXT (56 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 56 of 619
lCan be assigned integer or floating-point values, or type cast
to such values -- with conventional behavior.
lDefines the arithmetic operators defined for the floating-point
types -- with conventional behavior.
Explicit specializations of template class complex exist for the
three floating-point types. In this implementation, a value of any
other type T is type cast to double for actual calculations, with
double result assigned back to the stored object of type
complex::complex
complex(const T& re = 0, const T& im = 0);
complex(const complex& x);
The first constructor initializes the stored real part to re and
the stored imaginary part to im. The second constructor initializes
the stored real part to x.real() and the stored imaginary part to
x.imag().
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex(const complex<U>& x);
is replaced by:
complex(const complex& x);
which is the copy constructor.
complex::imag
T imag() const;
The member function returns the stored imaginary part.
complex::operator*=
complex& operator*=(const complex& rhs);
complex& operator*=(const T& rhs);
The first member function replaces the stored real and imaginary
parts with those corresponding to the complex product of *this and
rhs. It then returns *this.
The second member function multiplies both the stored real part and
the stored imaginary part with rhs. It then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex& operator*=(const complex<U>& rhs);
is replaced by:
file:///D|/97/c++_1/LIBREF.TXT (57 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 57 of 619
complex& operator*=(const complex& rhs);
complex::operator+=
complex& operator+=(const complex& rhs);
complex& operator+=(const T& rhs);
The first member function replaces the stored real and imaginary
parts with those corresponding to the complex sum of *this and rhs.
It then returns *this.
The second member function adds rhs to the stored real part. It
then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex& operator+=(const complex<U>& rhs);
is replaced by:
complex& operator+=(const complex& rhs);
complex::operator-=
complex& operator-=(const complex& rhs);
complex& operator-=(const T& rhs);
The first member function replaces the stored real and imaginary
parts with those corresponding to the complex difference of *this
and rhs. It then returns *this.
The second member function subtracts rhs from the stored real part.
It then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex& operator-=(const complex<U>& rhs);
is replaced by:
complex& operator-=(const complex& rhs);
complex::operator/=
complex& operator/=(const complex& rhs);
complex& operator/=(const T& rhs);
The first member function replaces the stored real and imaginary
parts with those corresponding to the complex quotient of *this and
rhs. It then returns *this.
The second member function multiplies both the stored real part and
file:///D|/97/c++_1/LIBREF.TXT (58 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 58 of 619
the stored imaginary part with rhs. It then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex& operator/=(const complex<U>& rhs);
is replaced by:
complex& operator/=(const complex& rhs);
complex::operator=
complex& operator=(const complex& rhs);
complex& operator=(const T& rhs);
The first member function replaces the stored real part with
rhs.real() and the stored imaginary part with rhs.imag(). It then
returns *this.
The second member function replaces the stored real part with rhs
and the stored imaginary part with zero. It then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
complex& operator=(const complex<U>& rhs);
is replaced by:
complex& operator=(const complex& rhs);
which is the default assignment operator.
complex::real
T real() const;
The member function returns the stored real part.
complex::value_type
typedef T value_type;
The type is a synonym for the template parameter T.
complex<double>
class complex<double> {
public:
complex(double re = 0, double im = 0);
complex(const complex<float>& x);
explicit complex(const complex<long double>& x);
// rest same as template class complex
};
file:///D|/97/c++_1/LIBREF.TXT (59 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 59 of 619
The explicitly specialized template class describes an object that
stores two objects of type double, one that represents the real
part of a complex number and one that represents the imaginary
part. The explicit specialization differs only in the constructors
it defines. The first constructor initializes the stored real part
to re and the stored imaginary part to im. The remaining two
constructors initialize the stored real part to x.real() and the
stored imaginary part to x.imag().
complex<float>
class complex<float> {
public:
complex(float re = 0, float im = 0);
explicit complex(const complex<double>& x);
explicit complex(const complex<long double>& x);
// rest same as template class complex
};
The explicitly specialized template class describes an object that
stores two objects of type float, one that represents the real part
of a complex number and one that represents the imaginary part. The
explicit specialization differs only in the constructors it
defines. The first constructor initializes the stored real part to
re and the stored imaginary part to im. The remaining two
constructors initialize the stored real part to x.real() and the
stored imaginary part to x.imag().
complex<long double>
class complex<long double> {
public:
complex(long double re = 0, long double im = 0);
complex(const complex<float>& x);
complex(const complex<double>& x);
// rest same as template class complex
};
The explicitly specialized template class describes an object that
stores two objects of type long double, one that represents the
real part of a complex number and one that represents the imaginary
part. The explicit specialization differs only in the constructors
it defines. The first constructor initializes the stored real part
to re and the stored imaginary part to im. The remaining two
constructors initialize the stored real part to x.real() and the
stored imaginary part to x.imag().
conjg
template<class T>
complex<T> conjg(const complex<T>& x);
The function returns the conjugate of x.
cos
file:///D|/97/c++_1/LIBREF.TXT (60 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 60 of 619
template<class T>
complex<T> cos(const complex<T>& x);
The function returns the cosine of x.
cosh
template<class T>
complex<T> cosh(const complex<T>& x);
The function returns the hyperbolic cosine of x.
exp
template<class T>
complex<T> exp(const complex<T>& x);
The function returns the exponential of x.
imag
template<class T>
T imag(const complex<T>& x);
The function returns the imaginary part of x.
log
template<class T>
complex<T> log(const complex<T>& x);
The function returns the logarithm of x. The branch cuts are along
the negative real axis.
log10
template<class T>
complex<T> log10(const complex<T>& x);
The function returns the base 10 logarithm of x. The branch cuts
are along the negative real axis.
norm
template<class T>
T norm(const complex<T>& x);
The function returns the squared magnitude of x.
operator!=
template<class T>
bool operator!=(const complex<T>& lhs, const complex<T>& rhs);
template<class T>
bool operator!=(const complex<T>& lhs, const T& rhs);
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (61 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 61 of 619
bool operator!=(const T& lhs, const complex<T>& rhs);
The operators each return true only if real(lhs) != real(rhs) ||
imag(lhs) != imag(rhs).
operator*
template<class T>
complex<T> operator*(const complex<T>& lhs, const complex<T>& rh
template<class T>
complex<T> operator*(const complex<T>& lhs, const T& rhs);
template<class T>
complex<T> operator*(const T& lhs, const complex<T>& rhs);
The operators each convert both operands to the return type, then
return the complex product of the converted lhs and rhs.
operator+
template<class T>
complex<T> operator+(const complex<T>& lhs, const complex<T>& rh
template<class T>
complex<T> operator+(const complex<T>& lhs, const T& rhs);
template<class T>
complex<T> operator+(const T& lhs, const complex<T>& rhs);
template<class T>
complex<T> operator+(const complex<T>& lhs);
The binary operators each convert both operands to the return type,
then return the complex sum of the converted lhs and rhs.
The unary operator returns lhs.
operator-
template<class T>
complex<T> operator-(const complex<T>& lhs, const complex<T>& rh
template<class T>
complex<T> operator-(const complex<T>& lhs, const T& rhs);
template<class T>
complex<T> operator-(const T& lhs, const complex<T>& rhs);
template<class T>
complex<T> operator-(const complex<T>& lhs);
The binary operators each convert both operands to the return type,
then return the complex difference of the converted lhs and rhs.
The unary operator returns a value whose real part is -real(lhs)
and whose imaginary part is -imag(lhs).
operator/
template<class T>
complex<T> operator/(const complex<T>& lhs, const complex<T>& rh
template<class T>
complex<T> operator/(const complex<T>& lhs, const T& rhs);
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (62 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 62 of 619
complex<T> operator/(const T& lhs, const complex<T>& rhs);
The operators each convert both operands to the return type, then
return the complex quotient of the converted lhs and rhs.
operator<<
template<class E, class T, class U>
basic_ostream<E, T>& operator<<(basic_ostream<E, T>& os,
const complex<U>& x);
The template function inserts the complex value x into the output
stream os, effectively by executing:
basic_ostringstream<E, T> ostr;
ostr.flags(os.flags());
ostr.imbue(os.imbue());
ostr.precision(os.precision());
ostr << '(' << real(x) << ','
<< imag(x) << ')';
os << ostr.str().c_str();
Thus, if os.width() is greater than zero, any padding occurs either
before or after the parenthesized pair of values, which itself
contains no padding. The function returns os.
operator==
template<class T>
bool operator==(const complex<T>& lhs, const complex<T>& rhs);
template<class T>
bool operator==(const complex<T>& lhs, const T& rhs);
template<class T>
bool operator==(const T& lhs, const complex<T>& rhs);
The operators each return true only if real(lhs) == real(rhs) &&
imag(lhs) == imag(rhs).
operator>>
template<class E, class T, class U>
basic_istream<E, T>& operator>>(basic_istream<E, T>& is,
complex<U>& x);
The template function attempts to extract a complex value from the
input stream is, effectively by executing:
is >> ch && ch == '('
is >> re >> ch && ch == ','
is >> im >> ch && ch == ')'
Here, ch is an object of type E, and re and im are objects of type
U.
If the result of this expression is true, the function stores re in
the real part and im in the imaginary part of x. In any event, the
function returns is.
file:///D|/97/c++_1/LIBREF.TXT (63 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 63 of 619
polar
template<class T>
complex<T> polar(const T& rho, const T& theta = 0);
The function returns the complex value whose magnitude is rho and
whose phase angle is theta.
pow
template<class T>
complex<T> pow(const complex<T>& x, int y);
template<class T>
complex<T> pow(const complex<T>& x, const T& y);
template<class T>
complex<T> pow(const complex<T>& x, const complex<T>& y);
template<class T>
complex<T> pow(const T& x, const complex<T>& y);
The functions each effectively convert both operands to the return
type, then return the converted x to the power y. The branch cut
for x is along the negative real axis.
real
template<class T>
T real(const complex<T>& x);
The function returns the real part of x.
sin
template<class T>
complex<T> sin(const complex<T>& x);
The function returns the imaginary sine of x.
sinh
template<class T>
complex<T> sinh(const complex<T>& x);
The function returns the hyperbolic sine of x.
sqrt
template<class T>
complex<T> sqrt(const complex<T>& x);
The function returns the square root of x, with phase angle in the
half-open interval (-pi/2, pi/2]. The branch cuts are along the
negative real axis.
__STD_COMPLEX
#define __STD_COMPLEX
file:///D|/97/c++_1/LIBREF.TXT (64 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 64 of 619
The macro is defined, with an unspecified expansion, to indicate
compliance with the specifications of this header.
<csetjmp>
namespace std {
#include <setjmp.h>
};
Include the standard header<csetjmp> to effectively include the
standard header <setjmp.h> within the std namespace.
deque
allocator_type . assign . at . back . begin . clear .
const_iterator . const_reference . const_reverse_iterator . deque .
difference_type . empty . end . erase . front . get_allocator .
insert . iterator . max_size . operator[] . pop_back . pop_front .
push_back . push_front . rbegin . reference . rend . resize .
reverse_iterator . size . size_type . swap . value_type
template<class T, class A = allocator<T> >
class deque {
public:
typedef A allocator_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::reference reference;
typedef A::const_reference const_reference;
typedef A::value_type value_type;
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_iterator<iterator, value_type,
reference, A::pointer, difference_type>
reverse_iterator;
typedef reverse_iterator<const_iterator, value_type,
const_reference, A::const_pointer, difference_type>
const_reverse_iterator;
explicit deque(const A& al = A());
explicit deque(size_type n, const T& v = T(), const A& al = A())
deque(const deque& x);
deque(const_iterator first, const_iterator last,
const A& al = A());
iterator begin();
const_iterator begin() const;
iterator end();
iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
void resize(size_type n, T x = T());
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
file:///D|/97/c++_1/LIBREF.TXT (65 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 65 of 619
reference at(size_type pos);
const_reference at(size_type pos) const;
reference operator[](size_type pos);
const_reference operator[](size_type pos);
reference front();
const_reference front() const;
reference back();
const_reference back() const;
void push_front(const T& x);
void pop_front();
void push_back(const T& x);
void pop_back();
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it,
const_iterator first, const_iterator last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
void swap(deque x);
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type T. The sequence is represented
in a way that permits insertion and removal of an element at either
end with a single element copy (constant time). Such operations in
the middle of the sequence require element copies and assignments
proportional to the number of elements in the sequence (linear
time).
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
Deque reallocation occurs when a member function must insert or
erase elements of the controlled sequence. In all such cases,
iterators or references that point anywhere within the controlled
sequence become invalid.
deque::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
deque::assign
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
The first member function replaces the sequence controlled by *this
file:///D|/97/c++_1/LIBREF.TXT (66 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 66 of 619
with the sequence [first, last). The second member function
replaces the sequence controlled by *this with a repetition of n
elements of value x.
In this implementation, if a translator does not support member
template functions, the templates:
template<class InIt>
void assign(InIt first, InIt last);
template<class Size, class T2>
void assign(Size n, const T2& x = T2());
are replaced by:
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
See the related sample program.
deque::at
const_reference at(size_type pos) const;
reference at(size_type pos);
The member function returns a reference to the element of the
controlled sequence at position pos. If that position is invalid,
the function throws an object of class out_of_range.
See the related sample program.
deque::back
reference back();
const_reference back() const;
The member function returns a reference to the last element of the
controlled sequence, which must be non-empty.
See the related sample program.
deque::begin
const_iterator begin() const;
iterator begin();
The member function returns a random-access iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
See the related sample program.
deque::clear
void clear() const;
The member function calls erase( begin(), end()).
file:///D|/97/c++_1/LIBREF.TXT (67 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 67 of 619
See the related sample program.
deque::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant random-
access iterator for the controlled sequence. It is described here
as a synonym for the unspecified type T1.
deque::const_reference
typedef A::const_reference const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
deque::const_reverse_iterator
typedef reverse_iterator<const_iterator, value_type,
const_reference, A::const_pointer, difference_type>
const_reverse_iterator;
The type describes an object that can serve as a constant reverse
random-access iterator for the controlled sequence.
deque::deque
explicit deque(const A& al = A());
explicit deque(size_type n, const T& v = T(), const A& al = A());
deque(const deque& x);
deque(const_iterator first, const_iterator last, const A& al = A());
All constructors store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
repetition of n elements of value x. The third constructor
specifies a copy of the sequence controlled by x. The last
constructor specifies the sequence [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
deque(InIt first, InIt last, const A& al = A());
is replaced by:
deque(const_iterator first, const_iterator last, const A& al = A
());
deque::difference_type
typedef A::difference_type difference_type;
file:///D|/97/c++_1/LIBREF.TXT (68 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 68 of 619
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
deque::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
deque::end
const_iterator end() const;
iterator end();
The member function returns a random-access iterator that points
just beyond the end of the sequence.
See the related sample program.
deque::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements of the controlled sequence in the range [first, last).
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
Removing N elements causes N destructor calls and an assignment for
each of the elements between the insertion point and the nearer end
of the sequence. Removing an element at either end invalidates only
iterators and references that designate the erased elements.
Otherwise, erasing an element invalidates all iterators and
references.
See the related sample program.
deque::front
reference front();
const_reference front() const;
The member function returns a reference to the first element of the
controlled sequence, which must be non-empty.
See the related sample program.
deque::get_allocator
A get_allocator() const;
The member function returns allocator.
file:///D|/97/c++_1/LIBREF.TXT (69 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 69 of 619
deque::insert
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it, const_iterator first, const_iterator last);
Each of the member functions inserts, before the element pointed to
by it in the controlled sequence, a sequence specified by the
remaining operands. The first member function inserts a single
element with value x and returns an iterator that points to the
newly inserted element. The second member function inserts a
repetition of n elements of value x. The last member function
inserts the sequence [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(iterator it, InIt first, InIt last);
is replaced by:
void insert(iterator it, const_iterator first, const_iterator
last);
When inserting a single element, the number of element copies is
linear in the number of elements between the insertion point and
the nearer end of the sequence. When inserting a single element at
either end of the sequence, the amortized number of element copies
is constant. When inserting N elements, the number of element
copies is linear in N plus the number of elements between the
insertion point and the nearer end of the sequence -- except when
the template member is specialized for InIt an input or forward
iterator, which behaves like N single insertions. Inserting an
element at either end invalidates all iterators, but no references,
that designate existing elements. Otherwise, inserting an element
invalidates all iterators and references.
See the related sample program.
deque::iterator
typedef T0 iterator;
The type describes an object that can serve as a random-access
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
deque::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
deque::operator[]
file:///D|/97/c++_1/LIBREF.TXT (70 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 70 of 619
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
The member function returns a reference to the element of the
controlled sequence at position pos. If that position is invalid,
the behavior is undefined.
See the related sample program.
deque::pop_back
void pop_back();
The member function removes the last element of the controlled
sequence, which must be non-empty. Removing the element invalidates
only iterators and references that designate the erased element.
See the related sample program.
deque::pop_front
void pop_front();
The member function removes the first element of the controlled
sequence, which must be non-empty. Removing the element invalidates
only iterators and references that designate the erased element.
See the related sample program.
deque::push_back
void push_back(const T& x);
The member function inserts an element with value x at the end of
the controlled sequence. Inserting the element invalidates all
iterators, but no references, to existing elements.
See the related sample program.
deque::push_front
void push_front(const T& x);
The member function inserts an element with value x at the
beginning of the controlled sequence. Inserting the element
invalidates all iterators, but no references, to existing elements.
See the related sample program.
deque::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse iterator that points just
beyond the end of the controlled sequence. Hence, it designates the
file:///D|/97/c++_1/LIBREF.TXT (71 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 71 of 619
beginning of the reverse sequence.
See the related sample program.
deque::reference
typedef A::reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
deque::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse iterator that points at the
first element of the sequence (or just beyond the end of an empty
sequence). Hence, it designates the end of the reverse sequence.
See the related sample program.
deque::resize
void resize(size_type n, T x = T());
The member function ensures that size() henceforth returns n. If it
must lengthen the controlled sequence, it appends elements with
value x.
See the related sample program.
deque::reverse_iterator
typedef reverse_iterator<iterator, value_type,
reference, A::pointer, difference_type>
reverse_iterator;
The type describes an object that can serve as a reverse random-
access iterator for the controlled sequence.
deque::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
deque::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
deque::swap
file:///D|/97/c++_1/LIBREF.TXT (72 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 72 of 619
void swap(deque& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
See the related sample program.
deque::value_type
typedef A::value_type value_type;
The type is a synonym for the template parameter T.
operator!=
template<class T, class A>
bool operator!=(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class T, class A>
bool operator==(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function overloads operator== to compare two objects
of template class deque. The function returns lhs.size() ==
rhs.size() && equal(lhs. begin(), lhs. end(), rhs.begin()).
See the related sample program.
operator<
template<class T, class A>
bool operator<(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function overloads operator< to compare two objects of
template class deque. The function returns lexicographical_compare
(lhs. begin(), lhs. end(), rhs.begin(), rhs.end()).
See the related sample program.
operator<=
template<class T, class A>
bool operator<=(
const deque <T, A>& lhs,
file:///D|/97/c++_1/LIBREF.TXT (73 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 73 of 619
const deque <T, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class A>
bool operator>(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class A>
bool operator>=(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function returns !(rhs < lhs).
swap
template<class T, class A>
void swap(
const deque <T, A>& lhs,
const deque <T, A>& rhs);
The template function executes lhs.swap(rhs).
<exception>
namespace std {
class exception;
class bad_exception;
typedef void (*terminate_handler)();
typedef void (*unexpected_handler)();
terminate_handler set_terminate(terminate_handler ph) throw();
unexpected_handler set_unexpected(unexpected_handler ph) throw()
void terminate();
void unexpected();
bool uncaught_exception();
};
Include the standard header <exception> to define several types and
functions related to the handling of exceptions.
bad_exception
class bad_exception : public exception {
};
The class describes an exception that can be thrown from an
unexpected handler. The value returned by what() is implementation-
defined. None of the member functions throw any exceptions.
file:///D|/97/c++_1/LIBREF.TXT (74 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 74 of 619
exception
class exception {
public:
exception() throw();
exception(const exception& rhs) throw();
exception& operator=(const exception& rhs) throw();
virtual ~exception() throw();
virtual const char *what() const throw();
};
The class serves as the base class for all exceptions thrown by
certain expressions and by the Standard C++ library. The C string
value returned by what() is left unspecified by the default
constructor, but may be defined by the constructors for certain
derived classes. None of the member functions throw any exceptions.
set_terminate
terminate_handler set_terminate(terminate_handler ph) throw();
The function establishes a new terminate handler as the function
*ph. Thus, ph must not be a null pointer. The function returns the
address of the previous terminate handler.
set_unexpected
unexpected_handler set_unexpected(unexpected_handler ph) throw();
The function establishes a new unexpected handler as the function
*ph. Thus, ph must not be a null pointer. The function returns the
address of the previous unexpected handler.
terminate_handler
typedef void (*terminate_handler)();
The type describes a pointer to a function suitable for use as a
terminate handler.
unexpected_handler
typedef void (*unexpected_handler)();
The type describes a pointer to a function suitable for use as an
unexpected handler.
terminate
void terminate();
The function calls the current terminate handler, a function of
type void () called when exception handling must be abandoned for
any of several reasons. A terminate handler may not return to its
caller. At program startup, the terminate handler is a function
that calls abort().
file:///D|/97/c++_1/LIBREF.TXT (75 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 75 of 619
uncaught_exception
bool uncaught_exception();
The function returns true only if a thrown exception is being
currently processed.
unexpected
void unexpected();
The function calls the current unexpected handler, a function of
type void () called when control leaves a function by a thrown
exception of a type not permitted by an exception specification for
the function, as in:
void f() throw() // function may throw no exceptions
{throw "bad"; } // unexpected throw calls unexpected()
An unexpected handler may not return to its caller. It may
terminate execution by:
lThrowing an object of a type listed in the exception
specification.
lThrowing an object of type bad_exception.
lCalling terminate(), abort(), or exit(int).
At program startup, the unexpected handler is a function that calls
terminate().
<fstream>
namespace std {
template<class E, class T = char_traits<E> >
class basic_filebuf;
typedef basic_filebuf<char> filebuf;
typedef basic_filebuf<wchar_t> wfilebuf;
template<class E, class T = char_traits<E> >
class basic_ifstream;
typedef basic_ifstream<char> ifstream;
typedef basic_ifstream<wchar_t> wifstream;
template<class E, class T = char_traits<E> >
class basic_ofstream;
typedef basic_ofstream<char> ofstream;
typedef basic_ofstream<wchar_t> wofstream;
template<class E, class T = char_traits<E> >
class basic_fstream;
typedef basic_fstream<char> fstream;
typedef basic_fstream<wchar_t> wfstream;
};
Include the iostreams standard header <fstream> to define several
template classes that support iostreams operations on sequences
stored in external files.
basic_filebuf
file:///D|/97/c++_1/LIBREF.TXT (76 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 76 of 619
template <class E, class T = char_traits<E> >
class basic_filebuf : public basic_streambuf<E, T> {
public:
basic_filebuf();
bool is_open() const;
basic_filebuf *open(const char *s, ios_base::openmode mode);
basic_filebuf *close();
protected:
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 pos,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual int_type underflow();
virtual int_type pbackfail(int_type c = T::eof());
virtual int_type overflow(int_type c = T::eof());
virtual int sync();
virtual basic_streambuf<E, T> *setbuf(E *s, streamsize n);
};
The template class describes a stream buffer that controls the
transmission of elements to and from a sequence of elements stored
in an external file.
An object of class basic_filebuf<E, T> stores a file pointer, which
designates the FILE object that controls the stream associated with
an open file. It also stores pointers to two file conversion facets
for use by the protected member functions overflow and underflow.
basic_filebuf::basic_filebuf
basic_filebuf();
The constructor stores a null pointer in all the pointers
controlling the input buffer and the output buffer. It also stores
a null pointer in the file pointer.
basic_filebuf::close
basic_filebuf *close();
The member function returns a null pointer if the file pointer fp
is a null pointer. Otherwise, it calls fclose(fp). If that function
returns a nonzero value, the function returns a null pointer.
Otherwise, it returns this to indicate that the file was
successfully closed.
basic_filebuf::is_open
bool is_open();
The member function returns true if the file pointer is not a null
pointer.
basic_filebuf::open
basic_filebuf *open(const char *s, ios_base::openmode mode);
file:///D|/97/c++_1/LIBREF.TXT (77 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 77 of 619
The member function endeavors to open the file with file name s, by
calling fopen(s, strmode). Here strmode is determined from mode & ~
(ate & | binary):
lios_base::in becomes "r" (open existing file for reading).
lios_base::out or
lios_base::out | ios_base::trunc becomes "w" (truncate existing
file or create for writing).
lios_base::out | app becomes "a" (open existing file for
appending all writes).
lios_base::in | ios_base::out becomes "r+" (open existing file
for reading and writing).
lios_base::in | ios_base::out | ios_base::trunc becomes
"w+" (truncate existing file or create for reading and
writing).
lios_base::in | ios_base::out | ios_base::app becomes "a+" (open
existing file for reading and for appending all writes).
If mode & ios_base::binary is nonzero, the function appends b to
strmode to open a binary stream instead of a text stream. It then
stores the value returned by fopen in the file pointer fp. If mode
& ios_base::ate is nonzero and the file pointer is not a null
pointer, the function calls fseek(fp, 0, SEEK_END) to position the
stream at end-of-file. If that positioning operation fails, the
function calls close(fp) and stores a null pointer in the file
pointer.
If the file pointer is not a null pointer, the function determines
the file conversion facet use_facet< codecvt<E, char,
T::state_type> >(getloc()), for use by underflow and overflow.
If the file pointer is a null pointer, the function returns a null
pointer. Otherwise, it returns this.
basic_filebuf::overflow
virtual int_type overflow(int_type c = T::eof());
If c != T::eof(), the protected virtual member function endeavors
to insert the element T::to_char_type(c) into the output buffer. It
can do so in various ways:
lIf a write position is available, it can store the element into
the write position and increment the next pointer for the
output buffer.
lIt can make a write position available by allocating new or
additional storage for the output buffer.
lIt can convert any pending output in the output buffer,
followed by c, by using the file conversion facet fac to call
fac.out as needed. Each element x of type char thus produced
written to the associated stream designated by the file pointer
fp as if by successive calls of the form fputc(x, fp). If any
conversion or write fails, the function does not succeed.
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns T::not_eof(c).
file:///D|/97/c++_1/LIBREF.TXT (78 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 78 of 619
basic_filebuf::pbackfail
virtual int_type pbackfail(int_type c = T::eof());
The protected virtual member function endeavors to put back an
element into the input buffer, then make it the current element
(pointed to by the next pointer). If c == T::eof(), the element to
push back is effectively the one already in the stream before the
current element. Otherwise, that element is replaced by x =
T::to_char_type(c). The function can put back an element in various
ways:
lIf a putback position is available, and the element stored
there compares equal to x, it can simply decrement the next
pointer for the input buffer.
lIf the function can make a putback position available, it can
do so, set the next pointer to point at that position, and
store x in that position.
lIf the function can push back an element onto the input stream,
it can do so, such as by calling ungetc for an element of type
char.
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns T::not_eof(c).
basic_filebuf::seekoff
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class basic_filebuf<E, T>, a stream position can be represented by
an object of type fpos_t, which stores an offset and any state
information needed to parse a wide stream. Offset zero designates
the first element of the stream. (An object of type pos_type stores
at least an fpos_t object.)
For a file opened for both reading and writing, both the input and
output streams are positioned in tandem. To switch between
inserting and extracting, you must call either pubseekoff or
pubseekpos. Calls to pubseekoff (and hence to seekoff) have various
limitations for text streams, binary streams, and wide streams.
If the file pointer fp is a null pointer, the function fails.
Otherwise, it endeavors to alter the stream position by calling
fseek(fp, off, way). If that function succeeds and the resultant
position fposn can be determined by calling fgetpos(fp, &fposn),
the function succeeds. If the function succeeds, it returns a value
of type pos_type containing fposn. Otherwise, it returns an invalid
stream position.
basic_filebuf::seekpos
virtual pos_type seekpos(pos_type pos,
ios_base::openmode which = ios_base::in | ios_base::out);
file:///D|/97/c++_1/LIBREF.TXT (79 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 79 of 619
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class basic_filebuf<E, T>, a stream position can be represented by
an object of type fpos_t, which stores an offset and any state
information needed to parse a wide stream. Offset zero designates
the first element of the stream. (An object of type pos_type stores
at least an fpos_t object.)
For a file opened for both reading and writing, both the input and
output streams are positioned in tandem. To switch between
inserting and extracting, you must call either pubseekoff or
pubseekpos. Calls to pubseekoff (and hence to seekoff) have various
limitations for text streams, binary streams, and wide streams.
If the file pointer fp is a null pointer, the function fails.
Otherwise, it endeavors to alter the stream position by calling
fsetpos(fp, &fposn), where fposn is the fpos_t object stored in
pos. If that function succeeds, the function returns pos.
Otherwise, it returns an invalid stream position.
basic_filebuf::setbuf
virtual basic_streambuf<E, T> *setbuf(E *s, streamsize n);
The protected member function returns zero if the file pointer fp
is a null pointer. Otherwise, it calls setvbuf(fp, (char *)s,
_IOFBF, n * sizeof (E)) to offer the array of n elements beginning
at s as a buffer for the stream. If that function returns a nonzero
value, the function returns a null pointer. Otherwise, it returns
this to signal success.
basic_filebuf::sync
int sync();
The protected member function returns zero if the file pointer fp
is a null pointer. Otherwise, it returns fflush(fp) to flush any
pending output to the stream.
basic_filebuf::underflow
virtual int_type underflow();
The protected virtual member function endeavors to extract the
current element c from the input stream, and return the element as
T::to_int_type(c). It can do so in various ways:
lIf a read position is available, it takes c as the element
stored in the read position and advances the next pointer for
the input buffer.
lIt can read one or more elements of type char, as if
successive calls of the form fgetc(fp), and convert them to an
element c of type E by using the file conversion facet fac to
call fac.in as needed. If any read or conversion fails, the
function does not succeed.
file:///D|/97/c++_1/LIBREF.TXT (80 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 80 of 619
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns c, converted as described above.
basic_fstream
template <class E, class T = char_traits<E> >
class basic_fstream : public basic_iostream<E, T> {
public:
explicit basic_fstream();
explicit basic_fstream(const char *s,
ios_base::openmode mode = ios_base::in | ios_base::out);
basic_filebuf<E, T> *rdbuf() const;
bool is_open() const;
void open(const char *s,
ios_base::openmode mode = ios_base::in | ios_base::out);
void close();
};
The template class describes an object that controls insertion and
extraction of elements and encoded objects using a stream buffer of
class basic_filebuf<E, T>, with elements of type E, whose character
traits are determined by the class T. The object stores an object
of class basic_filebuf<E, T>.
basic_fstream::basic_fstream
explicit basic_fstream();
explicit basic_fstream(const char *s,
ios_base::openmode mode = ios_base::in | ios_base::out);
The first constructor initializes the base class by calling
basic_iostream(sb), where sb is the stored object of class
basic_filebuf<E, T>. It also initializes sb by calling
basic_filebuf<E, T>().
The second constructor initializes the base class by calling
basic_iostream(sb). It also initializes sb by calling
basic_filebuf<E, T>(), then sb.open(s, mode). If the latter
function returns a null pointer, the constructor calls setstate
(failbit).
basic_fstream::close
voidclose();
The member function calls rdbuf()-> close().
basic_fstream::is_open
bool is_open();
The member function returns rdbuf()-> is_open().
basic_fstream::open
void open(const char *s,
file:///D|/97/c++_1/LIBREF.TXT (81 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 81 of 619
ios_base::openmode mode = ios_base::in | ios_base::out);
The member function calls rdbuf()-> open(s, mode). If that function
returns a null pointer, the function calls setstate(failbit).
basic_fstream::rdbuf
basic_filebuf<E, T> *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to basic_filebuf<E, T>.
basic_ifstream
template <class E, class T = char_traits<E> >
class basic_ifstream : public basic_istream<E, T> {
public:
explicit basic_ifstream();
explicit basic_ifstream(const char *s,
ios_base::openmode mode = ios_base::in);
basic_filebuf<E, T> *rdbuf() const;
bool is_open() const;
void open(const char *s,
ios_base::openmode mode = ios_base::in);
void close();
};
The template class describes an object that controls extraction of
elements and encoded objects from a stream buffer of class
basic_filebuf<E, T>, with elements of type E, whose character
traits are determined by the class T. The object stores an object
of class basic_filebuf<E, T>.
basic_ifstream::basic_ifstream
explicit basic_ifstream();
explicit basic_ifstream(const char *s,
ios_base::openmode mode = ios_base::in);
The first constructor initializes the base class by calling
basic_istream(sb), where sb is the stored object of class
basic_filebuf<E, T>. It also initializes sb by calling
basic_filebuf<E, T>().
The second constructor initializes the base class by calling
basic_istream(sb). It also initializes sb by calling
basic_filebuf<E, T>(), then sb.open(s, mode | ios_base::in). If the
latter function returns a null pointer, the constructor calls
setstate(failbit).
basic_ifstream::close
void close();
The member function calls rdbuf()-> close().
basic_ifstream::is_open
file:///D|/97/c++_1/LIBREF.TXT (82 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 82 of 619
bool is_open();
The member function returns rdbuf()-> is_open().
basic_ifstream::open
void open(const char *s,
ios_base::openmode mode = ios_base::in);
The member function calls rdbuf()-> open(s, mode | ios_base::in).
If that function returns a null pointer, the function calls
setstate(failbit).
basic_ifstream::rdbuf
basic_filebuf<E, T> *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to basic_filebuf<E, T>.
basic_ofstream
template <class E, class T = char_traits<E> >
class basic_ofstream : public basic_ostream<E, T> {
public:
explicit basic_ofstream();
explicit basic_ofstream(const char *s,
ios_base::openmode mode = ios_base::out | ios_base::trunc);
basic_filebuf<E, T> *rdbuf() const;
bool is_open() const;
void open(const char *s,
ios_base::openmode mode = ios_base::out | ios_base::trunc);
void close();
};
The template class describes an object that controls insertion of
elements and encoded objects into a stream buffer of class
basic_filebuf<E, T>, with elements of type E, whose character
traits are determined by the class T. The object stores an object
of class basic_filebuf<E, T>.
basic_ofstream::basic_ofstream
explicit basic_ofstream();
explicit basic_ofstream(const char *s,
ios_base::openmode which = ios_base::out | ios_base::trunc);
The first constructor initializes the base class by calling
basic_ostream(sb), where sb is the stored object of class
basic_filebuf<E, T>. It also initializes sb by calling
basic_filebuf<E, T>().
The second constructor initializes the base class by calling
basic_ostream(sb). It also initializes sb by calling
basic_filebuf<E, T>(), then sb.open(s, mode | ios_base::out). If
the latter function returns a null pointer, the constructor calls
file:///D|/97/c++_1/LIBREF.TXT (83 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 83 of 619
setstate(failbit).
basic_ofstream::close
void close();
The member function calls rdbuf()-> close().
basic_ofstream::is_open
bool is_open();
The member function returns rdbuf()-> is_open().
basic_ofstream::open
void open(const char *s,
ios_base::openmode mode = ios_base::out | ios_base::trunc);
The member function calls rdbuf()-> open(s, mode | ios_base::out).
If that function returns a null pointer, the function calls
setstate(failbit).
basic_ofstream::rdbuf
basic_filebuf<E, T> *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to basic_filebuf<E, T>.
filebuf
typedef basic_filebuf<char, char_traits<char> > filebuf;
The type is a synonym for template class basic_filebuf, specialized
for elements of type char with default character
fstream
typedef basic_fstream<char, char_traits<char> > fstream;
The type is a synonym for template class basic_fstream, specialized
for elements of type char with default character
ifstream
typedef basic_ifstream<char, char_traits<char> > ifstream;
The type is a synonym for template class basic_ifstream,
specialized for elements of type char with default character
ofstream
typedef basic_ofstream<char, char_traits<char> > ofstream;
The type is a synonym for template class basic_ofstream,
specialized for elements of type char with default character
file:///D|/97/c++_1/LIBREF.TXT (84 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 84 of 619
wfilebuf
typedef basic_filebuf<wchar_t, char_traits<wchar_t> > wfilebuf;
The type is a synonym for template class basic_filebuf, specialized
for elements of type wchar_t with default character traits.
wfstream
typedef basic_fstream<wchar_t, char_traits<wchar_t> > wfstream;
The type is a synonym for template class basic_fstream, specialized
for elements of type wchar_t with default character traits.
wifstream
typedef basic_ifstream<wchar_t, char_traits<wchar_t> > wifstream;
The type is a synonym for template class basic_ifstream,
specialized for elements of type wchar_t with default character
traits.
wofstream
typedef basic_ofstream<wchar_t, char_traits<wchar_t> > wofstream;
The type is a synonym for template class basic_ofstream,
specialized for elements of type wchar_t with default character
traits.
<functional>
binary_function . binary_negate . binder1st . binder2nd . divides .
equal_to . greater .
greater_equal . less . less_equal .
logical_and .
logical_not . logical_or . mem_fun_t . mem_fun_ref_t
. mem_fun1 .
mem_fun1_ref_t . minus . modulus . multiplies . negate
. not_equal_to . plus . pointer_to_binary_function .
pointer_to_unary_function . unary_function . unary_negate
bind1st . bind2nd . mem_fun . mem_fun_ref . mem_fun1 . mem_fun1_ref
. not1 . not2 . ptr_fun
namespace std {
// TEMPLATE CLASSES
template<class Arg, class Result>
struct unary_function;
template<class Arg1, class Arg2, class Result>
struct binary_function;
template<class T>
struct plus;
template<class T>
struct minus;
template<class T>
struct multiplies;
template<class T>
struct divides;
file:///D|/97/c++_1/LIBREF.TXT (85 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 85 of 619
template<class T>
struct modulus;
template<class T>
struct negate;
template<class T>
struct equal_to;
template<class T>
struct not_equal_to;
template<class T>
struct greater;
template<class T>
struct less;
template<class T>
struct greater_equal;
template<class T>
struct less_equal;
template<class T>
struct logical_and;
template<class T>
struct logical_or;
template<class T>
struct logical_not;
template<class Pred>
struct unary_negate;
template<class Pred>
struct binary_negate;
template<class Pred>
class binder1st;
template<class Pred>
class binder2nd;
template<class Arg, class Result>
class pointer_to_unary_function;
template<class Arg1, class Arg2, class Result>
class pointer_to_binary_function;
template<class R, class T>
struct mem_fun_t;
template<class R, class T, class A>
struct mem_fun1_t;
template<class R, class T>
struct mem_fun_ref_t;
template<class R, class T, class A>
struct mem_fun1_ref_t;
// TEMPLATE FUNCTIONS
template<class Pred>
unary_negate<Pred> not1(const Pred& pr);
template<class Pred>
binary_negate<Pred> not2(const Pred& pr);
template<class Pred, class T>
binder1st<Pred> bind1st(const Pred& pr, const T& x);
template<class Pred, class T>
binder2nd<Pred> bind2nd(const Pred& pr, const T& x);
template<class Arg, class Result>
pointer_to_unary_function<Arg, Result>
ptr_fun(Result (*)(Arg));
template<class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1, Arg2, Result>
ptr_fun(Result (*)(Arg1, Arg2));
file:///D|/97/c++_1/LIBREF.TXT (86 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 86 of 619
template<class R, class T>
mem_fun_t<R, T> mem_fun(R (T::*pm)());
template<class R, class T, class A>
mem_fun1_t<R, T, A> mem_fun1(R (T::*pm)(A arg));
template<class R, class T>
mem_fun_ref_t<R, T> mem_fun_ref(R (T::*pm)());
template<class R, class T, class A>
mem_fun1_ref_t<R, T, A> mem_fun1_ref(R (T::*pm)(A arg));
};
Include the STL standard header <functional> to define several
templates that help construct function objects, objects of a class
that defines operator(). Hence, function objects behave much like
function pointers, except that the object can store additional
information that can be used during a function call.
binary_function
template<class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
The template class serves as a base for classes that define a
member function of the form:
result_type operator()(first_argument_type, second_argument_type)
Hence, all such binary functions can refer to their first argument
type as first_argument_type, their second argument type as
second_argument_type, and their return type as result_type.
See the related sample program.
binary_negate
template<class Pred>
class binary_negate
: public binary_function<Pred::first_argument_type,
Pred::second_argument_type, bool> {
public:
explicit binary_negate(const Pred& pr);
bool operator()(const first_argument_type& x,
const second_argument_type& y) const;
};
The template class stores a copy of pr, which must be a binary
function object. It defines its member function operator() as
returning !pr(x, y).
bind1st
template<class Pred, class T>
binder1st<Pred> bind1st(const Pred& pr, const T& x);
file:///D|/97/c++_1/LIBREF.TXT (87 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 87 of 619
The function returns binder1st<Pred>(pr, Pred::first_argument_type
(x)).
bind2nd
template<class Pred, class T>
binder2nd<Pred> bind2nd(const Pred& pr, const T& y);
The function returns binder2nd<Pred>(pr, Pred::second_argument_type
(y)).
binder1st
template<class Pred>
class binder1st
: public unary_function<Pred::second_argument_type,
Pred::result_type> {
public:
binder1st(const Pred& pr, const Pred::first_argument_type x);
result_type operator()(const argument_type& y) const;
protected:
Pred op;
Pred::first_argument_type value;
};
The template class stores a copy of pr, which must be a binary
function object, in op, and a copy of x in value. It defines its
member function operator() as returning op(value, y).
binder2nd
template<class Pred>
class binder2nd
: public unary_function<Pred::first_argument_type,
Pred::result_type> {
public:
binder2nd(const Pred& pr, const Pred::second_argument_type y);
result_type operator()(const argument_type& x) const;
protected:
Pred op;
Pred::second_argument_type value;
};
The template class stores a copy of pr, which must be a binary
function object, in op, and a copy of y in value. It defines its
member function operator() as returning op(x, value).
divides
template<class T>
struct divides : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x / y.
file:///D|/97/c++_1/LIBREF.TXT (88 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 88 of 619
See the related sample program.
equal_to
template<class T>
struct equal_to : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x == y.
greater
template<class T>
struct greater : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x > y.
The member function defines a total ordering, even if T is an
object pointer type.
greater_equal
template<class T>
struct greater_equal : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x >= y.
The member function defines a total ordering, even if T is an
object pointer type.
less
template<class T>
struct less : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x < y.
The member function defines a total ordering, even if T is an
object pointer type.
less_equal
template<class T>
struct less_equal : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x <= y.
The member function defines a total ordering, even if T is an
object pointer type.
logical_and
file:///D|/97/c++_1/LIBREF.TXT (89 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 89 of 619
template<class T>
struct logical_and : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x && y.
logical_not
template<class T>
struct logical_not : public unary_function<T, bool> {
bool operator()(const T& x) const;
};
The template class defines its member function as returning !x.
logical_or
template<class T>
struct logical_or : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x || y.
mem_fun
template<class R, class T>
mem_fun_t<R, T> mem_fun(R (T::*pm)());
The template function returns mem_fun_t<R, T>(pm).
mem_fun_ref
template<class R, class T>
mem_fun_ref_t<R, T> mem_fun_ref(R (T::*pm)());
The template function returns mem_fun_ref_t<R, T>(pm).
mem_fun_ref_t
template<class R, class T>
struct mem_fun_ref_t : public unary_function<T *, R> {
explicit mem_fun_t(R (T::*pm)());
R operator()(T& x);
};
The template class stores a copy of pm, which must be a pointer to
a member function of class T, in a private member object. It
defines its member function operator() as returning (x.*Pm)().
mem_fun_t
template<class R, class T>
struct mem_fun_t : public unary_function<T *, R> {
explicit mem_fun_t(R (T::*pm)());
file:///D|/97/c++_1/LIBREF.TXT (90 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 90 of 619
R operator()(T *p);
};
The template class stores a copy of pm, which must be a pointer to
a member function of class T, in a private member object. It
defines its member function operator() as returning (p->*pm)().
mem_fun1
template<class R, class T, class A>
mem_fun1_t<R, T, A> mem_fun1(R (T::*pm)(A));
The template function returns mem_fun1_t<R, T, A>(pm).
mem_fun1_ref
template<class R, class T, class A>
mem_fun1_ref_t<R, T, A> mem_fun1_ref(R (T::*pm)(A));
The template function returns mem_fun1_ref_t<R, T, A>(pm).
mem_fun1_ref_t
template<class R, class T, class A>
struct mem_fun1_ref_t : public binary_function<T *, A, R> {
explicit mem_fun1_ref_t(R (T::*pm)(A));
R operator()(T& x, A arg);
};
The template class stores a copy of pm, which must be a pointer to
a member function of class T, in a private member object. It
defines its member function operator() as returning (x.*pm)(arg).
mem_fun1_t
template<class R, class T, class A>
struct mem_fun1_t : public binary_function<T *, A, R> {
explicit mem_fun1_t(R (T::*pm)(A));
R operator()(T *p, A arg);
};
The template class stores a copy of pm, which must be a pointer to
a member function of class T, in a private member object. It
defines its member function operator() as returning (p->*pm)(arg).
minus
template<class T>
struct minus : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x - y.
See the related sample program.
modulus
file:///D|/97/c++_1/LIBREF.TXT (91 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 91 of 619
template<class T>
struct modulus : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x % y.
See the related sample program.
multiplies
template<class T>
struct multiplies : public binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x * y.
See the related sample program.
negate
template<class T>
struct negate : public unary_function<T, T> {
T operator()(const T& x) const;
};
The template class defines its member function as returning -x.
not1
template<class Pred>
unary_negate<Pred> not1(const Pred& pr);
The template function returns unary_negate<Pred>(pr).
not2
template<class Pred>
binary_negate<Pred> not2(const Pred& pr);
The template function returns binary_negate<Pred>(pr).
not_equal_to
template<class T>
struct not_equal_to : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x != y.
plus
template<class T>
struct plus : public binary_function<T, T, T> {
file:///D|/97/c++_1/LIBREF.TXT (92 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 92 of 619
T operator()(const T& x, const T& y) const;
};
The template class defines its member function as returning x + y.
See the related sample program.
pointer_to_binary_function
template<class Arg1, class Arg2, class Result>
class pointer_to_binary_function
: public binary_function<Arg1, Arg2, Result> {
public:
explicit pointer_to_binary_function(Result (*pf)(Arg1, Arg2));
Result operator()(const Arg1 x, const Arg2 y) const;
};
The template class stores a copy of pf. It defines its member
function operator() as returning (*pf)(x, y).
pointer_to_unary_function
template<class Arg, class Result>
class pointer_to_unary_function
: public unary_function<Arg, Result> {
public:
explicit pointer_to_unary_function(Result (*pf)(Arg));
Result operator()(const Arg x) const;
};
The template class stores a copy of pf. It defines its member
function operator() as returning (*pf)(x).
ptr_fun
template<class Arg, class Result>
pointer_to_unary_function<Arg, Result>
ptr_fun(Result (*pf)(Arg));
template<class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1, Arg2, Result>
ptr_fun(Result (*pf)(Arg1, Arg2));
The first template function returns pointer_to_unary_function<Arg,
Result>(pf).
The second template function returns
pointer_to_binary_function<Arg1, Arg2, Result>(pf).
unary_function
template<class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
The template class serves as a base for classes that define a
file:///D|/97/c++_1/LIBREF.TXT (93 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 93 of 619
member function of the form:
result_type operator()(argument_type)
Hence, all such unary functions can refer to their sole argument
type as argument_type and their return type as result_type.
See the related sample program.
unary_negate
template<class Pred>
class unary_negate
: public unary_function<Pred::argument_type, bool> {
public:
explicit unary_negate(const Pred& pr);
bool operator()(const argument_type& x) const;
};
The template class stores a copy of pr, which must be a unary
function object. It defines its member function operator() as
returning !pr(x).
<iomanip>
namespace std {
// MANIPULATORS
T1 resetiosflags(ios_base::fmtflags mask);
T2 setiosflags(ios_base::fmtflags mask);
T3 setbase(int base);
template<class E>
T4 setfill(E c);
T5 setprecision(int n);
T6 setw(int n);
};
Include the iostreams standard header <iomanip> to define several
manipulators that each take a single argument. Each of these
manipulators returns an unspecified type, called T1 through T6
here, that overloads both basic_istream<E, T>::operator>> and
basic_ostream<E, T>::operator<<. Thus, you can write extractors and
inserters such as:
cin >> setbase(8);
cout << setbase(8);
resetiosflags
T1 resetiosflags(ios_base::fmtflags mask);
The manipulator returns an object that, when extracted from or
inserted into the stream str, calls str.setf(ios_base:: fmtflags(),
mask), then returns str.
setiosflags
T2 setiosflags(ios_base::fmtflags mask);
file:///D|/97/c++_1/LIBREF.TXT (94 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 94 of 619
The manipulator returns an object that, when extracted from or
inserted into the stream str, calls str.setf(mask), then returns
str.
setbase
T3 setbase(int base);
The manipulator returns an object that, when extracted from or
inserted into the stream str, calls str.setf(mask,
ios_base::basefield), then returns str. Here, mask is determined as
follows:
lIf base is 8, then mask is ios_base::oct.
lIf base is 10, then mask is ios_base::dec.
lIf base is 16, then mask is ios_base::hex.
lIf base is any other value, then mask is ios_base::fmtflags(0).
setfill
template<class E>
T4 setfill(E fillch);
The template manipulator returns an object that, when extracted
from or inserted into the stream str, calls str.fill(fillch), then
returns str. The type E must be the same as the element type for
the stream str.
setprecision
T5 setprecision(int prec);
The manipulator returns an object that, when extracted from or
inserted into the stream str, calls str.precision(prec), then
returns str.
setw
T6 setw(int wide);
The manipulator returns an object that, when extracted from or
inserted into the stream str, calls str.width(wide), then returns
str.
<ios>
basic_ios . fpos .
ios . ios_base . streamoff . streampos .
streamsize . wios . wstreampos
boolalpha . dec . fixed . hex . internal . left . noboolalpha .
noshowbase . noshowpoint . noshowpos . noskipws . nounitbuf .
nouppercase . oct . right . scientific . showbase . showpoint .
showpos . skipws . unitbuf . uppercase
namespace std {
typedef T1 streamoff;
file:///D|/97/c++_1/LIBREF.TXT (95 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 95 of 619
typedef T2 streamsize;
class ios_base;
// TEMPLATE CLASSES
template <class E, class T = char_traits<E> >
class basic_ios;
typedef basic_ios<char, char_traits<char> > ios;
typedef basic_ios<wchar_t, char_traits<wchar_t> > wios;
template <class St>
class fpos;
typedef fpos<mbstate_t> streampos;
typedef fpos<mbstate_t> wstreampos;
// MANIPULATORS
ios_base& boolalpha(ios_base& str);
ios_base& noboolalpha(ios_base& str);
ios_base& showbase(ios_base& str);
ios_base& noshowbase(ios_base& str);
ios_base& showpoint(ios_base& str);
ios_base& noshowpoint(ios_base& str);
ios_base& showpos(ios_base& str);
ios_base& noshowpos(ios_base& str);
ios_base& skipws(ios_base& str);
ios_base& noskipws(ios_base& str);
ios_base& unitbuf(ios_base& str);
ios_base& nounitbuf(ios_base& str);
ios_base& uppercase(ios_base& str);
ios_base& nouppercase(ios_base& str);
ios_base& internal(ios_base& str);
ios_base& left(ios_base& str);
ios_base& right(ios_base& str);
ios_base& dec(ios_base& str);
ios_base& hex(ios_base& str);
ios_base& oct(ios_base& str);
ios_base& fixed(ios_base& str);
ios_base& scientific(ios_base& str);
};
Include the iostreams standard header <ios> to define several types
and functions basic to the operation of iostreams. (This header is
typically included for you by another of the iostreams headers. You
seldom have occasion to include it directly.)
A large group of functions are manipulators. The manipulators
declared in <ios> alter the values stored in its argument object of
class ios_base. Other manipulators perform actions on streams
controlled by objects of a type derived from this class, such as a
specialization of one of the template classes basic_istream or
basic_ostream. For example, noskipws(istr) clears the format flag
ios_base::skipws in the object istr, which might be of type
istream.
You can also call a manipulator by inserting it into an output
stream or extracting it from an input stream, thanks to some
special machinery supplied in the classes derived from ios_base.
For example:
istr >> noskipws;
file:///D|/97/c++_1/LIBREF.TXT (96 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 96 of 619
calls noskipws(istr).
basic_ios
bad . basic_ios . char_type .
clear . copyfmt . eof . exceptions .
fail . good . imbue . init . int_type . narrow . off_type .
operator! . operator void * . pos_type . rdbuf . rdstate . setstate
. tie . widen
template <class E, class T = char_traits<E> >
class basic_ios : public ios_base {
public:
typedef E char_type;
typedef T::int_type int_type;
typedef T::pos_type pos_type;
typedef T::off_type off_type;
explicit basic_ios(basic_streambuf<E, T>* sb);
virtual ~basic_ios();
operator void *() const;
bool operator!() const;
iostate rdstate() const;
void clear(iostate state = goodbit);
void setstate(iostate state);
bool good() const;
bool eof() const;
bool fail() const;
bool bad() const;
iostate exceptions() const;
iostate exceptions(iostate except);
basic_ios& copyfmt(const basic_ios& rhs);
E fill() const;
E fill(E ch);
basic_ostream<E, T> *tie() const;
basic_ostream<E, T> *tie(basic_ostream<E, T> *str);
basic_streambuf<E, T> *rdbuf() const;
basic_streambuf<E, T> *rdbuf(basic_streambuf<E, T> *sb);
basic_ios& copyfmt(const basic_ios& rhs);
locale imbue(const locale& loc);
E widen(char ch);
char narrow(E ch, char dflt);
protected:
basic_ios();
void init(basic_streambuf<E, T>* sb);
};
The template class describes the storage and member functions
common to both input streams (of template class basic_istream) and
output streams (of template class basic_ostream) that depend on the
template parameters. (The class ios_base describes what is common
and not dependent on template parameters. An object of class
basic_ios<E, T> helps control a stream with elements of type E,
whose character traits are determined by the class T.
An object of class basic_ios<E, T> stores:
lformatting information and stream state information in a base
file:///D|/97/c++_1/LIBREF.TXT (97 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 97 of 619
object of type ios_base
la fill character in an object of type E
la tie pointer to an object of type basic_ostream<E, T>
la stream buffer pointer to an object of type basic_streambuf<E,
T>
basic_ios::bad
bool bad() const;
The member function returns true if rdstate() & badbit.
basic_ios::basic_ios
explicit basic_ios(basic_streambuf<E, T>* sb);
basic_ios();
The first constructor initializes its member objects by calling
init(sb). The second (protected) constructor leaves its member
objects uninitialized. A later call to init must initialize the
object before it can be safely destroyed.
basic_ios::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
basic_ios::clear
void clear(iostate state = goodbit);
The member function replaces the stored stream state information
with state | (rdbuf() != 0 ? goodbit : badbit). If state &
exceptions() is nonzero, it then throws an object of class failure.
basic_ios::copyfmt
basic_ios& copyfmt(const basic_ios& rhs);
The member function reports the callback event erase_event. It then
copies the fill character, the tie pointer, and the formatting
information from rhs into *this. Before altering the exception
mask, it reports the callback event copyfmt_event. If, after the
copy is complete, state & exceptions() is nonzero, the function
effectively calls clear with the argument rdstate(). It returns
*this.
basic_ios::eof
bool eof() const;
The member function returns true if rdstate() & eofbit.
basic_ios::exceptions
iostate exceptions() const;
file:///D|/97/c++_1/LIBREF.TXT (98 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 98 of 619
iostate exceptions(iostate except);
The first member function returns the stored exception mask. The
second member function stores except in the exception mask and
returns its previous stored value. Note that storing a new
exception mask can throw an exception just like the call clear
( rdstate()).
basic_ios::fail
bool fail() const;
The member function returns true if rdstate() & failbit.
basic_ios::fill
E fill() const;
E fill(E ch);
The first member function returns the stored fill character. The
second member function stores ch in the fill character and returns
its previous stored value.
basic_ios::good
bool good() const;
The member function returns true if rdstate() == goodbit (no state
flags are set).
basic_ios::imbue
locale imbue(const locale& loc);
If rdbuf is not a null pointer, the member function calls rdbuf()-
>pubimbue(loc). In any case, it returns ios_base::imbue(loc).
basic_ios::init
void init(basic_streambuf<E, T>* sb);
The member function stores values in all member objects, so that:
lrdbuf() returns sb
ltie() returns a null pointer
lrdstate() returns goodbit if sb is nonzero; otherwise, it
returns badbit
lexceptions() returns goodbit
lflags() returns skipws | dec
lwidth() returns zero
lprecision() returns 6
lfill() returns the space character
lgetloc() returns locale::classic()
liword returns zero and pword returns a null pointer for all
argument values
basic_ios::int_type
file:///D|/97/c++_1/LIBREF.TXT (99 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 99 of 619
typedef T::int_type int_type;
The type is a synonym for T::int_type.
basic_ios::narrow
char narrow(E ch, char dflt);
The member function returns use_facet< ctype<E> >( getloc()).
narrow(ch, dflt).
basic_ios::off_type
typedef T::off_type off_type;
The type is a synonym for T::off_type.
basic_ios::operator void *
operator void *() const;
The operator returns a null pointer only if fail().
basic_ios::operator!
bool operator!() const;
The operator returns fail().
basic_ios::pos_type
typedef T::pos_type pos_type;
The type is a synonym for T::pos_type.
basic_ios::rdbuf
basic_streambuf<E, T> *rdbuf() const;
basic_streambuf<E, T> *rdbuf(basic_streambuf<E, T> *sb);
The member function returns the stored stream buffer pointer.
basic_ios::rdstate
iostate rdstate() const;
The member function returns the stored stream state information.
basic_ios::setstate
void setstate(iostate state);
The member function effectively calls clear(state | rdstate()).
basic_ios::tie
file:///D|/97/c++_1/LIBREF.TXT (100 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 100 of 619
basic_ostream<E, T> *tie() const;
basic_ostream<E, T> *tie(basic_ostream<E, T> *str);
The first member function returns the stored tie pointer. The
second member function stores str in the tie pointer and returns
its previous stored value.
basic_ios::widen
E narrow(char ch);
The member function returns use_facet< ctype<E> >( getloc()). widen
(ch).
boolalpha
ios_base& boolalpha(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: boolalpha),
then returns str.
dec
ios_base& dec(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: dec,
ios_base:: basefield), then returns str.
fixed
ios_base& fixed(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: fixed,
ios_base:: floatfield), then returns str.
fpos
template <class St>
class fpos {
public:
fpos(St state, fpos_t fposn);
fpos(streamoff off);
fpos_t get_fpos_t() const;
St state() const;
void state(St state);
operator streamoff() const;
streamoff operator-(const fpos<St>& rhs) const;
fpos<St>& operator+=(streamoff off);
fpos<St>& operator-=(streamoff off);
fpos<St> operator+(streamoff off) const;
fpos<St> operator-(streamoff off) const;
bool operator==(const fpos<St>& rhs) const;
bool operator!=(const fpos<St>& rhs) const;
};
The template class describes an object that can store all the
file:///D|/97/c++_1/LIBREF.TXT (101 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 101 of 619
information needed to restore an arbitrary file-position indicator
within any stream. An object of class fpos<St> effectively stores
three member objects:
lA byte offset, of type streamoff
lAn arbitrary file position, for use by an object of class
basic_filebuf, of type fpos_t
lA conversion state, for use by an object of class
basic_filebuf, of type St, typically mbstate_t
For an environment with limited file size, however, streamoff and
fpos_t may sometimes be used interchangeably. And for an
environment with no streams that have a state-dependent encoding,
mbstate_t may actually be unused. So the number of member objects
stored may well vary from one to three.
fpos::fpos
fpos(St state, fpos_t fposn);
fpos(streamoff off);
The first constructor stores a zero offset and the objects state
and fposn. The second constructor stores the offset off, relative
to the beginning of file and in the initial conversion state (if
that matters). If off is -1, the resulting object represents an
invalid stream position.
fpos::get_fpos_t
fpos_t get_fpos_t() const;
returns the value stored in the fpos_t member object.
fpos::operator!=
bool operator!=(const fpos<St>& rhs) const;
The member function returns !(*this == rhs).
fpos::operator+
fpos<St> operator+(streamoff off) const;
The member function returns fpos<St>(*this) += off.
fpos::operator+=
fpos<St>& operator+=(streamoff off);
The member function adds off to the stored offset member object,
then returns *this. For positioning within a file, the result is
generally valid only for binary streams that do not have a state-
dependent encoding.
fpos::operator-
streamoff operator-(const fpos<St>& rhs) const;
file:///D|/97/c++_1/LIBREF.TXT (102 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 102 of 619
fpos<St> operator-(streamoff off) const;
The first member function returns (streamoff)*this - (streamoff)
rhs. The second member function returns fpos<St>(*this) -= off.
fpos::operator-=
fpos<St>& operator-=(streamoff off);
The member function returns fpos<St>(*this) -= off. For positioning
within a file, the result is generally valid only for binary
streams that do not have a state-dependent encoding.
fpos::operator==
bool operator==(const fpos<St>& rhs) const;
The member function returns (streamoff)*this == (streamoff)rhs.
fpos::operator streamoff
operator streamoff() const;
The member function returns the stored offset member object, plus
any additional offset stored as part of the fpos_t member object.
fpos::state
St state() const;
void state(St state);
The first member function returns the value stored in the St member
object. The second member function stores state in the St member
object.
hex
ios_base& hex(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: hex,
ios_base:: basefield), then returns str.
internal
ios_base& internal(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: internal,
ios_base:: adjustfield), then returns str.
ios
typedef basic_ios<char, char_traits<char> > ios;
The type is a synonym for template class basic_ios, specialized for
elements of type char with default character
ios_base
file:///D|/97/c++_1/LIBREF.TXT (103 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 103 of 619
event . event_callback . failure .
flags . fmtflags . getloc .
imbue . Init . ios_base . iostate . iword . openmode . operator= .
precision . pword .
register_callback . seekdir . setf .
sync_with_stdio . unsetf . width . xalloc
class ios_base {
public:
class failure;
typedef T1 fmtflags;
static const fmtflags boolalpha, dec, fixed, hex, internal,
left, oct, right, scientific, showbase, showpoint,
showpos, skipws, unitbuf, uppercase, adjustfield,
basefield, floatfield;
typedef T2 iostate;
static const iostate badbit, eofbit, failbit, goodbit;
typedef T3 openmode;
static const openmode app, ate, binary, in, out, trunc;
typedef T4 seekdir;
static const seekdir beg, cur, end;
typedef T5 event;
static const event copyfmt_event, erase_event,
copyfmt_event;
class Init;
ios_base& operator=(const ios_base& rhs);
fmtflags flags() const;
fmtflags flags(fmtflags fmtfl);
fmtflags setf(fmtflags fmtfl);
fmtflags setf(fmtflags fmtfl, fmtflags mask);
void unsetf(fmtflags mask);
streamsize precision() const;
streamsize precision(streamsize prec);
streamsize width() const;
stramsize width(streamsize wide);
locale imbue(const locale& loc);
locale getloc() const;
static int xalloc();
long& iword(int idx);
void *& pword(int idx);
typedef void *(event_callback(event ev, ios_base& ios, int idx);
void register_callback(event_callback pfn, int idx);
static bool sync_with_stdio(bool sync = true);
protected:
ios_base();
};
The class describes the storage and member functions common to both
input and output streams that do not depend on the template
parameters. (The template class basic_ios describes what is common
and is dependent on template parameters.)
An object of class ios_base stores formatting information, which
consists of:
lFormat flags in an object of type fmtflags
lAn exception mask in an object of type iostate
lA field width in an object of type int
file:///D|/97/c++_1/LIBREF.TXT (104 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 104 of 619
lA display precision in an object of type int
lA locale object in an object of type locale
lTwo extensible arrays, with elements of type long and void
An object of class ios_base also stores stream state information,
in an object of type iostate, and a callback stack.
ios_base::event
typedef T5 event;
static const event copyfmt_event, erase_event,
imbue_event;
The type is an enumerated type T5 that describes an object that can
store the callback event used as an argument to a function
registered with register_callback. The distinct event values are:
lcopyfmt_event, to identify a callback that occurs near the end
of a call to copyfmt, just before the exception mask is copied.
lerase_event, to identify a callback that occurs at the
beginning of a call to copyfmt, or at the beginning of a call
to the destructor for *this.
limbue_event, to identify a callback that occurs at the end of a
call to imbue, just before the function returns.
ios_base::event_callback
typedef void *(event_callback(event ev, ios_base& ios, int idx);
The type describes a pointer to a function that can be registered
with register_callback.
ios_base::failure
class failure : public exception {
public:
explicit failure(const string& what_arg) {
};
The member class serves as the base class for all exceptions thrown
by the member function clear in template class basic_ios. The value
returned by what() is what_arg.data().
ios_base::flags
fmtflags flags() const;
fmtflags flags(fmtflags fmtfl);
The first member function returns the stored format flags. The
second member function stores fmtfl in the format flags and returns
its previous stored value.
ios_base::fmtflags
typedef T1 fmtflags;
static const fmtflags boolalpha, dec, fixed, hex, internal,
left, ,
oct right, scientific, showbase, showpoint,
file:///D|/97/c++_1/LIBREF.TXT (105 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 105 of 619
showpos, skipws, unitbuf, uppercase, adjustfield,
basefield, floatfield;
The type is an enumerated type T1 that describes an object that can
store format flags. The distinct flag values are:
lboolalpha, to insert or extract objects of type bool as
(such as true and false) rather than as numeric values.
ldec, to insert or extract integer values in decimal format.
lfixed, to insert floating-point values in fixed-point format
(with no exponent field).
lhex, to insert or extract integer values in hexadecimal format.
linternal, to pad to a field width as needed by inserting fill
characters at a point internal to a generated numeric field.
lleft, to pad to a field width as needed by inserting fill
characters at the end of a generated field (left
justification).
loct, to insert or extract integer values in octal format.
lright, to pad to a field width as needed by inserting fill
characters at the beginning of a generated field (right
justification).
lscientific, to insert floating-point values in scientific
format (with an exponent field).
lshowbase, to insert a prefix that reveals the base of a
generated integer field.
lshowpoint, to insert a decimal point unconditionally in a
generated floating-point field.
lshowpos, to insert a plus sign in a non-negative generated
numeric field.
lskipws, to skip leading white space before certain extractions.
lunitbuf, to flush output after each insertion.
luppercase, to insert uppercase equivalents of lowercase letters
in certain insertions.
In addition, several useful values are:
ladjustfield, internal | left | right
lbasefield, dec | hex | oct
lfloatfield, fixed | scientific
ios_base::getloc
locale getloc() const;
The member function returns the stored locale object.
ios_base::imbue
locale imbue(const locale& loc);
The member function stores loc in the locale object, then reports
the callback event imbue_event. It returns the previous stored
value.
ios_base::Init
class Init {
file:///D|/97/c++_1/LIBREF.TXT (106 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 106 of 619
};
The nested class describes an object whose construction ensures
that the standard iostreams objects are properly constructed, even
during the execution of a constructor for an arbitrary static
object.
ios_base::ios_base
ios_base();
The (protected) constructor does nothing. A later call to
basic_ios::init must initialize the object before it can be safely
destroyed. Thus, the only safe use for class ios_base is as a base
class for template class basic_ios.
ios_base::iostate
typedef T2 iostate;
static const iostate badbit, eofbit, failbit, goodbit;
The type is an enumerated type T2 that describes an object that can
store stream state information. The distinct flag values are:
lbadbit, to record a loss of integrity of the stream buffer
leofbit, to record end-of-file while extracting from a stream
lfailbit, to record a failure to extract a valid field from a
stream
In addition, a useful value is:
lgoodbit, no bits set
ios_base::iword
long& iword(int idx);
The member function returns a reference to element idx of the
extensible array with elements of type long. All elements
effectively present and initially store the value zero. The
returned reference is invalid after the next call to iword for the
object, after the object is altered by a call to
basic_ios::copyfmt, or after the object is destroyed.
To obtain a unique index for use across all objects of type
ios_base, call xalloc.
ios_base::openmode
typedef T3 openmode;
static const openmode app, ate, binary, in, out, trunc;
The type is an enumerated type T3 that describes an object that can
store the opening mode for several iostreams objects. The distinct
flag values are:
lapp, to seek to the end of a stream before each insertion
file:///D|/97/c++_1/LIBREF.TXT (107 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 107 of 619
late, to seek to the end of a stream when its controlling object
is first created
lbinary, to read a file as a binary stream, rather than as a
text stream
lin, to permit extraction from a stream
lout, to permit insertion to a stream
ltrunc, to truncate an existing file when its controlling object
is first created
ios_base::operator=
ios_base& operator=(const ios_base& rhs) const;
The operator copies the stored formatting information, making a new
copy of any extensible arrays. It then returns *this. Note that the
callback stack is not copied.
ios_base::precision
streamsize precision() const;
streamsize precision(streamsize prec);
The first member function returns the stored display precision. The
second member function stores prec in the display precision and
returns its previous stored value.
ios_base::pword
void *& pword(int idx);
The member function returns a reference to element idx of the
extensible array with elements of type void pointer. All elements
effectively present and initially store the null pointer. The
returned reference is invalid after the next call to pword for the
object, after the object is altered by a call to
basic_ios::copyfmt, or after the object is destroyed.
To obtain a unique index for use across all objects of type
ios_base, call xalloc.
ios_base::register_callback
void register_callback(event_callback pfn, int idx);
The member function pushes the pair {pfn, idx} onto the stored
callback stack. When a callback event ev is reported, the functions
are called, in reverse order of registry, by the expression (*pfn)
(ev, *this, idx).
ios_base::seekdir
typedef T4 seekdir;
static const seekdir beg, cur, end;
The type is an enumerated type T4 that describes an object that can
store the seek mode used as an argument to the member functions of
several iostreams classes. The distinct flag values are:
file:///D|/97/c++_1/LIBREF.TXT (108 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 108 of 619
lbeg, to seek (alter the current read or write position)
relative to the beginning of a sequence (array, stream, or
file)
lcur, to seek relative to the current position within a sequence
lend, to seek relative to the end of a sequence
ios_base::setf
void setf(fmtflags mask);
fmtflags setf(fmtflags fmtfl, fmtflags mask);
The first member function effectively calls flags(mask | flags())
(set selected bits), then returns the previous format flags. The
second member function effectively calls flags(mask & fmtfl, flags
() & ~mask) (replace selected bits under a mask), then returns the
previous format flags.
ios_base::sync_with_stdio
static bool sync_with_stdio(bool sync = true);
The static member function stores a stdio sync flag, which is
initially true. When true, this flag ensures that operations on the
same file are properly synchronized between the iostreams functions
and those defined in the Standard C library. Otherwise,
synchronization may or may not be guaranteed, but performance may
be improved. The function stores sync in the stdio sync flag and
returns its previous stored value. You can call it reliably only
before performing any operations on the standard streams.
ios_base::unsetf
void unsetf(fmtflags mask);
The member function effectively calls flags(~mask & flags()) (clear
selected bits).
ios_base::width
streamsize width() const;
streamsize width(streamsize wide);
The first member function returns the stored field width. The
second member function stores wide in the field width and returns
its previous stored value.
ios_base::xalloc
static int xalloc();
The static member function returns a stored static value, which it
increments on each call. You can use the return value as a unique
index argument when calling the member functions iword or pword.
left
file:///D|/97/c++_1/LIBREF.TXT (109 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 109 of 619
ios_base& left(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: left,
ios_base:: adjustfield), then returns str.
noboolalpha
ios_base& noboolalpha(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: boolalpha),
then returns str.
noshowbase
ios_base& noshowbase(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: showbase),
then returns str.
noshowpoint
ios_base& noshowpoint(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: showpoint),
then returns str.
noshowpos
ios_base& noshowpos(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: showpos),
then returns str.
noskipws
ios_base& noskipws(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: skipws),
then returns str.
nounitbuf
ios_base& nounitbuf(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: unitbuf),
then returns str.
nouppercase
ios_base& nouppercase(ios_base& str);
The manipulator effectively calls str.unsetf(ios_base:: uppercase),
then returns str.
oct
file:///D|/97/c++_1/LIBREF.TXT (110 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 110 of 619
ios_base& oct(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: oct,
ios_base:: basefield), then returns str.
right
ios_base& right(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: right,
ios_base:: adjustfield), then returns str.
scientific
ios_base& scientific(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: scientific,
ios_base:: floatfield), then returns str.
showbase
ios_base& showbase(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: showbase),
then returns str.
showpoint
ios_base& showpoint(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: showpoint),
then returns str.
showpos
ios_base& showpos(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: showpos),
then returns str.
skipws
ios_base& skipws(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: skipws), then
returns str.
streamoff
typedef T1 streamoff;
The type is a signed integer type T1 that describes an object that
can store a byte offset involved in various stream positioning
operations. Its representation has at least 32 value bits. It is
not necessarily large enough to represent an arbitrary byte
position within a stream. The value streamoff(-1) generally
file:///D|/97/c++_1/LIBREF.TXT (111 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 111 of 619
indicates an erroneous offset.
streampos
typedef fpos<mbstate_t> streampos;
The type is a synonym for fpos< mbstate_t>.
streamsize
typedef T2 streamsize;
The type is a signed integer type T3 that describes an object that
can store a count of the number of elements involved in various
stream operations. Its representation has at least 16 bits. It is
not necessarily large enough to represent an arbitrary byte
position within a stream.
unitbuf
ios_base& unitbuf(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: unitbuf),
then returns str.
uppercase
ios_base& uppercase(ios_base& str);
The manipulator effectively calls str.setf(ios_base:: uppercase),
then returns str.
wios
typedef basic_ios<wchar_t, char_traits<wchar_t> > wios;
The type is a synonym for template class basic_ios, specialized for
elements of type wchar_t with default character traits.
wstreampos
typedef fpos<mbstate_t> wstreampos;
The type is a synonym for fpos< mbstate_t>.
<iosfwd>
namespace std {
// TYPE DEFINITIONS
typedef T1 streamoff;
typedef T2 streampos;
// TEMPLATES
template<class E>
class char_traits;
class char_traits<char>;
class char_traits<wchar_t>;
template<class E, class T = char_traits<E> >
file:///D|/97/c++_1/LIBREF.TXT (112 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 112 of 619
class basic_ios;
template<class E, class T = char_traits<E> >
class istreambuf_iterator;
template<class E, class T = char_traits<E> >
class ostreambuf_iterator;
template<class E, class T = char_traits<E> >
class basic_streambuf;
template<class E, class T = char_traits<E> >
class basic_istream;
template<class E, class T = char_traits<E> >
class basic_ostream;
template<class E, class T = char_traits<E> >
class basic_iostream;
template<class E, class T = char_traits<E> >
class basic_stringbuf;
template<class E, class T = char_traits<E> >
class basic_istringstream;
template<class E, class T = char_traits<E> >
class basic_ostringstream;
template<class E, class T = char_traits<E> >
class basic_stringstream;
template<class E, class T = char_traits<E> >
class basic_filebuf;
template<class E, class T = char_traits<E> >
class basic_ifstream;
template<class E, class T = char_traits<E> >
class basic_ofstream;
template<class E, class T = char_traits<E> >
class basic_fstream;
// char TYPE DEFINITIONS
typedef basic_ios<char, char_traits<char> > ios;
typedef basic_streambuf<char, char_traits<char> > streambuf;
typedef basic_istream<char, char_traits<char> > istream;
typedef basic_ostream<char, char_traits<char> > ostream;
typedef basic_iostream<char, char_traits<char> > iostream;
typedef basic_stringbuf<char, char_traits<char> > stringbuf;
typedef basic_istringstream<char, char_traits<char> > istringstream;
typedef basic_ostringstream<char, char_traits<char> > ostringstream;
typedef basic_stringstream<char, char_traits<char> > stringstream;
typedef basic_filebuf<char, char_traits<char> > filebuf;
typedef basic_ifstream<char, char_traits<char> > ifstream;
typedef basic_ofstream<char, char_traits<char> > ofstream;
typedef basic_fstream<char, char_traits<char> > fstream;
// wchar_t TYPE DEFINITIONS
typedef basic_ios<wchar_t, char_traits<wchar_t> > wios;
typedef basic_streambuf<wchar_t, char_traits<wchar_t> > wstreambuf;
typedef basic_istream<wchar_t, char_traits<wchar_t> > wistream;
typedef basic_ostream<wchar_t, char_traits<wchar_t> > wostream;
typedef basic_iostream<wchar_t, char_traits<wchar_t> > wiostream;
typedef basic_stringbuf<wchar_t, char_traits<wchar_t> > wstringbuf;
typedef basic_istringstream<wchar_t, char_traits<wchar_t> > wistring
typedef basic_ostringstream<wchar_t, char_traits<wchar_t> > wostring
typedef basic_stringstream<wchar_t, char_traits<wchar_t> > wstringst
typedef basic_filebuf<wchar_t, char_traits<wchar_t> > wfilebuf;
typedef basic_ifstream<wchar_t, char_traits<wchar_t> > wifstream;
typedef basic_ofstream<wchar_t, char_traits<wchar_t> > wofstream;
typedef basic_fstream<wchar_t, char_traits<wchar_t> > wfstream;
file:///D|/97/c++_1/LIBREF.TXT (113 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 113 of 619
};
Include the iostreams standard header <iosfwd> to declare forward
references to several template classes used throughout iostreams.
All such template classes are defined in other standard headers.
You include this header explicitly only when you need one of the
above declarations, but not its definition.
<iostream>
namespace std {
extern istream cin;
extern ostream cout;
extern ostream cerr;
extern ostream clog;
extern wistream wcin;
extern wostream wcout;
extern wostream wcerr;
extern wostream wclog;
};
Include the iostreams standard header <iostream> to declare objects
that control reading from and writing to the standard streams. This
is often the only header you need include to perform input and
output from a C++ program.
The objects fall into two groups:
lcin, cout, cerr, and clog are byte oriented, performing
conventional byte-at-a-time transfers.
lwcin, wcout, wcerr, and wclog are wide oriented, translating to
and from the wide characters that the program manipulates
internally.
Once you perform certain operations on a stream, such as the
standard input, you cannot perform operations of a different
orientation on the same stream. A program cannot operate
interchangeably on both cin and wcin, for example.
All the objects declared in this header share a peculiar property:
You can assume they are constructed before any static objects you
define, in a translation unit that includes <iostreams>. Equally,
you can assume that these objects are not destroyed before the
destructors for any such static objects you define. (The output
streams are, however, flushed during program termination.) You can
safely read from or write to the standard streams prior to program
startup and after program termination.
This guarantee is not universal, however. A static constructor may
call a function in another translation unit. The called function
cannot assume that the objects declared in this header have been
constructed, given the uncertain order in which translation units
participate in static construction. To use these objects in such a
context, you must first construct an object of class
ios_base::Init, as in:
#include <iostream>
file:///D|/97/c++_1/LIBREF.TXT (114 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 114 of 619
using namespace std;
void marker()
{ // called by some constructor
ios_base::Init unused_name;
cout << "called fun" << endl;
}
cerr
extern ostream cerr;
The object controls unbuffered insertions to the standard error
output as a byte stream. Once the object is constructed, the
expression cerr.flags() & unitbuf is nonzero.
cin
extern istream cin;
The object controls extractions from the standard input as a byte
stream. Once the object is constructed, the call cin.tie() returns
&cout.
clog
extern ostream clog;
The object controls buffered insertions to the standard error
output as a byte stream.
cout
extern ostream cout;
The object controls insertions to the standard output as a byte
stream.
wcerr
extern wostream wcerr;
The object controls unbuffered insertions to the standard error
output as a wide stream. Once the object is constructed, the
expression wcerr.flags() & unitbuf is nonzero.
wcin
extern wistream wcin;
The object controls extractions from the standard input as a wide
stream. Once the object is constructed, the call wcin.tie() returns
&wcout.
wclog
file:///D|/97/c++_1/LIBREF.TXT (115 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 115 of 619
extern wostream wclog;
The object controls buffered insertions to the standard error
output as a wide stream.
wcout
extern wostream wcout;
The object controls insertions to the standard output as a wide
stream.
<istream>
namespace std {
// DECLARATIONS
template<class E, class T = char_traits<E> >
class basic_istream;
typedef basic_istream<char, char_traits<char> > istream;
typedef basic_istream<wchar_t, char_traits<wchar_t> > wistream;
template<class E, class T = char_traits<E> >
class basic_iostream;
typedef basic_iostream<char, char_traits<char> > iostream;
typedef basic_iostream<wchar_t, char_traits<wchar_t> > wiostream
// EXTRACTORS
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T> is, E *s
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T> is, E& c
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is
// MANIPULATOR
template class<E, T>
basic_istream<E, T>& ws(basic_istream<E, T> is);
};
Include the iostreams standard header <istream> to define template
class basic_istream, which mediates extractions for the iostreams,
and the template class basic_iostream, which mediates both
insertions and extractions. The header also defines a related
manipulator. (This header is typically included for you by another
of the iostreams headers. You seldom have occasion to include it
directly.)
basic_iostream
template <class E, class T = char_traits<E> >
class basic_iostream : public basic_istream<E, T>,
public basic_ostream<E, T> {
file:///D|/97/c++_1/LIBREF.TXT (116 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 116 of 619
public:
explicit basic_iostream(basic_streambuf<E, T> *sb);
virtual ~basic_iostream();
};
The template class describes an object that controls insertions,
through its base object basic_ostream<E, T>, and extractions,
through its base object basic_istream<E, T>. The two objects share
a common virtual base object basic_ios<E, T>. They also manage a
common stream buffer, with elements of type E, whose character
traits are determined by the class T. The constructor initializes
its base objects via basic_istream(sb) and basic_ostream(sb).
basic_istream
basic_istream . gcount . get . getline . ignore . ipfx . isfx .
operator>> . peek . putback . read . readsome . seekg . sentry .
sync . tellg . unget
template <class E, class T = char_traits<E> >
class basic_istream : virtual public basic_ios<E, T> {
public:
class sentry;
explicit basic_istream(basic_streambuf<E, T> *sb);
virtual ~istream();
bool ipfx(bool noskip = false);
void isfx();
basic_istream& operator>>(basic_istream& (*pf)(basic_istream&));
basic_istream& operator>>(basic_ios<E, T>& (*pf)(basic_ios<E, T>
basic_istream& operator>>(ios_base<E, T>& (*pf)(ios_base<E, T>&)
basic_istream& operator>>(basic_streambuf<E, T> *sb);
basic_istream& operator>>(bool& n);
basic_istream& operator>>(short& n);
basic_istream& operator>>(unsigned short& n);
basic_istream& operator>>(int& n);
basic_istream& operator>>(unsigned int& n);
basic_istream& operator>>(long& n);
basic_istream& operator>>(unsigned long& n);
basic_istream& operator>>(void *& n);
basic_istream& operator>>(float& n);
basic_istream& operator>>(double& n);
basic_istream& operator>>(long double& n);
streamsize gcount() const;
int_type get();
basic_istream& get(E& c);
basic_istream& get(E *s, streamsize n);
basic_istream& get(E *s, streamsize n, E delim);
basic_istream& get(basic_streambuf<E, T> *sb);
basic_istream& get(baiic_streambuf<E, T> *sb, E delim);
basic_istream& getline(E *s, streamsize n)E
basic_istream& getline(E *s, streamsize n, E delim);
basic_istream& ignore(streamsize n = 1,
int_type delim = T::eof());
int_type peek();
basic_istream& read(E *s, streamsize n);
streamsize readsome(E *s, streamsize n);
basic_istream& putback(E c);
file:///D|/97/c++_1/LIBREF.TXT (117 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 117 of 619
basic_istream& unget();
pos_type tellg();
basic_istream& seekg(pos_type pos);
basic_istream& seekg(off_type off, ios_base::seek_dir way);
int sync();
};
The template class describes an object that controls extraction of
elements and encoded objects from a stream buffer with elements of
type E, whose character traits are determined by the class T.
Most of the member functions that overload operator>> are formatted
input functions. They follow the pattern:
iostate state = goodbit;
const sentry ok(*this);
if (ok)
{try
{extract elements and convert
accumulate flags in state
store a successful conversion}
catch (...)
{if (exceptions() & badbit)
throw;
setstate(badbit); }}
setstate(state);
return (*this);
Many other member functions are unformatted input functions. They
follow the pattern:
iostate state = goodbit;
count = 0; // the value returned by gcount
const sentry ok(*this, true);
if (ok)
{try
{extract elements and deliver
count extracted elements in count
accumulate flags in state}
catch (...)
{if (rdstate() & badbit)
throw;
setstate(badbit); }}
setstate(state);
Both groups of functions call setstate(eofbit) if they encounter
end-of-file while extracting elements.
An object of class basic_istream<E, T> stores:
lA virtual public base object of class basic_ios<E, T>.
lAn extraction count for the last unformatted input operation
(called count in the code above).
basic_istream::basic_istream
explicit basic_istream(basic_streambuf<E, T> *sb);
file:///D|/97/c++_1/LIBREF.TXT (118 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 118 of 619
The constructor initializes the base class by calling init(sb). It
also stores zero in the extraction count.
basic_istream::gcount
streamsize gcount() const;
The member function returns the extraction count.
basic_istream::get
int_type get();
basic_istream& get(E& c);
basic_istream& get(E *s, streamsize n);
basic_istream& get(E *s, streamsize n, E delim);
basic_istream& get(basic_streambuf<E, T> *sb);
basic_istream& get(basic_streambuf<E, T> *sb, E delim);
The first of these unformatted input functions extracts an element,
if possible, as if by returning rdbuf()->sbumpc(). Otherwise, it
returns T::eof(). If the function extracts no element, it calls
setstate(failbit).
The second function extracts the int_type element x the same way.
If x compares equal to T::eof(x), the function calls setstate
(failbit). Otherwise, it stores T::to_char_type(x) in c. The
function returns *this.
The third function returns get(s, n, widen('\n')).
The fourth function extracts up to n - 1 elements and stores them
in the array beginning at s. It always stores E(0) after any
extracted elements it stores. Extraction stops early on end-of-file
or on an element that compares equal to delim (which is not
extracted). If the function extracts no elements, it calls setstate
(failbit). In any case, it returns *this.
The fifth function returns get(sb, widen('\n')).
The sixth function extracts elements and inserts them into sb.
Extraction stops on end-of-file or on an element that compares
equal to delim (which is not extracted). It also stops, without
extracting the element in question, if an insertion fails or throws
an exception (which is caught but not rethrown). If the function
extracts no elements, it calls setstate(failbit). In any case, the
function returns *this.
basic_istream::getline
basic_istream& getline(E *s, streamsize n);
basic_istream& getline(E *s, streamsize n, E delim);
The first of these unformatted input functions returns getline(s,
n, widen('\n')).
The second function extracts up to n - 1 elements and stores them
file:///D|/97/c++_1/LIBREF.TXT (119 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 119 of 619
in the array beginning at s. It always stores E(0) after any
extracted elements it stores. In order of testing, extraction
stops:
1.At end of file.
2.After the function extracts an element that compares equal to
delim, in which case the element is neither put back nor
appended to the controlled sequence.
3.After the function extracts is.max_size() elements.
If the function extracts no elements, it calls setstate(failbit).
In any case, it returns *this.
basic_istream::ignore
basic_istream& ignore(streamsize n = 1,
int_type delim = T::eof());
The unformatted input function extracts up to n elements and
discards them. If n equals numeric_limits<int>::max(), however, it
is taken as arbitrarily large. Extraction stops early on end-of-
file or on an element x such that T::to_int_type(x) compares equal
to delim (which is also extracted). The function returns *this.
basic_istream::ipfx
bool ipfx(bool noskip = false);
The member function prepares for formatted or unformatted input. If
good() is true, the function:
lCalls tie-> flush() if tie() is not a null pointer.
lEffectively calls ws(*this) if flags() & skipws is nonzero.
If, after any such preparation, good() is false, the function calls
setstate(failbit). In any case, the function returns good().
You should not call ipfx directly. It is called as needed by an
object of class sentry.
basic_istream::isfx
void isfx();
The member function has no official duties, but an implementation
may depend on a call to isfx by a formatted or unformatted input
function to tidy up after an extraction. You should not call isfx
directly. It is called as needed by an object of class sentry.
basic_istream::operator>>
basic_istream& operator>>(
basic_istream& (*pf)(basic_istream&));
basic_istream& operator>>(
basic_ios<E, T>& (*pf)(basic_ios<E, T>&));
basic_istream& operator>>(
ios_base<E, T>& (*pf)(ios_base<E, T>&));
file:///D|/97/c++_1/LIBREF.TXT (120 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 120 of 619
basic_istream& operator>>(
basic_streambuf<E, T> *sb);
basic_istream& operator>>(bool& n);
basic_istream& operator>>(short& n);
basic_istream& operator>>(unsigned short& n);
basic_istream& operator>>(int& n);
basic_istream& operator>>(unsigned int& n);
basic_istream& operator>>(long& n);
basic_istream& operator>>(unsigned long& n);
basic_istream& operator>>(void *& n);
basic_istream& operator>>(float& n);
basic_istream& operator>>(double& n);
basic_istream& operator>>(long double& n);
The first member function ensures that an expression of the form
istr >>: ws calls ws(istr), then returns *this. The second and
third functions ensure that other manipulators, such as hex, behave
similarly. The remaining functions constitute the formatted input
functions.
The function:
basic_istream& operator>>(
basic_streambuf<E, T> *sb);
extracts elements, if sb is not a null pointer, and inserts them
into sb. Extraction stops on end-of-file. It also stops, without
extracting the element in question, if an insertion fails or throws
an exception (which is caught but not rethrown). If the function
extracts no elements, it calls setstate(failbit). In any case, the
function returns *this.
The function:
basic_istream& operator>>(bool& n);
extracts a field and converts it to a Boolean value by calling
use_facet<num_get<E, InIt>(getloc()). get(InIt( rdbuf()), Init(0),
*this, getloc(), n). Here, InIt is defined as
istreambuf_iterator<E, T>. The function returns *this.
The functions:
basic_istream& operator>>(short& n);
basic_istream& operator>>(unsigned short& n);
basic_istream& operator>>(int& n);
basic_istream& operator>>(unsigned int& n);
basic_istream& operator>>(long& n);
basic_istream& operator>>(unsigned long& n);
basic_istream& operator>>(void *& n);
each extract a field and convert it to a numeric value by calling
use_facet<num_get<E, InIt>(getloc()). get(InIt( rdbuf()), Init(0),
*this, getloc(), x). Here, InIt is defined as
istreambuf_iterator<E, T>, and x has type long, unsigned long,
needed. If the converted value cannot be represented as the type of
n, the function calls setstate(failbit). In any case, it returns
file:///D|/97/c++_1/LIBREF.TXT (121 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 121 of 619
*this.
The functions:
basic_istream& operator>>(float& n);
basic_istream& operator>>(double& n);
basic_istream& operator>>(long double& n);
each extract a field and convert it to a numeric value by calling
use_facet<num_get<E, InIt>(getloc()). get(InIt( rdbuf()), Init(0),
*this, getloc(), x). Here, InIt is defined as
istreambuf_iterator<E, T>, and x has type double or long double as
If the converted value cannot be represented as the type of n, the
function calls setstate(failbit). In any case, it returns *this.
basic_istream::peek
int_type peek();
The unformatted input function extracts an element, if possible, as
if by returning rdbuf()->sgetc(). Otherwise, it returns T::eof().
basic_istream::putback
basic_istream& putback(E c);
The unformatted input function puts back c, if possible, as if by
calling rdbuf()->sputbackc(). If rdbuf() is a null pointer, or if
the call to sputbackc returns T::eof(), the function calls setstate
(badbit). In any case, it returns *this.
basic_istream::read
basic_istremm& read(E *s, streamsize n);
The unformatted input function extracts up to n elements and stores
them in the array beginning at s. Extraction stops early on end-of-
file, in which case the function calls setstate(failbit). In any
case, it returns *this.
basic_istream::readsome
readsome readsome(E *s, streamsize n);
The member function extracts up to n elements and stores them in
the array beginning at s. If rdbuf() is a null pointer, the
function calls setstate(failbit). Otherwise, it assigns the value
of rdbuf()-<in_avail() to N. if N < 0, the function calls setstate
(eofbit). Otherwise, it replaces the value stored in N with the
smaller of n and N, then calls read(s, N). In any case, the
function returns gcount().
basic_istream::seekg
basic_istream& seekg(pos_type pos);
basic_istream& seekg(off_type off, ios_base::seek_dir way);
file:///D|/97/c++_1/LIBREF.TXT (122 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 122 of 619
If fail() is false, the first member function calls rdbuf()->
pubseekpos(pos). If fail() is false, the second function calls
rdbuf()-> pubseekoff(off, way). Both functions return *this.
basic_istream::sentry
class sentry {
public:
explicit sentry(basic_istream<E, T>& is, bool noskip = false);
operator bool() const;
};
The nested class describes an object whose declaration structures
the formatted input functions and the unformatted input functions.
The constructor effectively calls is.ipfx(noskip) and stores the
return value. operator bool() delivers this return value. The
destructor effectively calls is.isfx().
basic_istream::sync
int sync();
If rdbuf() is a null pointer, the function returns -1. Otherwise,
it calls rdbuf()->pubsync(). If that returns -1, the function calls
setstate(badbit) and returns -1. Otherwise, the function returns
zero.
basic_istream::tellg
pos_type tellg();
If fail() is false, the member function returns rdbuf()->
pubseekoff(0, cur, in). Otherwise, it returns streampos(-1).
basic_istream::unget
basic_istream& unget();
The unformatted input function puts back the previous element in
the stream, if possible, as if by calling rdbuf()->sungetc(). If
rdbuf() is a null pointer, or if the call to sungetc returns T::eof
(), the function calls setstate(badbit). In any case, it returns
*this.
iostream
typedef basic_iostream<char, char_traits<char> > iostream;
The type is a synonym for template class basic_iostream,
specialized for elements of type char with default character
istream
typedef basic_istream<char, char_traits<char> > istream;
The type is a synonym for template class basic_istream, specialized
file:///D|/97/c++_1/LIBREF.TXT (123 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 123 of 619
for elements of type char with default character
operator>>
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T> is, E *s);
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T> is, E& c);
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, si
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, si
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, un
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, un
The template function:
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T>& is, E *s);
extracts up to n - 1 elements and stores them in the array
beginning at s. If is.width() is greater than zero, n is is.width
(); otherwise it is the largest array of E that can be declared.
The function always stores E(0) after any extracted elements it
stores. Extraction stops early on end-of-file or on any element
(which is not extracted) that would be discarded by ws. If the
function extracts no elements, it calls is.setstate(failbit). In
any case, it calls is.width(0) and returns is.
The template function:
template<class E, class T>
basic_istream<E, T>& operator>>(basic_istream<E, T>& is, char& c
extracts an element, if possible, and stores it in c. Otherwise, it
calls is.setstate(failbit). In any case, it returns is.
The template function:
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, si
returns is >> (char *)s.
The template function:
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, si
returns is >> (char&)c.
The template function:
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, un
file:///D|/97/c++_1/LIBREF.TXT (124 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 124 of 619
returns is >> (char *)s.
The template function:
template<class T>
basic_istream<char, T>& operator>>(basic_istream<char, T> is, un
returns is >> (char&)c.
wiostream
typedef basic_iostream<wchar_t, char_traits<wchar_t> > wiostream;
The type is a synonym for template class basic_iostream,
specialized for elements of type wchar_t with default character
traits.
wistream
typedef basic_istream<wchar_t, char_traits<wchar_t> > wistream;
The type is a synonym for template class basic_istream, specialized
for elements of type wchar_t with default character traits.
ws
template class<E, T>
basic_istream<E, T>& ws(basic_istream<E, T> is);
The manipulator extracts and discards any elements x for which
use_facet< ctype<E> >( getloc()). is( ctype<E>::space, x) is true.
It calls setstate(eofbit) if it encounters end-of-file while
extracting elements. The function returns is.
<iterator>
advance . back_insert_iterator . back_inserter .
bidirectional_iterator_tag . distance . forward_iterator_tag .
front_insert_iterator . front_inserter . input_iterator_tag .
insert_iterator . inserter . istream_iterator . istreambuf_iterator
. iterator iterator_traits
. . operator!= . operator== . operator<
. operator<= . operator> . operator>= . operator+ . operator- .
ostream_iterator . ostreambuf_iterator . output_iterator_tag .
random_access_iterator_tag . reverse_bidirectional_iterator .
reverse_iterator
namespace std {
struct input_iterator_tag;
struct output_iterator_tag;
struct forward_iterator_tag;
struct bidirectional_iterator_tag;
struct random_access_iterator_tag;
// TEMPLATE CLASSES
template<class C, class T, class Dist>
struct iterator;
template<class It>
file:///D|/97/c++_1/LIBREF.TXT (125 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 125 of 619
struct iterator_traits;
template<class T>
struct iterator_traits<T *>
template<class BidIt, class T, class Ref,
class Ptr, class Dist>
class reverse_bidirectional_iterator;
template<class RanIt, class T, class Ref,
class Ptr, class Dist>
class reverse_iterator;
template<class Cont>
class back_insert_iterator;
template<class Cont>
class front_insert_iterator;
template<class Cont>
class insert_iterator;
template<class T, class Dist>
class istream_iterator;
template<class T>
class ostream_iterator;
template<class E, class T>
class istreambuf_iterator;
template<class E, class T>
class ostreambuf_iterator;
// TEMPLATE FUNCTIONS
template<class BidIt, class T, class Ref, class Ptr, class Dist>
bool operator==(
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& lhs,
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator==(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class T, class Dist>
bool operator==(
const istream_iterator<T, Dist>& lhs,
const istream_iterator<T, Dist>& rhs);
template<class E, class T>
bool operator==(
const istreambuf_iterator<E, T>& lhs,
const istreambuf_iterator<E, T>& rhs);
template<class BidIt, class T, class Ref, class Ptr, class Dist>
bool operator!=(
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& lhs,
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator!=(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class T, class Dist>
bool operator!=(
const istream_iterator<T, Dist>& lhs,
const istream_iterator<T, Dist>& rhs);
template<class E, class T>
file:///D|/97/c++_1/LIBREF.TXT (126 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 126 of 619
bool operator!=(
const istreambuf_iterator<E, T>& lhs,
const istreambuf_iterator<E, T>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator<(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>&mmp lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator>(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>&mmp lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator<=(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>&mmp lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator>=(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>&mmp lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
Dist operator-(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
reverse_iterator<RanIt, T, Ref, Ptr, Dist> operator+(
Dist n,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
template<class Cont>
back_insert_iterator<Cont> back_inserter(Cont& x);
template<class Cont>
front_insert_iterator<Cont> front_inserter(Cont& x);
template<class Cont, class Iter>
insert_iterator<Cont> inserter(Cont& x, Iter it);
template<class InIt, class Dist>
void advance(InIt& it, Dist n);
template<class Init, class Dist>
ptrdiff_t distance(InIt first, InIt last);
};
Include the STL standard header <iterator> to define a number of
classes, template classes, and template functions that aid in the
declaration and manipulation of iterators.
advance
template<class InIt, class Dist>
void advance(InIt& it, Dist n);
The template function effectively advances it by incrementing it n
times. If InIt is a random-access iterator type, the function
evaluates the expression it += n. Otherwise, it performs each
increment by evaluating ++it. If InIt is an input or forward
iterator type, n must not be negative.
See the related sample program.
back_insert_iterator
file:///D|/97/c++_1/LIBREF.TXT (127 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 127 of 619
template<class Cont>
class back_insert_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef Cont container_type;
typedef Cont::value_type value_type;
explicit back_insert_iterator(Cont& x);
back_insert_iterator& operator=(const Cont::value_type& val);
back_insert_iterator& operator*();
back_insert_iterator& operator++();
back_insert_iterator operator++(int);
protected:
Cont& container;
};
The template class describes an output iterator object. It inserts
elements into a container of type Cont, which it accesses via the
protected reference object it stores called container. The
container must define:
lThe member type value_type, which is the type of an element of
the sequence controlled by the container.
lThe member function push_back(value_type c), which appends a
new element with value c to the end of the sequence.
back_insert_iterator::back_insert_iterator
explicit back_insert_iterator(Cont& x);
The constructor initializes container with x.
back_insert_iterator::container_type
typedef Cont container_type;
The type is a synonym for the template parameter Cont.
back_insert_iterator::operator*
back_insert_iterator& operator*();
The member function returns *this.
back_insert_iterator::operator++
back_insert_iterator& operator++();
back_insert_iterator operator++(int);
The member functions both return *this.
back_insert_iterator::operator=
back_insert_iterator& operator=(const Cont::value_type& val);
The member function evaluates container. push_back(val), then
returns *this.
file:///D|/97/c++_1/LIBREF.TXT (128 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 128 of 619
back_insert_iterator::value_type
typedef Cont::value_type value_type;
The type describes the elements of the sequence controlled by the
associated container.
back_inserter
template<class Cont>
back_insert_iterator<Cont> back_inserter(Cont& x);
The template member function returns back_insert_iterator<Cont>(x).
bidirectional_iterator_tag
struct bidirectional_iterator_tag
: public forward_iterator_tag {
};
The type is the same as iterator<It>::iterator_category when It
describes an object that can serve as a bidirectional iterator.
distance
template<class Init, class Dist>
ptrdiff_t distance(InIt first, InIt last);
The template function sets a count n to zero. It then effectively
advances first and increments n until first == last. If InIt is a
random-access iterator type, the function evaluates the expression
n += last - first. Otherwise, it performs each iterator increment
by evaluating ++first.
In this implementation, if a translator does not support partial
specialization of templates, the return type is ptrdiff_t instead
of iterator_traits<InIt>::distance_type. If you are not certain
this type is adequate, use the template function:
template<class InIt, class Dist>
void _Distance(InIt first, InIt last, Dist& n0);
which adds n to the value stored in n0.
See the related sample program.
forward_iterator_tag
struct forward_iterator_tag
: public input_iterator_tag {
};
The type is the same as iterator<It>::iterator_category when It
describes an object that can serve as a forward iterator.
front_insert_iterator
file:///D|/97/c++_1/LIBREF.TXT (129 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 129 of 619
template<class Cont>
class front_insert_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef Cont container_type;
typedef Cont::value_type value_type;
explicit front_insert_iterator(Cont& x);
front_insert_iterator& operator=(const Cont::value_type& val);
front_insert_iterator& operator*();
front_insert_iterator& operator++();
front_insert_iterator operator++(int);
protected:
Cont& container;
};
The template class describes an output iterator object. It inserts
elements into a container of type Cont, which it accesses via the
protected reference object it stores called container. The
container must define:
lThe member type value_type, which is the type of an element of
the sequence controlled by the container.
lThe member function push_front(value_type c), which prepends a
new element with value c to the beginning of the sequence.
front_insert_iterator::container_type
typedef Cont container_type;
The type is a synonym for the template parameter Cont.
front_insert_iterator::front_insert_iterator
explicit front_insert_iterator(Cont& x);
The constructor initializes container with x.
front_insert_iterator::operator*
front_insert_iterator& operator*();
The member function returns *this.
front_insert_iterator::operator++
front_insert_iterator& operator++();
front_insert_iterator operator++(int);
The member functions both return *this.
front_insert_iterator::operator=
front_insert_iterator& operator=(const Cont::value_type& val);
The member function evaluates container. push_front(val), then
returns *this.
file:///D|/97/c++_1/LIBREF.TXT (130 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 130 of 619
front_insert_iterator::value_type
typedef Cont::value_type value_type;
The type describes the elements of the sequence controlled by the
associated container.
front_inserter
template<class Cont>
front_insert_iterator<Cont> front_inserter(Cont& x);
The template member function returns front_insert_iterator<Cont>
(x).
input_iterator_tag
struct input_iterator_tag {
};
The type is the same as iterator<It>::iterator_category when It
describes an object that can serve as an input iterator.
insert_iterator
template<class Cont>
class insert_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef Cont container_type;
typedef Cont::value_type value_type;
explicit insert_iterator(Cont& x, Cont::iterator it);
insert_iterator& operator=(const Cont::value_type& val);
insert_iterator& operator*();
insert_iterator& operator++();
insert_iterator& operator++(int);
protected:
Cont& container;
Cont::iterator iter;
};
The template class describes an output iterator object. It inserts
elements into a container of type Cont, which it accesses via the
protected reference object it stores called container. It also
stores the protected iterator object, of class Cont::iterator,
called iter. The container must define:
lThe member type iterator, which is the type of an iterator for
the container.
lThe member type value_type, which is the type of an element of
the sequence controlled by the container.
lThe member function insert(iterator it, value_type c), which
inserts a new element with value c immediately before the
element designated by it in the controlled sequence, then
returns an iterator that designates the inserted element.
file:///D|/97/c++_1/LIBREF.TXT (131 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 131 of 619
insert_iterator::container_type
typedef Cont container_type;
The type is a synonym for the template parameter Cont.
insert_iterator::insert_iterator
explicit insert_iterator(Cont& x, Cont::iterator it);
The constructor initializes container with x, and iter with it.
insert_iterator::operator*
insert_iterator& operator*();
The member function returns *this.
insert_iterator::operator++
insert_iterator& operator++();
insert_iterator& operator++(int);
The member functions both return *this.
insert_iterator::operator=
insert_iterator& operator=(const Cont::value_type& val);
The member function evaluates iter = container. insert(iter, val),
then returns *this.
insert_iterator::value_type
typedef Cont::value_type value_type;
The type describes the elements of the sequence controlled by the
associated container.
inserter
template<class Cont, class Iter>
insert_iterator<Cont> inserter(Cont& x, Iter it);
The template member function returns insert_iterator<Cont>(x, it).
istream_iterator
template<class U, class E = char, class T = char_traits<E> >
class istream_iterator
: public iterator<input_iterator_tag, U, ptrdiff_t> {
public:
typedef E char_type;
typedef T traits_type;
typedef basic_istream<E, T> istream_type;
istream_iterator();
file:///D|/97/c++_1/LIBREF.TXT (132 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 132 of 619
istream_iterator(istream_type& is);
const U& operator*() const;
const U *operator->() const;
istream_iterator<U, E, T>& operator++();
istream_iterator<U, E, T> operator++(int);
};
The template class describes an input iterator object. It extracts
objects of class U from an input stream, which it accesses via an
object it stores, of type pointer to basic_istream<E, T>. After
constructing or incrementing an object of class istream_iterator
with a non-null stored pointer, the object attempts to extract and
store an object of type U from the associated input stream. If the
extraction fails, the object effectively replaces the stored
pointer with a null pointer (thus making an end-of-sequence
indicator).
istream_iterator::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
istream_iterator::istream_iterator
istream_iterator();
istream_iterator(istream_type& is);
The first constructor initializes the input stream pointer with a
null pointer. The second constructor initializes the input stream
pointer with &is, then attempts to extract and store an object of
type U.
istream_iterator::istream_type
typedef basic_istream<E, T> istream_type;
The type is a synonym for basic_istream<E, T>.
istream_iterator::operator*
const U& operator*() const;
The operator returns the stored object of type U.
istream_iterator::operator->
const U *operator->() const;
The operator returns &**this.
istream_iterator::operator++
istream_iterator<U, E, T>& operator++();
istream_iterator<U, E, T> operator++(int);
The first operator attempts to extract and store an object of type
file:///D|/97/c++_1/LIBREF.TXT (133 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 133 of 619
U from the associated input stream. The second operator makes a
copy of the object, increments the object, then returns the copy.
istream_iterator::traits_type
typedef T traits_type;
The type is a synonym for the template parameter T.
istreambuf_iterator
template<class E, class T = char_traits<E> >
class istreambuf_iterator
: public iterator<input_iterator_tag, T, Dist> {
public:
typedef E char_type;
typedef T traits_type;
typedef T::int_type int_type;
typedef basic_streambuf<E, T> streambuf_type;
typedef basic_istream<E, T> istream_type;
istreambuf_iterator(streambuf_type *sb = 0) throw();
istreambuf_iterator(istream_type& is) throw();
const E& operator*() const;
const E *operator->();
istreambuf_iterator& operator++();
istreambuf_iterator operator++(int);
bool equal(const istreambuf_iterator& rhs);
};
The template class describes an input iterator object. It extracts
elements of class E from an input stream buffer, which it accesses
via an object it stores, of type pointer to basic_streambuf<E, T>.
After constructing or incrementing an object of class
istreambuf_iterator with a non-null stored pointer, the object
effectively attempts to extract and store an object of type E from
the associated itput stream. (The extraction may be delayed,
however, until the object is actually dereferenced or copied.) If
the extraction fails, the object effectively replaces the stored
pointer with a null pointer (thus making an end-of-sequence
indicator).
istreambuf_iterator::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
istreambuf_iterator::equal
bool equal(const istreambuf_iterator& rhs);
The member function returns true only if the stored stream-buffer
pointers for the object and rhs are both null pointers or are both
non-null pointers.
istreambuf_iterator::int_type
file:///D|/97/c++_1/LIBREF.TXT (134 of 626) [28/10/2007 12:33:45 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 134 of 619
typedef T:int_type int_type;
The type is a synonym for T::int_type">int_type.
istreambuf_iterator::istream_type
typedef basic_istream<E, T> istream_type;
The type is a synonym for basic_istream<E, T>.
istreambuf_iterator::istreambuf_iterator
istreambuf_iterator(streambuf_type *sb = 0) throw();
istreambuf_iterator(istream_type& is) throw();
The first constructor initializes the input stream-buffer pointer
with sb. The second constructor initializes the input stream-buffer
pointer with is.rdbuf(), then (eventually) attempts to extract and
store an object of type E.
istreambuf_iterator::operator*
const E& operator*() const;
The operator returns the stored object of type E.
istreambuf_iterator::operator++
istreambuf_iterator& operator++();
istreambuf_iterator operator++(int);
The first operator (eventually) attempts to extract and store an
object of type E from the associated input stream. The second
operator makes a copy of the object, increments the object, then
returns the copy.
istreambuf_iterator::operator->
const E *operator->() const;
The operator returns &**this.
istreambuf_iterator::streambuf_type
typedef basic_streambuf<E, T> streambuf_type;
The type is a synonym for basic_streambuf<E, T>.
istreambuf_iterator::traits_type
typedef T traits_type;
The type is a synonym for the template parameter T.
iterator
file:///D|/97/c++_1/LIBREF.TXT (135 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 135 of 619
template<class C, class T, class Dist = ptrdiff_t>
struct iterator {
typedef C iterator_category;
typedef T value_type;
typedef Dist distance_type;
};
The template class serves as a base type for all iterators. It
defines the member types iterator_category (a synonym for the
template parameter C), value_type (a synonym for the template
parameter T), and distance_type (a synonym for the template
parameter Dist).
iterator_traits
template<class It>
struct iterator_traits {
typedef It::iterator_category iterator_category;
typedef It::value_type value_type;
typedef It::distance_type distance_type;
};
The template class determines several critical types associated
with the iterator type It. It defines the member types
iterator_category (a synonym for It::iterator_category), value_type
(a synonym for It::value_type), and distance_type (a synonym for
It::distance_type).
In this implementation, if a translator does not support partial
specialization of templates, you should use the template functions:
template<class C, class T, class Dist>
C _Iter_cat(const iterator<C, T, Dist>&);
template<class T>
random_access_iterator_tag _Iter_cat(const T *);
template<class C, class T, class Dist>
T *_Val_type(const iterator<C, T, Dist>&);
template<class T>
T *_Val_type(const T *);
template<class C, class T, class Dist>
Dist *_Dist_type(const iterator<C, T, Dist>&);
template<class T>
ptrdiff_t *_Dist_type(const T *);
which determine the same types somewhat less directly. You use
these functions as arguments on a function call. Their sole purpose
is to supply a useful template class parameter to the called
function.
operator!=
template<class BidIt, class T, class Ref, class Ptr, class Dist>
bool operator!=(
const reverse_bidirectional_iterator<BidIt, T, Ref,
file:///D|/97/c++_1/LIBREF.TXT (136 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 136 of 619
Ptr, Dist>& lhs,
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator!=(
const reverse_iterator<BidIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<BidIt, T, Ref, Ptr, Dist>& rhs);
template<class T, class Dist>
bool operator!=(
const istream_iterator<T, Dist>& lhs,
const istream_iterator<T, Dist>& rhs);
template<class E, class T>
bool operator!=(
const istreambuf_iterator<E, T>& lhs,
const istreambuf_iterator<E, T>& rhs);
The template operator returns !(lhs == rhs).
operator==
template<class BidIt, class T, class Ref, class Ptr, class Dist>
bool operator==(
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& lhs,
const reverse_bidirectional_iterator<BidIt, T, Ref,
Ptr, Dist>& rhs);
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator==(
const reverse_iterator<BidIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<BidIt, T, Ref, Ptr, Dist>& rhs);
template<class T, class Dist>
bool operator==(
const istream_iterator<T, Dist>& lhs,
const istream_iterator<T, Dist>& rhs);
template<class E, class T>
bool operator==(
const istreambuf_iterator<E, T>& lhs,
const istreambuf_iterator<E, T>& rhs);
The first two template operators each return true only if
lhs.current == rhs.current. The third template operator returns
true only if both lhs and rhs store the same stream pointer. The
fourth template operator returns lhs.equal(rhs).
operator<
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator<(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns rhs.current < lhs.current.
operator<=
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator<=(
file:///D|/97/c++_1/LIBREF.TXT (137 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 137 of 619
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns !(rhs < lhs).
operator>
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator>(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns rhs < lhs.
operator>=
template<class RanIt, class T, class Ref, class Ptr, class Dist>
bool operator>=(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns !(lhs < rhs).
operator+
template<class RanIt, class T, class Ref, class Ptr, class Dist>
reverse_iterator<RanIt, T, Ref, Ptr, Dist> operator+(
Dist n,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns rhs + n.
operator-
template<class RanIt, class T, class Ref, class Ptr, class Dist>
Dist operator-(
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& lhs,
const reverse_iterator<RanIt, T, Ref, Ptr, Dist>& rhs);
The template operator returns rhs.current - lhs.current.
ostream_iterator
template<class U, class E=char, class Tr=char_traits<E> >
class ostream_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef U value_type;
typedef E char_type;
typedef T traits_type;
typedef basic_ostream<E, T> ostream_type;
ostream_iterator(ostream_type& os);
ostream_iterator(ostream_type& os, const E *delim);
ostream_iterator<U, E, T>& operator=(const U& val);
ostream_iterator<U, E, T>& operator*();
ostream_iterator<U, E, T>& operator++();
ostream_iterator<U, E, T> operator++(int);
file:///D|/97/c++_1/LIBREF.TXT (138 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 138 of 619
};
The template class describes an output iterator object. It inserts
objects of class U into an output stream, which it accesses via an
object it stores, of type pointer to basic_ostream<E, T>. It also
stores a pointer to a delimiter string, a null-terminated string of
elements of type E, which is appended after each insertion. (Note
that the string itself is not copied by the constructor.)
ostream_iterator::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
ostream_iterator::operator*
ostream_iterator<U, E, T>& operator*();
The operator returns *this.
ostream_iterator::operator++
ostream_iterator<U, E, T>& operator++();
ostream_iterator<U, E, T> operator++(int);
The operators both return *this.
ostream_iterator::operator=
ostream_iterator<U, E, T>& operator=(const U& val);
The operator inserts val into the output stream associated with the
object, then returns *this.
ostream_iterator::ostream_iterator
ostream_iterator(ostream_type& os);
ostream_iterator(ostream_type& os, const E *delim);
The first constructor initializes the output stream pointer with
&os. The delimiter string pointer designates an empty string. The
second constructor initializes the output stream pointer with &os
and the delimiter string pointer with delim.
ostream_iterator::ostream_type
typedef basic_ostream<E, T> ostream_type;
The type is a synonym for basic_ostream<E, T>.
ostream_iterator::traits_type
typedef T traits_type;
The type is a synonym for the template parameter T.
file:///D|/97/c++_1/LIBREF.TXT (139 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 139 of 619
ostream_iterator::value_type
typedef U value_type;
The type is a synonym for the template parameter U.
ostreambuf_iterator
template<class E, class T = char_traits<E> >
class ostreambuf_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef E char_type;
typedef T traits_type;
typedef basic_streambuf<E, T> streambuf_type;
typedef basic_ostream<E, T> ostream_type;
ostreambuf_iterator(streambuf_type *sb) throw();
ostreambuf_iterator(ostream_type& os) throw();
ostreambuf_iterator& operator=(E x);
ostreambuf_iterator& operator*();
ostreambuf_iterator& operator++();
T1 operator++(int);
bool failed() const throw();
};
The template class describes an output iterator object. It inserts
elements of class E into an output stream buffer, which it accesses
via an object it stores, of type pointer to basic_streambuf<E, T>.
ostreambuf_iterator::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
ostreambuf_iterator::failed
bool failed() const throw();
The member function returns true only if no insertion into the
output stream buffer has failed earlier.
ostreambuf_iterator::operator*
ostreambuf_iterator& operator*();
The operator returns *this.
ostreambuf_iterator::operator++
ostreambuf_iterator& operator++();
T1 operator++(int);
The first operator returns *this. The second operator returns an
object of some type T1 that can be converted to
ostreambuf_iterator<E, T>.
file:///D|/97/c++_1/LIBREF.TXT (140 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 140 of 619
ostreambuf_iterator::operator=
ostreambuf_iterator& operator=(E x);
The operator inserts x into the associated stream buffer, then
returns *this.
ostreambuf_iterator::ostream_type
typedef basic_ostream<E, T> ostream_type;
The type is a synonym for basic_ostream<E, T>.
ostreambuf_iterator::ostreambuf_iterator
ostreambuf_iterator(streambuf_type *sb) throw();
ostreambuf_iterator(ostream_type& is) throw();
The first constructor initializes the output stream-buffer pointer
with sb. The second constructor initializes the output stream-
buffer pointer with is.rdbuf(). (The stored pointer must not be a
null pointer.)
ostreambuf_iterator::streambuf_type
typedef basic_streambuf<E, T> streambuf_type;
The type is a synonym for basic_streambuf<E, T>.
ostreambuf_iterator::traits_type
typedef T traits_type;
The type is a synonym for the template parameter T.
output_iterator_tag
struct output_iterator_tag {
};
The type is the same as iterator<It>::iterator_category when It
describes an object that can serve as an output iterator.
random_access_iterator_tag
struct random_access_iterator_tag
: public bidirectional_iterator_tag {
};
The type is the same as iterator<It>::iterator_category when It
describes an object that can serve as a random-access iterator.
reverse_bidirectional_iterator
template<class BidIt,
class T = iterator_traits<BidIt>::value_type,
file:///D|/97/c++_1/LIBREF.TXT (141 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 141 of 619
class Ref = T&,
class Ptr = T *, class Dist = ptrdiff_t>
class reverse_bidirectional_iterator
: public iterator<bidirectional_iterator_tag, T, Dist> {
public:
typedef BidIt iter_type;
typedef Ref reference_type;
typedef Ptr pointer_type;
reverse_bidirectional_iterator();
explicit reverse_bidirectional_iterator(BidIt x);
BidIt base() const;
Ref operator*() const;
Ptr operator->() const;
reverse_bidirectional_iterator& operator++();
reverse_bidirectional_iterator operator++(int);
reverse_bidirectional_iterator& operator--();
reverse_bidirectional_iterator operator--();
protected:
BidIt current;
};
The template class describes an object that behaves like a
bidirectional iterator of class
iterator<bidirectional_iterator_tag, T, Dist>. It stores a
bidirectional iterator of type BidIt in the protected object
current. Incrementing the object x of type
reverse_bidirectional_iterator decrements x.current, and
decrementing x increments x.current. Moreover, the expression *x
evaluates to *--(tmp = current) (where tmp is a temporary object of
class BidIt), of type Ref. Typically, Ref is type T&.
Thus, you can use an object of class reverse_bidirectional_iterator
to access in reverse order a sequence that is traversed in order by
a bidirectional iterator.
reverse_bidirectional_iterator::base
BidIt base() const;
The member function returns current.
reverse_bidirectional_iterator::iter_type
typedef BidIt iter_type;
The type is a synonym for the template parameter BidIt.
reverse_bidirectional_iterator::operator*
Ref operator*() const;
The operator assigns current to a temporary object tmp of class
BidIt, then returns *--tmp.
reverse_bidirectional_iterator::operator++
reverse_bidirectional_iterator& operator++();
file:///D|/97/c++_1/LIBREF.TXT (142 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 142 of 619
reverse_bidirectional_iterator operator++(int);
The first (preincrement) operator evaluates --current. then returns
*this.
The second (postincrement) operator makes a copy of *this,
evaluates --current, then returns the copy.
reverse_bidirectional_iterator::operator--
reverse_bidirectional_iterator& operator--();
reverse_bidirectional_iterator operator--();
The first (predecrement) operator evaluates ++current, then returns
*this.
The second (postdecrement) operator makes a copy of *this,
evaluates ++current, then returns the copy.
reverse_bidirectional_iterator::operator->
Ptr operator->() const;
The operator returns &**this.
reverse_bidirectional_iterator::pointer_type
typedef Ptr pointer_type;
The type is a synonym for the template parameter Ref.
reverse_bidirectional_iterator::reference_type
typedef Ref reference_type;
The type is a synonym for the template parameter Ref.
reverse_bidirectional_iterator::reverse_bidirectional_iterator
reverse_bidirectional_iterator();
explicit reverse_bidirectional_iterator(BidIt x);
The first constructor initializes current with its default
constructor. The second constructor initializes current with
current(x).
reverse_iterator
template<class RanIt,
class T = iterator_traits<RanIt>::value_type,
class Ref = T&,
class Ptr = T *, class Dist = ptrdiff_t>
class reverse_iterator
: public iterator<random_access_iterator_tag, T, Dist> {
public:
typedef RanIt iter_type;
typedef Ref reference_type;
file:///D|/97/c++_1/LIBREF.TXT (143 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 143 of 619
typedef Ptr pointer_type;
reverse_iterator();
explicit reverse_iterator(RanIt x);
RanIt base() const;
Ref operator*() const;
Ptr operator->() const;
reverse_iterator& operator++();
reverse_iterator operator++(int);
reverse_iterator& operator--();
reverse_iterator operator--();
reverse_iterator& operator+=(Dist n);
reverse_iterator operator+(Dist n) const;
reverse_iterator& operator-=(Dist n);
reverse_iterator operator-(Dist n) const;
Ref operator[](Dist n) const;
protected:
RanIt current;
};
The template class describes an object that behaves like a random-
access iterator of class iterator<random_access_iterator_tag, T,
Dist>. It stores a random-access iterator of type RanIt in the
protected object current. Incrementing the object x of type
reverse_iterator decrements x.current, and decrementing x
increments x.current. Moreover, the expression *x evaluates to *
(current - 1), of type Ref. Typically, Ref is type T&.
Thus, you can use an object of class reverse_iterator to access in
reverse order a sequence that is traversed in order by a random-
access iterator.
reverse_iterator::base
RanIt base() const;
The member function returns current.
reverse_iterator::iter_type
typedef RanIt iter_type;
The type is a synonym for the template parameter RanIt.
reverse_iterator::operator*
Ref operator*() const;
The operator returns *(current - 1).
reverse_iterator::operator+
reverse_iterator operator+(Dist n) const;
The operator returns reverse_iterator(*this) += n.
reverse_iterator::operator++
file:///D|/97/c++_1/LIBREF.TXT (144 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 144 of 619
reverse_iterator& operator++();
reverse_iterator operator++(int);
The first (preincrement) operator evaluates --current, then returns
*this.
The second (postincrement) operator makes a copy of *this,
evaluates --current, then returns the copy.
reverse_iterator::operator+=
reverse_iterator& operator+=(Dist n);
The operator evaluates current - n, then returns *this.
reverse_iterator::operator-
reverse_iterator operator-(Dist n) const;
The operator returns reverse_iterator(*this) -= n.
reverse_iterator::operator--
reverse_iterator& operator--();
reverse_iterator operator--();
The first (predecrement) operator evaluates ++current, then returns
*this.
The second (postdecrement) operator makes a copy of *this,
evaluates ++current, then returns the copy.
reverse_iterator::operator-=
reverse_iterator& operator-=(Dist n);
The operator evaluates current + n, then returns *this.
reverse_iterator::operator->
Ptr operator->() const;
The operator returns &**this.
reverse_iterator::operator[]
Ref operator[](Dist n) const;
The operator returns *(*this + n).
reverse_iterator::pointer_type
typedef Ptr pointer_type;
The type is a synonym for the template parameter Ref.
file:///D|/97/c++_1/LIBREF.TXT (145 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 145 of 619
reverse_iterator::reference_type
typedef Ref reference_type;
The type is a synonym for the template parameter Ref.
reverse_iterator::reverse_iterator
reverse_iterator();
explicit reverse_iterator(RanIt x);
The first constructor initializes current with its default
constructor. The second constructor initializes current with
current(x).
<limits>
namespace std {
enum float_round_style;
template<class T>
class numeric_limits;
};
Include the standard header <limits> to define the template class
numeric_limits. Explicit specializations of this class describe
many arithmetic properties of the scalar types (other than
pointers).
float_round_style
enum float_round_style {
round_indeterminate = -1,
round_toward_zero = 0,
round_to_nearest = 1,
round_toward_infinity = 2,
round_toward_neg_infinity = 3
};
The enumeration describes the various methods that an
implementation can choose for rounding a floating-point value to an
integer value:
lround_indeterminate -- rounding method cannot be determined
lround_toward_zero -- round toward zero
lround_to_nearest -- round to nearest integer
lround_toward_infinity -- round away from zero
lround_toward_neg_infinity -- round to more negative integer
numeric_limits
template<class T>
class numeric_limits {
public:
static const bool has_denorm = false;
static const bool has_denorm_loss = false;
static const bool has_infinity = false;
file:///D|/97/c++_1/LIBREF.TXT (146 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 146 of 619
static const bool has_quiet_NaN = false;
static const bool has_signaling_NaN = false;
static const bool is_bounded = false;
static const bool is_exact = false;
static const bool is_iec559 = false;
static const bool is_integer = false;
static const bool is_modulo = false;
static const bool is_signed = false;
static const bool is_specialized = false;
static const bool tinyness_before = false;
static const bool traps = false;
static const float_round_style round_style = round_toward_zero;
static const int digits = 0;
static const int digits10 = 0;
static const int max_exponent = 0;
static const int max_exponent10 = 0;
static const int min_exponent = 0;
static const int min_exponent10 = 0;
static const int radix = 0;
static T denorm_min() throw();
static T epsilon() throw();
static T infinity() throw();
static T max() throw();
static T min() throw();
static T quiet_NaN() throw();
static T round_error() throw();
static T signaling_NaN() throw();
};
The template class describes many arithmetic properties of its
parameter type T. The header defines explicit specializations for
the types wchar_t, bool, char, signed char, unsigned char, short,
long, float, double, and long double. For all these explicit
member is_specialized is true, and all relevant members have
meaningful values. The program can supply additional explicit
specializations.
For an arbitrary specialization, no members have meaningful values.
A member object that does not have a meaningful value stores zero
(or false) and a member function that does not return a meaningful
value returns T(0).
See the related numeric_limits sample program.
numeric_limits::denorm_min
static T denorm_min() throw();
The function returns the minimum value for the type (which is the
same as min() if has_denorm is false).
See the related numeric_limits sample program.
numeric_limits::digits
static const int digits = 0;
file:///D|/97/c++_1/LIBREF.TXT (147 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 147 of 619
The member stores the number of radix digits that the type can
represent without change (which is the number of bits other than
any sign bit for a predefined integer type, or the number of
mantissa digits for a predefined floating-point type).
See the related numeric_limits sample program.
numeric_limits::digits10
static const int digits10 = 0;
The member stores the number of decimal digits that the type can
represent without change.
See the related numeric_limits sample program.
numeric_limits::epsilon
static T epsilon() throw();
The function returns the difference between 1 and the smallest
value greater than 1 that is representable for the type (which is
the value FLT_EPSILON for type
See the related numeric_limits sample program.
numeric_limits::has_denorm
static const bool has_denorm = false;
The member stores true for a floating-point type that has
denormalized values (effectively a variable number of exponent
bits).
See the related numeric_limits sample program.
numeric_limits::has_denorm_loss
static const bool has_denorm_loss = false;
The member stores true for a type that determines whether a value
has lost accuracy because it is delivered as a denormalized result
(too small to represent as a normalized value) or because it is
inexact (not the same as a result not subject to limitations of
exponent range and precision). The latter is an option with IEC 559
floating-point representations that can affect some results.
See the related numeric_limits sample program.
numeric_limits::has_infinity
static const bool has_infinity = false;
The member stores true for a type that has a representation for
positive infinity. True if is_iec559 is true.
file:///D|/97/c++_1/LIBREF.TXT (148 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 148 of 619
See the related numeric_limits sample program.
numeric_limits::has_quiet_NaN
static const bool has_quiet_NaN = false;
The member stores true for a type that has a representation for a
quiet NaN, an encoding that is "Not a Number" that does not signal
its presence in an expression. True if is_iec559 is true.
See the related numeric_limits sample program.
numeric_limits::has_signaling_NaN
static const bool has_signaling_NaN = false;
The member stores tree for a type that has a representation for a
signaling NaN, an encoding that is ``Not a Number'' which signals
its presence in an expression by reporting an exception. True if
is_iec559 is true.
See the related numeric_limits sample program.
numeric_limits::infinity
static T infinity() throw();
The function returns the representation of positive infinity for
the type. The return value is meaningful only if has_infinity is
true.
See the related numeric_limits sample program.
numeric_limits::is_bounded
static const bool is_bounded = false;
The member stores true for a type that has a bounded set of
representable values (which is the case for all predefined types).
See the related numeric_limits sample program.
numeric_limits::is_exact
static const bool is_exact = false;
The member stores true for a type that has exact representations
for all its values (which is the case for all predefined integer
types). A fixed-point or rational representation is also considered
exact, but not a floating-point representation.
See the related numeric_limits sample program.
numeric_limits::is_iec559
static const bool is_iec559 = false;
file:///D|/97/c++_1/LIBREF.TXT (149 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 149 of 619
The member stores true for a type that has a representation
conforming to IEC 559, an international standard for representing
floating-point values (also known as IEEE 754 in the United
States).
See the related numeric_limits sample program.
numeric_limits::is_integer
static const bool is_integer = false;
The member stores true for a type that has an integer
representation (which is the case for all predefined integer
types).
See the related numeric_limits sample program.
numeric_limits::is_modulo
static const bool is_modulo = false;
The member stores true for a type that has a modulo representation,
where all results are reduced modulo some value (which is the case
for all predefined unsigned integer types).
See the related numeric_limits sample program.
numeric_limits::is_signed
static const bool is_signed = false;
The member stores true for a type that has a signed representation
(which is the case for all predefined floating-point and signed
integer types).
See the related numeric_limits sample program.
numeric_limits::is_specialized
static const bool is_specialized = false;
The member stores true for a type that has an explicit
specialization defined for template class numeric_limits (which is
the case for all scalar types other than pointers).
See the related numeric_limits sample program.
numeric_limits::max
static T max() throw();
The function returns the maximum finite value for the type (which
is INT_MAX for type int and FLT_MAX for type float). The return
is meaningful if is_bounded is true.
See the related numeric_limits sample program.
file:///D|/97/c++_1/LIBREF.TXT (150 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 150 of 619
numeric_limits::max_exponent
static const int max_exponent = 0;
The member stores the maximum positive integer such that the type
can represent as a finite value radix raised to that power (which
is the value FLT_MAX_EXP for type float). Meaningful only
floating-point types.
See the related numeric_limits sample program.
numeric_limits::max_exponent10
static const int max_exponent10 = 0;
The member stores the maximum positive integer such that the type
can represent as a finite value 10 raised to that power (which is
the value FLT_MAX_10_EXP for type float). Meaningful only
floating-point types.
See the related numeric_limits sample program.
numeric_limits::min
static T min() throw();
The function returns the minimum normalized value for the type
(which is INT_MIN for type int and FLT_MIN for type float). The
value is meaningful if is_bounded is true or is_signed is false.
See the related numeric_limits sample program.
numeric_limits::min_exponent
static const int min_exponent = 0;
The member stores the minimum negative integer such that the type
can represent as a normalized value radix raised to that power
(which is the value FLT_MIN_EXP for type float). Meaningful only
floating-point types.
See the related numeric_limits sample program.
numeric_limits::min_exponent10
static const int min_exponent10 = 0;
The member stores the minimum negative integer such that the type
can represent as a normalized value 10 raised to that power (which
is the value FLT_MIN_10_EXP for type float). Meaningful only
floating-point types.
See the related numeric_limits sample program.
numeric_limits::quiet_NaN
file:///D|/97/c++_1/LIBREF.TXT (151 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 151 of 619
static T quiet_NaN() throw();
The function returns a representation of a quiet NaN for the type.
The return value is meaningful only if has_quiet_NaN is true.
See the related numeric_limits sample program.
numeric_limits::radix
static const int radix = 0;
The member stores the base of the representation for the type
(which is 2 for the predefined integer types, and the base to which
the exponent is raised, or FLT_RADIX, for the predefined floating-
point types).
See the related numeric_limits sample program.
numeric_limits::round_error
static T round_error() throw();
The function returns the maximum rounding error for the type.
See the related numeric_limits sample program.
numeric_limits::round_style
static const float_round_style round_style = round_toward_zero;
The member stores a value that describes the various methods an
implementation can choose for rounding a floating-point value to an
integer value.
See the related numeric_limits sample program.
numeric_limits::signaling_NaN
static T signaling_NaN() throw();
The function returns a representation of a signaling NaN for the
type. The return value is meaningful only if has_signaling_NaN is
true.
See the related numeric_limits sample program.
numeric_limits::tinyness_before
static const bool tinyness_before = false;
The member stores true for a type that determines whether a value
is "tiny" (too small to represent as a normalized value) before
rounding, an option with IEC 559 floating-point representations
that can affect some results.
See the related numeric_limits sample program.
file:///D|/97/c++_1/LIBREF.TXT (152 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 152 of 619
numeric_limits::traps
static const bool traps = false;
The member stores true for a type that generates some kind of
signal to report certain arithmetic exceptions.
See the related numeric_limits sample program.
<list>
namespace std {
template<class T, class A>
class list;
// TEMPLATE FUNCTIONS
template<class T, class A>
bool operator==(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
bool operator!=(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
bool operator<(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
bool operator>(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
bool operator<=(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
bool operator>=(
const list<T, A>& lhs,
const list<T, A>& rhs);
template<class T, class A>
void swap(
const list<T, A>& lhs,
const list<T, A>& rhs);
};
Include the STL standard header <list> to define the container
template class list and three supporting templates.
list
allocator_type . assign . back . begin . clear . const_iterator .
const_reference . const_reverse_iterator . difference_type . empty
. end . erase . front . get_allocator . insert . iterator . list .
max_size . merge . pop_back . pop_front . push_back . push_front .
rbegin . reference . remove . remove_if . rend . resize . reverse .
reverse_iterator . size . size_type . sort . splice . swap . unique
file:///D|/97/c++_1/LIBREF.TXT (153 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 153 of 619
. value_type
template<class T, class A = allocator<T> >
class list {
public:
typedef A allocator_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::reference reference;
typedef A::const_reference const_reference;
typedef A::value_type value_type;
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
explicit list(const A& al = A());
explicit list(size_type n, const T& v = T(), const A& al = A());
list(const list& x);
list(const_iterator first, const_iterator last,
const A& al = A());
iterator begin();
const_iterator begin() const;
iterator end();
iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
void resize(size_type n, T x = T());
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
void push_front(const T& x);
void pop_front();
void push_back(const T& x);
void pop_back();
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it,
const_iterator first, const_iterator last);
void insert(iterator it,
const T *first, const T *last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
void swap(list x);
file:///D|/97/c++_1/LIBREF.TXT (154 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 154 of 619
void splice(iterator it, list& x);
void splice(iterator it, list& x, iterator first);
void splice(iterator it, list& x, iterator first, iterator last)
void remove(const T& x);
void remove_if(binder2nd<not_equal_to<T> > pr);
void unique();
void unique(not_equal_to<T> pr);
void merge(list& x);
void merge(list& x, greater<T> pr);
void sort();
template<class Pred>
void sort(greater<T> pr);
void reverse();
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type T. The sequence is stored as a
bidirectional linked list of elements, each containing a member of
type T.
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
List reallocation occurs when a member function must insert or
erase elements of the controlled sequence. In all such cases, only
iterators or references that point at erased portions of the
controlled sequence become invalid.
list::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
list::assign
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
The first member function replaces the sequence controlled by *this
with the sequence [first, last). The second member function
replaces the sequence controlled by *this with a repetition of n
elements of value x.
In this implementation, if a translator does not support member
template functions, the templates:
template<class InIt>
void assign(InIt first, InIt last);
template<class Size, class T2>
void assign(Size n, const T2& x = T2());
file:///D|/97/c++_1/LIBREF.TXT (155 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 155 of 619
are replaced by:
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
See the related sample program.
list::back
reference back();
const_reference back() const;
The member function returns a reference to the last element of the
controlled sequence, which must be non-empty.
See the related sample program.
list::begin
const_iterator begin() const;
iterator begin();
The member function returns a bidirectional iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
list::clear
void clear() const;
The member function calls erase( begin(), end()).
list::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant
bidirectional iterator for the controlled sequence. It is described
here as a synonym for the unspecified type T1.
list::const_reference
typedef A::const_reference const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
list::const_reverse_iterator
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
The type describes an object that can serve as a constant reverse
bidirectional iterator for the controlled sequence.
file:///D|/97/c++_1/LIBREF.TXT (156 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 156 of 619
list::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
list::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
list::end
const_iterator end() const;
iterator end();
The member function returns a bidirectional iterator that points
just beyond the end of the sequence.
list::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements of the controlled sequence in the range [first, last).
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
Erasing N elements causes N destructor calls. No reallocation
occurs, so iterators and references become invalid only for the
erased elements.
list::front
reference front();
const_reference front() const;
The member function returns a reference to the first element of the
controlled sequence, which must be non-empty.
See the related sample program.
list::get_allocator
A get_allocator() const;
The member function returns allocator.
list::insert
iterator insert(iterator it, const T& x = T());
file:///D|/97/c++_1/LIBREF.TXT (157 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 157 of 619
void insert(iterator it, size_type n, const T& x);
void insert(iterator it, const_iterator first, const_iterator last);
Each of the member functions inserts, before the element pointed to
by it in the controlled sequence, a sequence specified by the
remaining operands. The first member function inserts a single
element with value x and returns an iterator that points to the
newly inserted element. The second member function inserts a
repetition of n elements of value x. The last member function
inserts the sequence [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(iterator it, InIt first, InIt last);
is replaced by:
void insert(iterator it, const_iterator first, const_iterator last);
void insert(iterator it, const T *first, const T *last);
Inserting N elements causes N copies. No reallocation occurs, so no
iterators or references become invalid.
See the related sample program.
list::iterator
typedef T0 iterator;
The type describes an object that can serve as a bidirectional
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
list::list
explicit list(const A& al = A());
explicit list(size_type n, const T& v = T(), const A& al = A());
list(const list& x);
list(const_iterator first, const_iterator last, const A& al = A());
All constructors store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
repetition of n elements of value x. The third constructor
specifies a copy of the sequence controlled by x. The last
constructor specifies the sequence [first, last). None of the
constructors perform any interim reallocations.
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
list(InIt first, InIt last, const A& al = A());
file:///D|/97/c++_1/LIBREF.TXT (158 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 158 of 619
is replaced by:
list(const_iterator first, const_iterator last,
const A& al = A());
See the related sample program.
list::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
list::merge
void merge(list& x);
void merge(list& x, greater<T> pr);
Both member functions remove all elements from the sequence
controlled by x and insert them into the controlled sequence. Both
sequences must be ordered by the same predicate, described below.
The resulting sequence is also ordered by that predicate.
For the iterators Pi and Pj designating elements at positions i and
j, the first member function imposes the order !(*Pj < *Pi)
whenever i < j. (The elements are sorted in ascending order.) The
second member function imposes the order !pr(*Pj, *Pi) whenever i <
j.
No pairs of elements in the original controlled sequence are
reversed in the resulting controlled sequence. If a pair of
elements in the resulting controlled sequence compares equal (!(*Pi
< *Pj) && !(*Pj < *Pi)), an element from the original controlled
sequence appears before an element from the sequence controlled by
x.
In this implementation, if a translator does not support member
template functions, the template:
template<class Pred>
void merge(list& x, Pred pr);
is replaced by:
void merge(list& x, greater<T> pr);
list::pop_back
void pop_back();
The member function removes the last element of the controlled
sequence, which must be non-empty.
list::push_back
file:///D|/97/c++_1/LIBREF.TXT (159 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 159 of 619
void push_back(const T& x);
The member function inserts an element with value x at the end of
the controlled sequence.
list::pop_front
void pop_front();
The member function removes the first element of the controlled
sequence, which must be non-empty.
list::push_front
void push_front(const T& x);
The member function inserts an element with value x at the
beginning of the controlled sequence.
list::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. Hence, it
designates the beginning of the reverse sequence.
list::reference
typedef A::reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
list::remove
void remove(const T& x);
The member function removes from the controlled sequence all
elements, designated by the iterator P, for which *P == x.
list::remove_if
void remove_if(binder2nd<not_equal_to<T> > pr);
The member function removes from the controlled sequence all
elements, designated by the iterator P, for which pr(*P) is true.
In this implementation, if a translator does not support member
template functions, the template:
templace<class Pred>
void remove_if(Pred pr);
is replaced by:
file:///D|/97/c++_1/LIBREF.TXT (160 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 160 of 619
>void remove_if(binder2nd< not_equal_to<T> > pr);
list::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse bidirectional iterator that
points at the first element of the sequence (or just beyond the end
of an empty sequence). Hence, it designates the end of the reverse
sequence.
list::resize
void resize(size_type n, T x = T());
The member function ensures that size() henceforth returns n. If it
must make the controlled sequence longer, it appends elements with
value x.
list::reverse
void reverse();
The member function reverses the order in which elements appear in
the controlled sequence.
list::reverse_iterator
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
The type describes an object that can serve as a reverse
bidirectional iterator for the controlled sequence.
list::size
size_type size() const;
The member function returns the length of the controlled sequence.
list::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
list::sort
void sort();
template<class Pred>
void sort(greater<T> pr);
Both member functions order the elements in the controlled sequence
file:///D|/97/c++_1/LIBREF.TXT (161 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 161 of 619
by a predicate, described below.
For the iterators Pi and Pj designating elements at positions i and
j, the first member function imposes the order !(*Pj < *Pi)
whenever i < j. (The elements are sorted in ascending order.) The
member template function imposes the order !pr(*Pj, *Pi) whenever i
< j. No pairs of elements in the original controlled sequence are
reversed in the resulting controlled sequence.
In this implementation, if a translator does not support member
template functions, the template:
template<class Pred>
void sort(Pred pr);
is replaced by:
void sort(greater<T> pr);
list::splice
void splice(iterator it, list& x);
void splice(iterator it, list& x, iterator first);
void splice(iterator it, list& x, iterator first, iterator last);
The first member function inserts the sequence controlled by x
before the element in the controlled sequence pointed to by it. It
also removes all elements from x. (&x must not equal this.)
The second member function removes the element pointed to by first
in the sequence controlled by x and inserts it before the element
in the controlled sequence pointed to by it. (If it == first || it
== ++first, no change occurs.)
The third member function inserts the subrange designated by
[first, last) from the sequence controlled by x before the element
in the controlled sequence pointed to by it. It also removes the
original subrange from the sequence controlled by x. (If &x ==
this, the range [first, last) must not include the element pointed
to by it.)
If the third member function inserts N elements, and &x != this, an
object of class iterator is incremented N times. For all splice
member functions, if allocator != str.allocator, a copy and a
destructor call also occur for each inserted element.
list::swap
void swap(list& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
list::unique
file:///D|/97/c++_1/LIBREF.TXT (162 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 162 of 619
void unique();
void unique(not_equal_to<T> pr);
The first member function removes from the controlled sequence
every element that compares equal to its preceding element. For the
iterators Pi and Pj designating elements at positions i and j, the
second member function removes every element for which i + 1 == j
&& pr(*Pi, *Pj).
In this implementation, if a translator does not support member
template functions, the template:
template<class Pred>
void unique(Pred pr);
is replaced by:
void unique(not_equal_to<T> pr);
For a controlled sequence of length N (> 0), the predicate pr(*Pi,
*Pj) is evaluated N - 1 times.
list::value_type
typedef A::value_type value_type;
The type is a synonym for the template parameter T.
operator!=
template<class T, class A>
bool operator!=(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class T, class A>
bool operator==(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function overloads operator== to compare two objects
of template class list. The function returns lhs.size() == rhs.size
() && equal(lhs. begin(), lhs. end(), rhs.begin()).
operator<
template<class T, class A>
bool operator<(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function overloads operator< to compare two objects of
file:///D|/97/c++_1/LIBREF.TXT (163 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 163 of 619
template class list. The function returns lexicographical_compare
(lhs. begin(), lhs. end(), rhs.begin(), rhs.end()).
operator<=
template<class T, class A>
bool operator<=(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class A>
bool operator>(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class A>
bool operator>=(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function returns !(rhs < lhs).
swap
template<class T, class A>
void swap(
const list <T, A>& lhs,
const list <T, A>& rhs);
The template function executes lhs.swap(rhs).
<locale>
codecvt . codecvt_base . codecvt_byname . collate . collate_byname
. ctype . ctype<char> .
ctype_base . ctype_byname . has_facet .
locale . messages .
messages_base . messages_byname . money_base .
money_get . money_put . moneypunct . moneypunct_byname . num_get .
num_put . numpunct . numpunct_byname . time_base . time_get .
time_get_byname . time_put . time_put_byname . use_facet
isalnum . isalpha . iscntrl . isdigit . isgraph . islower . isprint
. ispunct . isspace . isupper . isxdigit . tolower . toupper
namespace std {
class locale;
class ctype_base;
template<class E>
class ctype;
class ctype<char>;
file:///D|/97/c++_1/LIBREF.TXT (164 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 164 of 619
template<class E>
class ctype_byname;
class codecvt_base;
template<class From, class To, class State>
class codecvt;
template<class From, class To, class State>
class codecvt_byname;
template<class E, class InIt>
class num_get;
template<class E, class OutIt>
class num_put;
template<class E>
class numpunct;
template<class E>
class numpunct_byname;
template<class E>
class collate;
template<class E>
class collate_byname;
class time_base;
template<class E, class InIt>
class time_get;
template<class E, class InIt>
class time_get_byname;
template<class E, class OutIt>
class time_put;
template<class E, class OutIt>
class time_put_byname;
class money_base;
template<class E, bool Intl, class InIt>
class money_get;
template<class E, bool Intl, class OutIt>
class money_put;
template<class E, bool Intl>
class moneypunct;
template<class E, bool Intl>
class moneypunct_byname;
class messages_base;
template<class E>
class messages;
template<class E>
class messages_byname;
// TEMPLATE FUNCTIONS
template<class Facet>
bool has_facet(const locale& loc, const Facet *fac);
template<class Facet>
const Facet& use_facet(const locale& loc,
const Facet *fac, bool is_std);
template<class E>
bool isspace(E c, const locale& loc) const;
template<class E>
bool isprint(E c, const locale& loc) const;
template<class E>
bool iscntrl(E c, const locale& loc) const;
template<class E>
bool isupper(E c, const locale& loc) const;
template<class E>
file:///D|/97/c++_1/LIBREF.TXT (165 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 165 of 619
bool islower(E c, const locale& loc) const;
template<class E>
bool isalpha(E c, const locale& loc) const;
template<class E>
bool isdigit(E c, const locale& loc) const;
template<class E>
bool ispunct(E c, const locale& loc) const;
template<class E>
bool isxdigit(E c, const locale& loc) const;
template<class E>
bool isalnum(E c, const locale& loc) const;
template<class E>
bool isgraph(E c, const locale& loc) const;
template<class E>
E toupper(E c, const locale& loc) const;
template<class E>
E tolower(E c, const locale& loc) const;
};
Include the standard header <locale> to define a host of template
classes and functions that encapsulate and manipulate locales.
codecvt
template<class From, class To, class State>
class codecvt : public locale::facet, public codecvt_base {
public:
typedef From from_type;
typedef To to_type;
typedef State state_type;
explicit codecvt(size_t refs = 0);
result in(State& state,
const To *first1, const To *last1, const To *next1,
From *first2, From *last2, From *next2);
result out(State& state,
const From *first1, const From *last1, const From *next1,
To *first2, To *last2, To *next2);
bool always_noconv() const throw();
int max_length() const throw();
int length(State& state,
From *first1, const From *last1, size_t _N2) const throw();
int encoding() const throw();
static locale::id id;
protected:
~codecvt();
virtual result do_in(State& state,
const To *first1, const To *last1, const To *next1,
From *first2, From *last2, From *next2);
virtual result do_out(State& state,
const From *first1, const From *last1, const From *next1,
To *first2, To *last2, To *next2);
virtual bool do_always_noconv() const throw();
virtual int do_max_length() const throw();
virtual int do_encoding() const throw();
virtual int do_length(State& state,
From *first1, const From *last1, size_t len2) const throw();
};
file:///D|/97/c++_1/LIBREF.TXT (166 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 166 of 619
The template class describes an object that can serve as a locale
facet, to control conversions between a sequence of values of type
From and a sequence of values of type To. The class State
characterizes the transformation -- and an object of class State
stores any necessary state information during a conversion.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
The template versions of do_in do_out always return
codecvt_base::noconv. The Standard C++ library defines an explicit
specialization, however, that is more useful:
codecvt<wchar_t, char, mbstate_t
which converts between wchar_t and char
codecvt::always_noconv
bool always_noconv() const throw();
The member function returns do_always_noconv().
codecvt::codecvt
explicit codecvt(size_t refs = 0);
The constructor initializes its locale::facet base object with
locale::facet(refs).
codecvt::do_always_noconv
virtual bool do_always_noconv() const throw();
The protected virtual member function returns true only if every
call to do_in or do_out returns noconv. The template version always
returns true.
codecvt::do_encoding
virtual int do_encoding() const throw();
The protected virtual member function returns:
l-1, if the encoding of sequences of type to_type is state
dependent
l0, if the encoding involves sequences of varying lengths
ln, if the encoding involves only sequences of length n
codecvt::do_in
virtual result do_in(State state&,
const To *first1, const To *last1, const To *next1,
From *first2, From *last2, From *next2);
file:///D|/97/c++_1/LIBREF.TXT (167 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 167 of 619
The protected virtual member function endeavors to convert the
source sequence at [first1, last1) to a destination sequence that
it stores within [first2, last2). It always stores in next1 a
pointer to the first unconverted element in the source sequence,
and it always stores in next2 a pointer to the first unaltered
element in the destination sequence.
state must represent the initial conversion state at the beginning
of a new source sequence. The function alters its stored value, as
needed, to reflect the current state of a successful conversion.
Its stored value is otherwise unspecified.
The function returns:
lcodecvt_base::error if the source sequence is ill-formed
lcodecvt_base::noconv if the function performs no conversion
lcodecvt_base::ok if the conversion succeeds
lcodecvt_base::partial if the source is insufficient, or if the
destination is not large enough, for the conversion to succeed
The template version always returns noconv.
codecvt::do_length
virtual int do_length(State state&,
From *first1, const From *last1, size_t len2) const throw();
The protected virtual member function effectively calls do_out
(state, first1, last1, next1, buf, buf + len2, next2) for some
buffer buf and pointer next2, then returns next2 - buf. (Thus, it
is roughly analogous to the function mbrlen, at least when From is
type char.)
The template version always returns the lesser of last1 - first1
and len2.
codecvt::do_max_length
virtual int do_max_length() const throw();
The protected virtual member function returns the largest
permissible value that can be returned by do_length(first1, last1,
1), for arbitrary valid values of first1 and last1. (Thus, it is
roughly analogous to the macro MB_CUR_MAX, at least when From is
type char.)
The template version always returns 1.
codecvt::do_out
virtual result do_out(State state&,
const From *first1, const From *last1, const From *next1,
To *first2, To *last2, To *next2);
The protected virtual member function endeavors to convert the
source sequence at [first1, last1) to a destination sequence that
file:///D|/97/c++_1/LIBREF.TXT (168 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 168 of 619
it stores within [first2, last2). It always stores in next1 a
pointer to the first unconverted element in the source sequence,
and it always stores in next2 a pointer to the first unaltered
element in the destination sequence.
state must represent the initial conversion state at the beginning
of a new source sequence. The function alters its stored value, as
needed, to reflect the current state of a successful conversion.
Its stored value is otherwise unspecified.
The function returns:
lcodecvt_base::error if the source sequence is ill-formed
lcodecvt_base::noconv if the function performs no conversion
lcodecvt_base::ok if the conversion succeeds
lcodecvt_base::partial if the source is insufficient, or if the
destination is not large enough, for the conversion to succeed
The template version always returns noconv.
codecvt::encoding
int encoding() const throw();
The member function returns do_encoding().
codecvt::from_type
typedef From from_type;
The type is a synonym for the template parameter From.
codecvt::in
result in(State state&,
const To *first1, const To *last1, const To *next1,
From *first2, From *last2, From *next2);
The member function returns do_in(state, first1, last1, next1,
first2, last2, next2).
codecvt::length
int length(State state&,
From *first1, const From *last1, size_t len2) const throw();
The member function returns do_length(first1, last1, len2).
codecvt::max_length
int max_length() const throw();
The member function returns do_max_length().
codecvt::out
result out(State state&,
file:///D|/97/c++_1/LIBREF.TXT (169 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 169 of 619
const From *first1, const From *last1, const From *next1,
To *first2, To *last2, To *next2);
The member function returns do_out(state, first1, last1, next1,
first2, last2, next2).
codecvt::state_type
typedef State state_type;
The type is a synonym for the template parameter State.
codecvt::to_type
typedef To to_type;
The type is a synonym for the template parameter To.
codecvt_base
class codecvt_base {
public:
enum result {ok, partial, error, noconv};
};
The class describes an enumeration common to all specializations of
template class codecvt. The enumeration result describes the
possible return values from do_in or do_out:
lerror if the source sequence is ill-formed
lnoconv if the function performs no conversion
lok if the conversion succeeds
lpartial if the destination is not large enough for the
conversion to succeed
codecvt_byname
template<class From, class To, class State>
class codecvt_byname : public codecvt<From, To, State> {
public:
explicit codecvt_byname(const char *s, size_t refs = 0);
protected:
~codecvt_byname();
};
The template class describes an object that can serve as a locale
facet of type codecvt<From, To, State>. Its behavior is determined
by the named locale s. The constructor initializes its base object
with codecvt<From, To, State>(refs).
collate
template<class E>
class collate : public locale::facet {
public:
typedef E char_type;
typedef basic_string<E> string_type;
file:///D|/97/c++_1/LIBREF.TXT (170 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 170 of 619
explicit collate(size_t refs = 0);
int compare(const E *first1, const E *last1,
const E *first2, const E *last2) const;
string_type transform(const E *first, const E *last) const;
long hash(const E *first, const E *last) const;
static locale::id id;
protected:
~collate();
virtual int do_compare(const E *first1, const E *last1,
const E *first2, const E *last2) const;
virtual string_type do_transform(const E *first, const E *last)
virtual long do_hash(const E *first, const E *last) const;
};
The template class describes an object that can serve as a locale
facet, to control comparisons of sequences of type E.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
collate::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
collate::collate
explicit collate(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
collate::compare
int compare(const E *first1, const E *last1,
const E *first2, const E *last2) const;
The member function returns do_compare(first1, last1, first2,
last2).
collate::do_compare
virtual int do_compare(const E *first1, const E *last1,
const E *first2, const E *last2) const;
The protected virtual member function compares the sequence at
[first1, last1) with the sequence at [first2, last2). It compares
values by applying operator< between pairs of corresponding
elements of type E. The first sequence compares less if it has the
smaller element in the earliest unequal pair in the sequences, or
if no unequal pairs exist but the first sequence is shorter.
If the first sequence compares less than the second sequence, the
function returns -1. If the second sequence compares less, the
function returns +1. Otherwise, the function returns zero.
file:///D|/97/c++_1/LIBREF.TXT (171 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 171 of 619
collate::do_transform
virtual string_type do_transform(const E *first, const E *last) cons
The protected virtual member function returns an object of class
string_type whose controlled sequence is a copy of the sequence
[first, last). If a class derived from collate<E> overrides
do_compare, it should also override do_transform to match. Put
simply, two transformed strings should yield the same result, when
passed to collate::compare, that you would get from passing the
untransformed strings to compare in the derived class.
collate::do_hash
virtual long do_hash(const E *first, const E *last) const;
The protected virtual member function returns an integer derived
from the values of the elements in the sequence [first, last). Such
a hash value can be useful, for example, in distributing sequences
pseudo-randomly across an array of lists.
collate::hash
long hash(const E *first, const E *last) const;
The member function returns do_hash(first, last).
collate::string_type
typedef basic_string<E> string_type;
The type describes a specialization of template class basic_string
whose objects can store copies of the source sequence.
collate::transform
string_type transform(const E *first, const E *last) const;
The member function returns do_transform(first, last).
collate_byname
template<class E>
class collate_byname : public collate<E> {
public:
explicit collate_byname(const char *s, size_t refs = 0);
protected:
~collate_byname();
};
The template class describes an object that can serve as a locale
facet of type collate<E>. Its behavior is determined by the named
locale s. The constructor initializes its base object with
collate<E>(refs).
ctype
file:///D|/97/c++_1/LIBREF.TXT (172 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 172 of 619
char_type . ctype . do_is .
do_narrow . do_scan_is . do_scan_not .
do_tolower . do_toupper . do_widen . is . narrow . scan_is .
scan_not . tolower . toupper . widen
template<class E>
class ctype : public locale::facet, public ctype_base {
public:
typedef E char_type;
explicit ctype(size_t refs = 0);
bool is(mask msk, E ch) const;
const E *is(const E *first, const E *last, mask *dst) const;
const E *scan_is(mask msk, const E *first, const E *last) const;
const E *scan_not(mask msk, const E *first, const E *last) const
E toupper(E ch) const;
const E *toupper(E *first, E *last) const;
E tolower(E ch) const;
const E *tolower(E *first, E *last) const;
E widen(char ch) const;
const char *widen(char *first, char *last, E *dst) const;
char narrow(E ch, char dflt) const;
const E *narrow(const E *first, const E *last,
char dflt, char *dst) const;
static locale::id id;
protected:
~ctype();
virtual bool do_is(mask msk, E ch) const;
virtual const E *do_is(const E *first, const E *last,
mask *dst) const;
virtual const E *do_scan_is(mask msk, const E *first,
const E *last) const;
virtual const E *do_scan_not(mask msk, const E *first,
const E *last) const;
virtual E do_toupper(E ch) const;
virtual const E *do_toupper(E *first, E *last) const;
virtual E do_tolower(E ch) const;
virtual const E *do_tolower(E *first, E *last) const;
virtual E do_widen(char ch) const;
virtual const char *do_widen(char *first, char *last, E *dst) co
virtual char do_narrow(E ch, char dflt) const;
virtual const E *do_narrow(const E *first, const E *last,
char dflt, char *dst) const;
};
The template class describes an object that can serve as a locale
facet, to characterize various properties of a
"character" (element) of type E. Such a facet also converts between
sequences of E elements and sequences of
An object of class ctype<E> stores a pointer to the first element
of a ctype mask table, an array of UCHAR_MAX + 1 elements of type
ctype_base::mask. It also stores a Boolean object that indicates
whether the array should be deleted when the ctype<E> object is
destroyed.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
file:///D|/97/c++_1/LIBREF.TXT (173 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 173 of 619
stores a unique positive value in id.
The Standard C++ library defines two explicit specializations of
this template class:
lctype<char>, whose differences are described separately
lctype<wchar_t<, which treats elements as wide characters
In this implementation, other specializations of template class
ctype<E>:
lConvert a value ch of type E to a value of type char with
expression (char)ch.
lConvert a value c of type char to a value of type E with
expression E(c).
All other operations are performed on char values the same as for
specialization ctype<char>.
ctype::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
ctype::ctype
explicit ctype(size_t refs = 0);
The type is a synonym for the template parameter E.
ctype::do_is
virtual bool do_is(mask msk, E ch) const;
virtual const E *do_is(const E *first, const E *last,
mask *dst) const;
The first protected member template function returns true if table
[(unsigned char)(char)ch] & msk is nonzero, where table is the
stored pointer to the ctype mask table.
The second protected member template function stores in dst[I] the
value table[(unsigned char)(char)first[I]] & msk, where I ranges
over the interval [0, last - first).
ctype::do_narrow
virtual char do_narrow(E ch, char dflt) const;
virtual const E *do_narrow(const E *first, const E *last,
char dflt, char *dst) const;
The first protected member template function returns (char)ch, or
dflt if that expression is undefined.
The second protected member template function stores in dst[I] the
value do_narrow(first[I], dflt), for I in the interval [0, last -
first).
file:///D|/97/c++_1/LIBREF.TXT (174 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 174 of 619
ctype::do_scan_is
virtual const E *do_scan_is(mask msk, const E *first,
const E *last) const;
The protected member function returns the smallest pointer p in the
range [first, last) for which do_is(msk, *p) is true. If no such
value exists, the function returns last.
ctype::do_scan_not
virtual const E *do_scan_not(mask msk, const E *first,
const E *last) const;
The protected member function returns the smallest pointer p in the
range [first, last) for which do_is(msk, *p) is false. If no such
value exists, the function returns last.
ctype::do_tolower
virtual E do_tolower(E ch) const;
virtual const E *do_tolower(E *first, E *last) const;
The first protected member template function returns the lowercase
character corresponding to ch, if such a character exists.
Otherwise, it returns ch.
The second protected member template function replaces each element
first[I], for I in the interval [0, last - first), with do_tolower
(first[I].
ctype::do_toupper
virtual E do_toupper(E ch) const;
virtual const E *do_toupper(E *first, E *last) const;
The first protected member template function returns the uppercase
character corresponding to ch, if such a character exists.
Otherwise, it returns ch.
The second protected member template function replaces each element
first[I], for I in the interval [0, last - first), with do_toupper
(first[I].
ctype::do_widen
virtual E do_widen(char ch) const;
virtual const char *do_widen(char *first, char *last, E *dst) const;
The first protected member template function returns E(ch).
The second protected member template function stores in dst[I] the
value do_widen(first[I]), for I in the interval [0, last - first).
ctype::is
file:///D|/97/c++_1/LIBREF.TXT (175 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 175 of 619
bool is(mask msk, E ch) const;
const E *is(const E *first, const E *last, mask *dst) const;
The first member function returns do_is(msk, ch). The second member
function returns do_is(first, last, dst).
ctype::narrow
char narrow(E ch, char dflt) const;
const E *narrow(const E *first, const E *last,
char dflt, char *dst) const;
The first member function returns do_narrow(ch, dflt). The second
member function returns do_narrow(first, last, dflt, dst).
ctype::scan_is
const E *scan_is(mask msk, const E *first, const E *last) const;
The member function returns do_scan_is(msk, first, last).
ctype::scan_not
const E *scan_not(mask msk, const E *first, const E *last) const;
The member function returns do_scan_not(msk, first, last).
ctype::tolower
E tolower(E ch) const;
const E *tolower(E *first, E *last) const;
The member function returns do_tolower(first, last).
ctype::toupper
E toupper(E ch) const;
const E *toupper(E *first, E *last) const;
The member function returns do_toupper(first, last).
ctype::widen
E widen(char ch) const;
const char *widen(char *first, char *last, E *dst) const;
The member function returns do_widen(first, last, dst).
ctype<char>
class ctype<char> : public locale::facet, public ctype_base {
public:
typedef char char_type;
explicit ctype(const mask *tab = 0, bool del = false,
size_t refs = 0);
bool is(mask msk, char ch) const;
file:///D|/97/c++_1/LIBREF.TXT (176 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 176 of 619
const char *is(const char *first, const char *last,
mask *dst) const;
const char *scan_is(mask msk,
const char *first, const char *last) const;
const char *scan_not(mask msk,
const char *first, const char *last) const;
char toupper(char ch) const;
const char *toupper(char *first, char *last) const;
char tolower(char ch) const;
const char *tolower(char *first, char *last) const;
char widen(char ch) const;
const char *widen(char *first, char *last, char *dst) const;
char narrow(char ch, char dflt) const;
const char *narrow(const char *first, const char *last,
char dflt, char *dst) const;
static locale::id id;
protected:
~ctype();
virtual char do_toupper(char ch) const;
virtual const char *do_toupper(char *first, char *last) const;
virtual char do_tolower(char ch) const;
virtual const char *do_tolower(char *first, char *last) const;
const mask *table() const throw();
static const mask *classic_table() const throw();
static const size_t table_size;
};
The class is an explicit specialization of template class ctype for
type char. Hence, it describes an object that can serve as a
facet, to characterize various properties of a
"character" (element) of type char. The explicit
differs from the template class in several ways:
lIts sole public constructor lets you specify tab, the ctype
mask table, and del, the Boolean object that is true if the
array should be deleted when the ctype<char> object is
destroyed -- as well as the usual reference-count parameter
refs.
lThe protected member function table() returns the stored ctype
mask table.
lThe static member object table_size specifies the minimum
number of elements in a ctype mask table.
lThe protected static member function classic_table() returns
the ctype mask table appropriate to the "C" locale.
lThere are no protected virtual member functions do_is,
do_narrow, do_scan_is, do_scan_not, or do_widen. The
corresponding public member functions perform the equivalent
operations themselves.
lThe member functions narrow and widen simply copy elements
unaltered.
ctype_base
class ctype_base {
public:
enum mask;
static const mask space, print, cntrl,
file:///D|/97/c++_1/LIBREF.TXT (177 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 177 of 619
upper, lower, digit, punct, xdigit,
alpha, alnum, graph;
};
The class serves as a base class for facets of template class
ctype. It defines just the enumerated type mask and several
constants of this type. Each of the constants characterizes a
different way to classify characters, as defined by the functions
with similar names declared in the header <ctype.h>. The constants
are:
lspace (function isspace)
lprint (function isprint)
lcntrl (function iscntrl)
lupper (function isupper)
llower (function islower)
ldigit (function isdigit)
lpunct (function ispunct)
lxdigit (function isxdigit)
lalpha (function isalpha)
lalnum (function isalnum)
lgraph (function isgraph)
You can characterize a combination of classifications by ORing
these constants. In particular, it is always true that alnum ==
(alpha | digit) and graph == (alnum | punct).
ctype_byname
template<class E>
class ctype_byname : public ctype<E> {
public:
explicit ctype_byname(const char *s, size_t refs = 0);
protected:
~ctype_byname();
};
The template class describes an object that can serve as a locale
facet of type ctype<E>. Its behavior is determined by the named
locale s. The constructor initializes its base object with ctype<E>
(refs) (or the equivalent for base class ctype<char>).
has_facet
template<class Facet>
bool has_facet(const locale& loc, const Facet *fac);
The template function returns true if a locale facet of class Facet
is listed within the locale object loc.
In this implementation, you should write _HAS(loc, Facet) in place
of has_facet(loc, (Facet *)0), because the second parameter is a
nonstandard extension.
isalnum
template<class E>
file:///D|/97/c++_1/LIBREF.TXT (178 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 178 of 619
bool isalnum(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: alnum, c).
isalpha
template<class E>
bool isalpha(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: alpha, c).
iscntrl
template<class E>
bool iscntrl(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: cntrl, c).
isdigit
template<class E>
bool isdigit(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: digit, c).
isgraph
template<class E>
bool isgraph(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: graph, c).
islower
template<class E>
bool islower(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: lower, c).
isprint
template<class E>
bool isprint(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: print, c).
ispunct
template<class E>
bool ispunct(E c, const locale& loc) const;
file:///D|/97/c++_1/LIBREF.TXT (179 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 179 of 619
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: punct, c).
isspace
template<class E>
bool isspace(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: space, c).
isupper
template<class E>
bool isupper(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: upper, c).
isxdigit
template<class E>
bool isxdigit(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). is
(ctype<E>:: xdigit, c).
locale
category . classic . facet . global . id . locale . name .
operator!= . operator() . operator==
class locale {
public:
class facet;
class id;
typedef int category;
static const category none, collate, ctype, monetary,
numeric, time, messages, all;
locale();
explicit locale(const char *s);
locale(const locale& x, const locale& y,
category cat);
locale(const locale& x, const char *s, category cat);
bool operator()(const string& lhs,
const string& rhs) const;
string name() const;
bool operator==(const locale& x) const;
bool operator!=(const locale& x) const;
static locale global(const locale& x);
static const locale& classic();
};
The class describes a locale object that encapsulates a locale. It
represents culture-specific information as a list of facets. A
facet is a pointer to an object of a class derived from class facet
file:///D|/97/c++_1/LIBREF.TXT (180 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 180 of 619
that has a public object of the form:
static locale::id id;
You can define an open-ended set of these facets. You can also
construct a locale object that designates an arbitrary number of
facets.
Predefined groups of these facets represent the locale categories
traditionally managed in the Standard C library by the function
setlocale.
Category collate (LC_COLLATE) includes the facets:
collate<char>
collate<wchar_t>
Category ctype (LC_CTYPE) includes the facets:
ctype<char>
ctype<wchar_t>
codecvt<char, char, mbstate_t>
codecvt<wchar_t, char, mbstate_t>
Category monetary (LC_MONETARY) includes the facets:
moneypunct<char, false>
moneypunct<wchar_t, false>
moneypunct<char, true>
moneypunct<wchar_t, true>
money_get<char, istreambuf_iterator<char> >
money_get<wchar_t, istreambuf_iterator<wchar_t> >
money_put<char, ostreambuf_iterator<char> >
money_put<wchar_t, ostreambuf_iterator<wchar_t> >
Category numeric (LC_NUMERIC) includes the facets:
num_get<char, istreambuf_iterator<char> >
num_get<wchar_t, istreambuf_iterator<wchar_t> >
num_put<char, ostreambuf_iterator<char> >
num_put<wchar_t, ostreambuf_iterator<wchar_t> >
numpunct<char>
numpunct<wchar_t>
Category time (LC_TIME) includes the facets:
time_get<char, istreambuf_iterator<char> >
time_get<wchar_t, istreambuf_iterator<wchar_t> >
time_put<char, ostreambuf_iterator<char> >
time_put<wchar_t, ostreambuf_iterator<wchar_t> >
Category messages (LC_MESSAGE) includes the facets:
messages<char>
messages<wchar_t>
(The last category is required by Posix, but not the C Standard.)
file:///D|/97/c++_1/LIBREF.TXT (181 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 181 of 619
Some of these predefined facets are used by the iostreams classes
to control the conversion of numeric values to and from text
sequences.
An object of class locale also stores a locale name as an object of
class string. Using an invalid locale name to construct a locale
facet or a locale object throws an object of class runtime_error.
If the stored locale name is "*", no C-style locale corresponds
exactly to that represented by the object. Otherwise, you can
establish a matching locale within the Standard C library by
calling setlocale( LC_ALL, x.name. c_str()).
In this implementation, you can also call the static member
function:
static locale empty();
to construct a locale object that has no facets. It is also a
transparent locale -- the template function use_facet consults the
global locale if it cannot find the requested facet in a
transparent locale. Thus, you can write:
cout.imbue(locale::empty());
Subsequent insertions to cout are mediated by the current state of
the global locale. You can even write:
locale loc(locale::empty(), locale("C"), locale::numeric);
cout.imbue(loc);
Numeric formatting rules remain the same as in the C locale even as
the global locale supplies changing rules for inserting dates and
monetary amounts.
locale::category
typedef int category;
static const category none, collate, ctype, monetary,
numeric, time, messages, all;
The type is a synonym for int, so that it can represent any of the
locale categories. It can also represent a group of constants local
to class locale:
lnone, corresponding to none of the C categories
lcollate, corresponding to the C category LC_COLLATE
lctype, corresponding to the C category LC_CTYPE
lmonetary, corresponding to the C category LC_MONETARY
lnumeric, corresponding to the C category LC_NUMERIC
ltime, corresponding to the C category LC_TIME
lmessages, corresponding to the Posix category LC_MESSAGE
lall, corresponding to the C union of all categories LC_ALL
You can represent an arbitrary group of categories by ORing these
constants, as in monetary | time.
file:///D|/97/c++_1/LIBREF.TXT (182 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 182 of 619
locale::classic
static const locale& classic();
The static member function returns a locale object that represents
the C locale.
locale::facet
class facet {
protected:
explicit facet(size_t refs = 0);
virtual ~facet();
private:
facet(const facet&) // not defined
void operator=(const facet&) // not defined
};
The member class serves as the base class for all locale facets.
Note that you can neither copy nor assign an object of class facet.
You can construct and destroy objects derived from class
locale::facet, but not objects of the base class proper. Typically,
you construct an object myfac derived from facet when you construct
a locale, as in:
locale loc(locale::classic(), new myfac);
In such cases, the constructor for the base class facet should have
a zero refs argument. When the object is no longer needed, it is
deleted. Thus, you supply a nonzero refs argument only in those
rare cases where you take responsibility for the lifetime of the
object.
locale::global
static locale global(const locale& x);
The static member function stores a copy of x as the global locale.
It also calls setlocale( LC_ALL, x.name. c_str()), to establish a
matching locale within the Standard C library. The function then
returns the previous global locale. At program startup, the global
locale represents the C locale.
locale::id
class id {
protected:
id();
private:
id(const id&) // not defined
void operator=(const id&) // not defined
};
The member class describes the static member object required by
each unique locale facet. Note that you can neither copy nor assign
an object of class id.
file:///D|/97/c++_1/LIBREF.TXT (183 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 183 of 619
locale::locale
locale();
explicit locale(const char *s);
locale(const locale& x, const locale& y,
category cat);
locale(const locale& x, const char *s, category cat);
The first constructor initializes the object to match the global
locale. The second constructor initializes all the locale
categories to have behavior consistent with the locale name s. The
remaining constructors copy x, with the exceptions noted:
locale(const locale& x, const locale& y,
category cat);
replaces from y those facets corresponding to a category c for
which c & cat is nonzero.
locale(const locale& x, const char *s, category cat);
replaces from locale(s, all) those facets corresponding to a
category c for which c & cat is nonzero.
In this implementation, you should write _ADDFAC(loc, Facet) to
return a new locale that adds the facet Facet to the locale loc,
since not all translators currently support the additional template
constructors:
template<class Facet>
locale(const locale& x, Facet *fac);
template<class Facet>
locale(const locale& x, const locale& y);
If a locale name s is a null pointer or otherwise invalid, the
function throws runtime_error.
locale::name
string name() const;
The member function returns the stored locale name.
locale::operator!=
bool operator!=(const locale& x) const;
The member function returns !(*this == x).
locale::operator()
bool operator()(const string& lhs, const string& rhs);
The member function effectively executes:
file:///D|/97/c++_1/LIBREF.TXT (184 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 184 of 619
const collate<E>& fac = use_fac<collate<E> >(*this);
return (fac.compare(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end()) < 0);
Thus, you can use a locale object as a function object.
In this implementation, if a translator does not support member
template functions, the template:
template<class E, class T, class A>
bool operator()(const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
is replaced by:
bool operator()(const string& lhs, const string& rhs);
locale::operator==
bool operator==(const locale& x) const;
The member function returns true only if *this and x are copies of
the same locale or have the same name (other than "*").
messages
template<class E>
class messages : public locale::facet, public messages_base {
public:
typedef E char_type;
typedef basic_string<E> string_type;
explicit messages(size_t refs = 0);
catalog open(const string& name,
const locale& loc) const;
string_type get(catalog cat, int set, int msg,
const string_type& dflt) const;
void close(catalog cat) const;
static locale::id id;
protected:
~messages();
virtual catalog do_open(const string& name,
const locale& loc) const;
virtual string_type do_get(catalog cat, int set, int msg,
const string_type& dflt) const;
virtual void do_close(catalog cat) const;
};
The template class describes an object that can serve as a locale
facet, to characterize various properties of a message catalog that
can supply messages represented as sequences of elements of type E.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
messages::char_type
file:///D|/97/c++_1/LIBREF.TXT (185 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 185 of 619
typedef E char_type;
The type is a synonym for the template parameter E.
messages::close
void close(catalog cat) const;
The member function calls do_close(cat);.
messages::do_close
virtual void do_close(catalog cat) const;
The protected member function closes the message catalog, which
must have been opened by an earlier call to do_open.
messages::do_get
virtual string_type do_get(catalog cat, int set, int msg,
const string_type& dflt) const;
The protected member function endeavors to obtain a message
sequence from the message catalog cat. It may make use of set, msg,
and dflt in doing so. It returns a copy of dflt on failure.
Otherwise, it returns a copy of the specified message sequence.
In this implementation, the function returns a locale-specific
version of the sequence no if msg is zero. It returns a locale-
specific version of the sequence yes if msg is one. Otherwise, it
returns dflt.
messages::do_open
virtual catalog do_open(const string& name,
const locale& loc) const;
The protected member function endeavors to open a message catalog
whose name is name. It may make use of the locale loc in doing so.
It returns a value that compares less than zero on failure.
Otherwise, the returned value can be used as the first argument on
a later call to get. It should in any case be used as the argument
on a later call to close.
In this implementation, the function always returns zero.
messages::get
string_type get(catalog cat, int set, int msg,
const string_type& dflt) const;
The member function returns do_get(cat, set, msg, dflt);.
messages::messages
explicit messages(size_t refs = 0);
file:///D|/97/c++_1/LIBREF.TXT (186 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 186 of 619
The constructor initializes its base object with locale::facet
(refs).
messages::open
catalog open(const string& name,
const locale& loc) const;
The member function returns do_open(name, loc);.
messages::string_type
typedef basic_string<E> string_type;
The type describes a specialization of template class basic_string
whose objects can store copies of the message sequences.
messages_base
class messages_base {
typedef int catalog;
};
The class describes a type common to all specializations of
template class messages. The type catalog is a synonym for type
that describes the possible return values from messages::do_open.
messages_byname
template<class E>
class messages_byname : public messages<E> {
public:
explicit messages_byname(const char *s, size_t refs = 0);
protected:
~messages_byname();
};
The template class describes an object that can serve as a locale
facet of type messages<E>. Its behavior is determined by the named
locale s. The constructor initializes its base object with
messages<E>(refs).
money_base
class money_base {
enum part {none, sign, space,
symbol, value};
struct pattern {
char field[4];
};
};
The class describes an enumeration and a structure common to all
specializations of template class moneypunct. The enumeration part
describes the possible values in elements of the array field in the
structure pattern. The values of part are:
file:///D|/97/c++_1/LIBREF.TXT (187 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 187 of 619
lnone to match zero or more spaces or generate nothing
lsign to match or generate a positive or negative sign
lspace to match zero or more spaces or generate a space
lsymbol to match or generate a currency symbol
lvalue to match or generate a monetary value
money_get
template<class E,
class InIt = istreambuf_iterator<E> >
class money_get : public locale::facet {
public:
typedef E char_type;
typedef InIt iter_type;
typedef basic_string<E> string_type;
explicit money_get(size_t refs = 0);
iter_type get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, long double& val) const;
iter_type get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, string_type& val) const;
static locale::id id;
protected:
~money_get();
virtual iter_type do_get(iter_type first, iter_type last, bool i
ios_base& x, ios_base::iostate& st, string_type& val) const;
virtual iter_type do_get(iter_type first, iter_type last, bool i
ios_base& x, ios_base::iostate& st, long double& val) const;
};
The template class describes an object that can serve as a locale
facet, to control conversions of sequences of type E to monetary
values.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
money_get::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
money_get::do_get
virtual iter_type do_get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, string_type& val) const;
virtual iter_type do_get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, long double& val) const;
The first virtual protected member function endeavors to match
sequential elements beginning at first in the sequence [first,
last) until it has recognized a complete, nonempty monetary input
field. If successful, it converts this field to a sequence of one
or more decimal digits, optionally preceded by a minus sign (-), to
represent the amount and stores the result in the string_type
file:///D|/97/c++_1/LIBREF.TXT (188 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 188 of 619
object val. It returns an iterator designating the first element
beyond the monetary input field. Otherwise, the function stores an
empty sequence in val and sets ios_base::failbit in st. It returns
an iterator designating the first element beyond any prefix of a
valid monetary input field. In either case, if the return value
equals last, the function sets ios_base::eofbit in st.
The second virtual protected member function behaves the same as
the first, except that, if successful, it converts the optionally-
signed digit sequence to a value of type long double and stores
value in val.
The format of a monetary input field is determined by the locale
facet fac returned by the (effective) call use_facet <moneypunct<E,
intl>(x. getloc()). Specifically:
lfac.neg_format() determines the order in which components of
the field occur
lfac.curr_symbol() determines the sequence of elements that
constitutes a currency symbol
lfac.positive_sign() determines the sequence of elements that
constitutes a positive sign
lfac.negative_sign() determines the sequence of elements that
constitutes a negative sign
lfac.grouping() determines how digits are grouped to the left of
any decimal point
lfac.thousands_sep() determines the element that separates
groups of digits to the left of any decimal point
lfac.decimal_point() determines the element that separates the
integer digits from the fraction digits
lfac.frac_digits() determines the number of significant fraction
digits to the right of any decimal point
If the sign string (fac.negative_sign or fac.positive_sign) has
more than one element, only the first element is matched where the
element equal to money_base::sign appears in the format pattern
(fac.neg_format). Any remaining elements are matched at the end of
the monetary input field. If neither string has a first element
that matches the next element in the monetary input field, the sign
string is taken as empty and the sign is positive.
If x.flags() & showbase is nonzero, the string fac.curr_symbol must
match where the element equal to money_base::symbol appears in the
format pattern. Otherwise, if money_base::symbol occurs at the end
of the format pattern, and if no elements of the sign string remain
to be matched, the currency symbol is not matched. Otherwise, the
currency symbol is optionally matched.
If no instances of fac.thousands_sep() occur in the value portion
of the monetary input field (where the element equal to
money_base::value appears in the format pattern), no grouping
constraint is imposed. Otherwise, any grouping constraints imposed
by fac.grouping() are enforced. Note that the resulting digit
sequence represents an integer whose low-order fac.frac_digits()
decimal digits are considered to the right of the decimal point.
Arbitrary white space is matched where the element equal to
file:///D|/97/c++_1/LIBREF.TXT (189 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 189 of 619
money_base::space appears in the format pattern, if it appears
other than at the end of the format pattern. Otherwise, no internal
white space is matched. An element c is considered white space if
use_facet <ctype<E>(x. getloc()). is(ctype_base:: space, c) is
true.
money_get::get
iter_type get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, long double& val) const;
iter_type get(iter_type first, iter_type last, bool intl,
ios_base& x, ios_base::iostate& st, string_type& val) const;
Both member functions return do_get(first, last, intl, x, st, val).
money_get::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter InIt.
money_get::money_get
explicit money_get(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
money_get::string_type
typedef basic_string<E> string_type;
The type describes a specialization of template class basic_string
whose objects can store sequences of elements from the source
sequence.
money_put
template<class E,
class OutIt = ostreambuf_iterator<E> >
class money_put : public locale::facet {
public:
typedef E char_type;
typedef OutIt iter_type;
typedef basic_string<E> string_type;
explicit money_put(size_t refs = 0);
iter_type put(iter_type next, bool intl, ios_base& x,
E fill, long double& val) const;
iter_type put(iter_type next, bool intl, ios_base& x,
E fill, string_type& val) const;
static locale::id id;
protected:
~money_put();
virtual iter_type do_put(iter_type next, bool intl,
ios_base& x, E fill, string_type& val) const;
virtual iter_type do_put(iter_type next, bool intl,
ios_base& x, E fill, long double& val) const;
file:///D|/97/c++_1/LIBREF.TXT (190 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 190 of 619
};
The template class describes an object that can serve as a locale
facet, to control conversions of monetary values to sequences of
type E.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
money_put::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
money_put::do_put
virtual iter_type do_put(iter_type next, bool intl,
ios_base& x, E fill, string_type& val) const;
virtual iter_type do_put(iter_type next, bool intl,
ios_base& x, E fill, long double& val) const;
The first virtual protected member function generates sequential
elements beginning at next to produce a monetary output field from
the string_type object val. The sequence controlled by val must
begin with one or more decimal digits, optionally preceded by a
minus sign (-), which represents the amount. The function returns
an iterator designating the first element beyond the generated
monetary output field.
The second virtual protected member function behaves the same as
the first, except that it effectively first converts val to a
sequence of decimal digits, optionally preceded by a minus sign,
then converts that sequence as above.
The format of a monetary output field is determined by the locale
facet fac returned by the (effective) call use_facet <moneypunct<E,
intl>(x. getloc()). Specifically:
lfac.pos_format() determines the order in which components of
the field are generated for a non-negative value.
lfac.neg_format() determines the order in which components of
the field are generated for a negative value.
lfac.curr_symbol() determines the sequence of elements to
generate for a currency symbol.
lfac.positive_sign() determines the sequence of elements to
generate for a positive sign.
lfac.negative_sign() determines the sequence of elements to
generate for a negative sign.
lfac.grouping() determines how digits are grouped to the left of
any decimal point.
lfac.thousands_sep() determines the element that separates
groups of digits to the left of any decimal point.
lfac.decimal_point() determines the element that separates the
integer digits from any fraction digits.
lfac.frac_digits() determines the number of significant fraction
file:///D|/97/c++_1/LIBREF.TXT (191 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 191 of 619
digits to the right of any decimal point.
If the sign string (fac.negative_sign or fac.positive_sign) has
more than one element, only the first element is generated where
the element equal to money_base::sign appears in the format pattern
(fac.neg_format or fac.pos_format). Any remaining elements are
generated at the end of the monetary output field.
If x.flags() & showbase is nonzero, the string fac.curr_symbol is
generated where the element equal to money_base::symbol appears in
the format pattern. Otherwise, no currency symbol is generated.
If no grouping constraints are imposed by fac.grouping() (its first
element has the value CHAR_MAX), then no instances of
fac.thousands_sep() are generated in the value portion of the
monetary output field (where the element equal to money_base::value
appears in the format pattern). If fac.frac_digits() is zero, then
no instance of fac.decimal_point() is generated after the decimal
digits. Otherwise, the resulting monetary output field places the
low-order fac.frac_digits() decimal digits to the right of the
decimal point.
Padding occurs as for any numeric output field, except that if
x.flags() & x.internal is nonzero, any internal padding is
generated where the element equal to money_base::space appears in
the format pattern, if the element does appear. Otherwise, internal
padding occurs before the generated sequence. The padding character
is fill.
The function calls x.width(0) to reset the field width to zero.
money_put::put
iter_type put(iter_type next, bool intl, ios_base& x,
E fill, long double& val) const;
iter_type put(iter_type iter_type next, bool intl, ios_base& x,
E fill, string_type& val) const;
Both member functions return do_put(next, intl, x, fill, val).
money_put::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter OutIt.
money_put::money_put
explicit money_put(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
money_put::string_type
typedef basic_string<E> string_type;
file:///D|/97/c++_1/LIBREF.TXT (192 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 192 of 619
The type describes a specialization of template class basic_string
whose objects can store sequences of elements from the source
sequence.
moneypunct
char_type . curr_symbol . decimal_point . do_curr_symbol .
do_decimal_point . do_frac_digits . do_grouping . do_neg_format .
do_negative_sign . do_pos_format . do_positive_sign .
do_thousands_sep .
frac_digits . grouping . moneypunct . neg_format
. negative_sign . pos_format . positive_sign . string_type .
thousands_sep
template<class E, bool Intl>
class moneypunct : public locale::facet, public money_base {
public:
typedef E char_type;
typedef basic_string<E> string_type;
explicit moneypunct(size_t refs = 0);
E decimal_point() const;
E thousands_sep() const;
string grouping() const;
string_type curr_symbol() const;
string_type positive_sign() const;
string_type negative_sign() const;
int frac_digits() const;
pattern pos_format( oonst;
pattern neg_format() const;
static const bool intl = Intl;
static locale::id id;
protected:
~moneypunct();
virtual E do_decimal_point() const;
virtual E do_thousands_sep() const;
virtual string do_grouping() const;
virtual string_type do_curr_symbol() const;
virtual string_type do_positive_sign() const;
virtual string_type do_negative_sign() const;
virtual int do_frac_digits() const;
virtual pattern do_pos_format() const;
virtual pattern do_neg_format() const;
};
The template class describes an object that can serve as a locale
facet, to describe the sequences of type E used to represent a
monetary input field or a monetary output field. If the template
parameter Intl is true, international conventions are observed.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
The const static object intl stores the value of the template
parameter Intl.
moneypunct::char_type
file:///D|/97/c++_1/LIBREF.TXT (193 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 193 of 619
typedef E char_type;
The type is a synonym for the template parameter E.
moneypunct::curr_symbol
string_type curr_symbol() const;
The member function returns do_curr_symbol().
moneypunct::decimal_point
E decimal_point() const;
The member function returns do_decimal_point().
moneypunct::do_curr_symbol
string_type do_curr_symbol() const;
The protected virtual member function returns a locale-specific
sequence of elements to use as a currency symbol.
moneypunct::do_decimal_point
E do_decimal_point() const;
The protected virtual member function returns a locale-specific
element to use as a decimal point.
moneypunct::do_frac_digits
int do_frac_digits() const;
The protected virtual member function returns a locale-specific
count of the number of digits to display to the right of any
decimal point.
moneypunct::do_grouping
string do_grouping() const;
The protected virtual member function returns a locale-specific
rule for determining how digits are grouped to the left of any
decimal point. The encoding is the same as for lconv::grouping.
moneypunct::do_neg_format
pattern do_neg_format() const;
The protected virtual member function returns a locale-specific
rule for determining how to generate a monetary output field for a
negative amount. Each of the four elements of pattern::field can
have the values:
lnone to match zero or more spaces or generate nothing
file:///D|/97/c++_1/LIBREF.TXT (194 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 194 of 619
lsign to match or generate a positive or negative sign
lspace to match zero or more spaces or generate a space
lsymbol to match or generate a currency symbol
lvalue to match or generate a monetary value
Components of a monetary output field are generated (and components
of a monetary input field are matched) in the order in which these
elements appear in pattern::field. Each of the values sign, symbol,
value, and either none or space must appear exactly once. The value
none must not appear first. The value space must not appear first
or last. If Intl is true, the order is symbol, sign, none, then
value.
The template version of moneypunct<E, Intl> returns
{money_base::symbol, money_base::sign, money_base::value,
money_base::none}.
moneypunct::do_negative_sign
string_type do_negative_sign() const;
The protected virtual member function returns a locale-specific
sequence of elements to use as a negative sign.
moneypunct::do_pos_format
pattern do_pos_format() const;
The protected virtual member function returns a locale-specific
rule for determining how to generate a monetary output field for a
positive amount. (It also determines how to match the components of
a monetary input field.) The encoding is the same as for
do_neg_format.
The template version of moneypunct<E, Intl> returns
{money_base::symbol, money_base::sign, money_base::value,
money_base::none}.
moneypunct::do_positive_sign
string_type do_positive_sign() const;
The protected virtual member function returns a locale-specific
sequence of elements to use as a positive sign.
moneypunct::do_thousands_sep
E do_thousands_sep() const;
The protected virtual member function returns a locale-specific
element to use as a group separator to the left of any decimal
point.
moneypunct::frac_digits
int frac_digits() const;
file:///D|/97/c++_1/LIBREF.TXT (195 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 195 of 619
The member function returns do_frac_digits().
moneypunct::grouping
string grouping() const;
The member function returns do_grouping().
moneypunct::moneypunct
explicit moneypunct(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
moneypunct::neg_format
pattern neg_format() const;
The member function returns do_neg_format().
moneypunct::negative_sign
string_type negative_sign() const;
The member function returns do_negative_sign().
moneypunct::pos_format
pattern pos_format() const;
The member function returns do_pos_format().
moneypunct::positive_sign
string_type positive_sign() const;
The member function returns do_positive_sign().
moneypunct::string_type
typedef basic_string<E> string_type;
The type describes a specialization of template class basic_string
whose objects can store copies of the punctuation sequences.
moneypunct::thousands_sep
E thousands_sep() const;
The member function returns do_thousands_sep().
moneypunct_byname
template<class E, bool Intl>
class moneypunct_byname : public moneypunct<E, Intl> {
file:///D|/97/c++_1/LIBREF.TXT (196 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 196 of 619
public:
explicit moneypunct_byname(const char *s, size_t refs = 0);
protected:
~moneypunct_byname();
};
The template class describes an object that can serve as a locale
facet of type moneypunct<E, Intl>. Its behavior is determined by
the named locale s. The constructor initializes its base object
with moneypunct<E, Intl>(refs).
num_get
template<class E, class InIt = istreambuf_iterator<E> >
class num_get : public locale::facet {
public:
typedef E char_type;
typedef InIt iter_type;
explicit num_get(size_t refs = 0);
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, long& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, unsigned long& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, double& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, long double& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, void *& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, bool& val) const;
static locale::id id;
protected:
~num_get();
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, long& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, unsigned long& val) cons
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, double& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, long double& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, void *& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, bool& val) const;
};
The template class describes an object that can serve as a locale
facet, to control conversions of sequences of type E to numeric
values.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
file:///D|/97/c++_1/LIBREF.TXT (197 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 197 of 619
num_get::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
num_get::do_get
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, long& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, unsigned long& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, double& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, long double& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, void *& val) const;
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, bool& val) const;
The first virtual protected member function endeavors to match
sequential elements beginning at first in the sequence [first,
last) until it has recognized a complete, nonempty integer input
field. If successful, it converts this field to its equivalent
value as type long, and stores the result in val. It returns
iterator designating the first element beyond the numeric input
field. Otherwise, the function stores nothing in val and sets
ios_base::failbit in st. It returns an iterator designating the
first element beyond any prefix of a valid integer input field. In
either case, if the return value equals last, the function sets
ios_base::eofbit in st.
The integer input field is converted by the same rules used by the
scan functions for matching and converting a series of char
from a file. (Each such char element is assumed to map to
equivalent element of type E by a simple, one-to-one, mapping.) The
equivalent scan conversion specification is determined as follows:
lIf x.flags() & ios_base::basefield == ios_base::oct, the
conversion specification is lo.
lIf x.flags() & ios_base::basefield == ios_base::hex, the
conversion specification is lx.
lIf x.flags() & ios_base::basefield == 0, the conversion
specification is li.
lOtherwise, the conversion specification is ld.
The format of an integer input field is further determined by the
locale facet fac returned by the call use_facet <numpunct<E>(x.
getloc()). Specifically:
lfac.grouping() determines how digits are grouped to the left of
any decimal point.
lfac.thousands_sep() determines the sequence that separates
groups of digits to the left of any decimal point.
file:///D|/97/c++_1/LIBREF.TXT (198 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 198 of 619
If no instances of fac.thousands_sep() occur in the numeric input
field, no grouping constraint is imposed. Otherwise, any grouping
constraints imposed by fac.grouping() is enforced and separators
are removed before the scan conversion occurs.
The second virtual protected member function:
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, unsigned long& val) const;
behaves the same as the first, except that it replaces a conversion
specification of ld with lu. If successful it converts the numeric
input field to a value of type unsigned long and stores that value
The third virtual protected member function:
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, double& val) const;
behaves the same as the first, except that it endeavors to match a
complete, nonempty floating-point input field. fac.decimal_point()
determines the sequence that separates the integer digits from the
fraction digits. The equivalent scan conversion specifier is lf.
The fourth virtual protected member function:
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, long double& val) const;
behaves the same as the third, except that the equivalent scan
conversion specifier is Lf.
The fifth virtual protected member function:
virtual iter_type do_get(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, void *& val) const;
behaves the same as the first, except that the equivalent scan
conversion specifier is p.
The sixth virtual protected member function:
virtual iter_type do_get(iter_type first, iter_type last, ios_base&
ios_base::iostate& st, bool& val) const;
behaves the same as the first, except that it endeavors to match a
complete, nonempty Boolean input field. If successful, it converts
the Boolean input field to a value of type bool and stores that
value in val.
A Boolean input field takes one of two forms. If x.flags() &
ios_base::boolalpha is false, it is the same as an integer input
field, except that the converted value must be either 0 (for false)
or 1 (for true). Otherwise, the sequence must match either
fac.falsename() (for false), or fac.truename() (for true).
file:///D|/97/c++_1/LIBREF.TXT (199 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 199 of 619
num_get::get
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, long& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, unsigned long& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, double& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, long double& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, void *& val) const;
iter_type get(iter_type first, iter_type last, ios_base& x,
ios_base::iostate& st, bool& val) const;
All member functions return do_get(first, last, x, st, val).
num_get::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter InIt.
num_get::num_get
explicit num_get(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
num_put
template<class E, class OutIt = ostreambuf_iterator<E> >
class num_put : public locale::facet {
public:
typedef E char_type;
typedef OutIt iter_type;
explicit num_put(size_t refs = 0);
iter_type put(iter_type next, ios_base& x,
E fill, long val) const;
iter_type put(iter_type next, ios_base& x,
E fill, unsigned long val) const;
iter_type put(iter_type next, ios_base& x,
E fill, double val) const;
iter_type put(iter_type next, ios_base& x,
E fill, long double val) const;
iter_type put(iter_type next, ios_base& x,
E fill, const void *val) const;
iter_type put(iter_type next, ios_base& x,
E fill, bool val) const;
static locale::id id;
protected:
~num_put();
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, long val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
file:///D|/97/c++_1/LIBREF.TXT (200 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 200 of 619
E fill, unsigned long val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, double val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, long double val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, const void *val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, bool val) const;
};
The template class describes an object that can serve as a locale
facet, to control conversions of numeric values to sequences of
type E.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
num_put::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
num_put::do_put
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, long val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, unsigned long val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, double val) const;
virtual iter_type do_put(iter_type nextp ios_base& x,
E fill, long double val) const;
virtual iter_type do_put(iter_type nextp ios_base& x,
E fill, const void *val) const;
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, bool val) const;
The first virtual protected member function generates sequential
elements beginning at next to produce an integer output field from
the value of val. The function returns an iterator designating the
next place to insert an element beyond the generated integer output
field.
The integer output field is generated by the same rules used by the
print functions for generating a series of char elements to a
(Each such char element is assumed to map to an equivalent element
type E by a simple, one-to-one, mapping.) Where a print function
pads a field with either spaces or the digit 0, however, do_put
instead uses fill. The equivalent print conversion specification is
determined as follows:
lIf x.flags() & ios_base::basefield == ios_base::oct, the
conversion specification is lo.
lIf x.flags() & ios_base::basefield == ios_base::hex, the
file:///D|/97/c++_1/LIBREF.TXT (201 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 201 of 619
conversion specification is lx.
lOtherwise, the conversion specification is ld.
If x.width() is nonzero, a field width of this value is prepended.
The function then calls x.width(0) to reset the field width to
zero.
Padding occurs only if the minimum number of elements N required to
specify the output field is less than x.width(). Such padding
consists of a sequence of N - width() copies of fill. Padding then
occurs as follows:
lIf x.flags() & ios_base::adjustfield == ios_base::left, the
flag - is prepended. (Padding occurs after the generated text.)
lIf x.flags() & ios_base::adjustfield == ios_base::internal, the
flag 0 is prepended. (For a numeric output field, padding
occurs where the print functions pad with 0.)
lOtherwise, no additional flag is prepended. (Padding occurs
before the generated sequence.)
Finally:
lIf x.flags() & ios_base::showpos is nonzero, the flag + is
prepended to the conversion specification.
lIf x.flags() & ios_base::showbase is nonzero, the flag # is
prepended to the conversion specification.
The format of an integer output field is further determined by the
locale facet fac returned by the call use_facet <numpunct<E>(x.
getloc()). Specifically:
lfac.grouping() determines how digits are grouped to the left of
any decimal point
lfac.thousands_sep() determines the sequence that separates
groups of digits to the left of any decimal point
If no grouping constraints are imposed by fac.grouping() (its first
element has the value CHAR_MAX) then no instances of
fac.thousands_sep() are generated in the output field. Otherwise,
separators are inserted after the print conversion occurs.
The second virtual protected member function:
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, unsigned long val) const;
behaves the same as the first, except that it replaces a conversion
specification of ld with lu.
The third virtual protected member function:
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, double val) const;
behaves the same as the first, except that it produces a floating-
point output field from the value of val. fac.decimal_point()
determines the sequence that separates the integer digits from the
file:///D|/97/c++_1/LIBREF.TXT (202 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 202 of 619
fraction digits. The equivalent print conversion specifier is
determined as follows:
lIf x.flags() & ios_base::floatfield == ios_base::fixed, the
conversion specification is lf.
lIf x.flags() & ios_base::floatfield == ios_base::scientific,
the conversion specification is le. If x.flags() &
ios_base::uppercase is nonzero, e is replaced with E.
lOtherwise, the conversion specification is lg. If x.flags() &
ios_base::uppercase is nonzero, g is replaced with G.
If x.flags() & ios_base::fixed is nonzero, or if x.precision() is
greater than zero, a precision with the value x.precision() is
prepended to the conversion specification. Any padding behaves the
same as for an integer output field. The padding character is fill.
Finally:
lIf x.flags() & ios_base::showpos is nonzero, the flag + is
prepended to the conversion specification.
lIf x.flags() & ios_base::showpoint is nonzero, the flag # is
prepended to the conversion specification.
The fourth virtual protected member function:
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, long double val) const;
behaves the same as the third, except that the qualifier l in the
conversion specification is replaced with L.
The fifth virtual protected member function:
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, const void *val) const;
behaves the same as the first, except that the conversion
specification is p, plus any qualifier needed to specify padding.
The sixth virtual protected member function:
virtual iter_type do_put(iter_type next, ios_base& x,
E fill, bool val) const;
behaves the same as the first, except that it generates a Boolean
output field from val.
A Boolean output field takes one of two forms. If x.flags() &
ios_base::boolalpha is false, the generated sequence is either 0
(for false) or 1 (for true). Otherwise, the generated sequence is
either fac.falsename() (for false), or fac.truename() (for true).
num_put::put
iter_type put(iter_type next, ios_base& x,
E fill, long val) const;
iter_type put(iter_type next, ios_base& x,
E fill, unsigned long val) const;
file:///D|/97/c++_1/LIBREF.TXT (203 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 203 of 619
iter_type put(iter_type iter_type next, ios_base& x,
E fill, double val) const;
iter_type put(iter_type next, ios_base& x,
E fill, long double val) const;
iter_type put(iter_type next, ios_base& x,
E fill, const void *val) const;
iter_type put(iter_type next, ios_base& x,
E fill, bool val) const;
All member functions return do_put(next, x, fill, val).
num_put::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter OutIt.
num_put::num_put
explicit num_put(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
numpunct
char_type . decimal_point . do_decimal_point . do_falsename .
do_grouping . do_truename . do_thousands_sep . falsename . grouping
. numpunct . string_type . thousands_sep . truename
template<class E, class numpunct : public locale::facet {
public:
typedef E char_type;
typedef basic_string<E> string_type;
explicit numpunct(size_t refs = 0);
E decimal_point() const;
E thousands_sep() const;
string grouping() const;
string_type truename() const;
string_type falsename() const;
static locale::id id;
protected:
~numpunct();
virtual E do_decimal_point() const;
virtual E do_thousands_sep() const;
virtual string do_grouping() const;
virtual string_type do_truename() const;
virtual string_type do_falsename() const;
};
The template class describes an object that can serve as a locale
facet, to describe the sequences of type E used to represent the
input fields matched by num_get or the output fields generated by
num_get.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
file:///D|/97/c++_1/LIBREF.TXT (204 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 204 of 619
stores a unique positive value in id.
numpunct::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
numpunct::decimal_point
E decimal_point() const;
The member function returns do_decimal_point().
numpunct::do_decimal_point
E do_decimal_point() const;
The protected virtual member function returns a locale-specific
element to use as a decimal point.
numpunct::do_falsename
string_type do_falsename() const;
The protected virtual member function returns a locale-specific
sequence to use as a text representation of the value false.
numpunct::do_grouping
string do_grouping() const;
The protected virtual member function returns a locale-specific
rule for determining how digits are grouped to the left of any
decimal point. The encoding is the same as for lconv::grouping.
numpunct::do_thousands_sep
E do_thousands_sep() const;
The protected virtual member function returns a locale-specific
element to use as a group separator to the left of any decimal
point.
numpunct::do_truename
string_type do_truename() const;
The protected virtual member function returns a locale-specific
sequence to use as a text representation of the value true.
numpunct::falsename
string_type falsename() const;
The member function returns do_falsename().
file:///D|/97/c++_1/LIBREF.TXT (205 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 205 of 619
numpunct::grouping
string grouping() const;
The member function returns do_grouping().
numpunct::numpunct
explicit numpunct(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
numpunct::string_type
typedef basic_string<E> string_type;
The type describes a specialization of template class basic_string
whose objects can store copies of the punctuation sequences.
numpunct::thousands_sep
E thousands_sep() const;
The member function returns do_thousands_sep().
numpunct::truename
string_type truename() const;
The member function returns do_truename().
numpunct_byname
template<class E>
class numpunct_byname : public numpunct<E> {
public:
explicit numpunct_byname(const char *s, size_t refs = 0);
protected:
~numpunct_byname();
};
The template class describes an object that can serve as a locale
facet of type numpunct<E>. Its behavior is determined by the named
locale s. The constructor initializes its base object with
numpunct<E>(refs).
time_base
class time_base {
public:
enum dateorder {no_order, dmy, mdy, ymd, ydm};
};
The class serves as a base class for facets of template class
time_get. It defines just the enumerated type dateorder and several
file:///D|/97/c++_1/LIBREF.TXT (206 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 206 of 619
constants of this type. Each of the constants characterizes a
different way to order the components of a date. The constants are:
lno_order specifies no particular order.
ldmy specifies the order day, month, then year, as in 2 December
1979.
lmdy specifies the order month, day, then year, as in December
2, 1979.
lymd specifies the order year, month, then day, as in 1979/12/2.
lydm specifies the order year, day, then month, as in 1979: 2
Dec.
time_get
template<class E, class InIt = istreambuf_iterator<E> >
class time_get : public locale::facet {
public:
typedef E char_type;
typedef InIt iter_type;
explicit time_get(size_t refs = 0);
dateorder date_order() const;
iter_type get_time(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
iter_type get_date(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
iter_type get_weekday(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
iter_type get_month(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
iter_type get_year(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
static locale::id id;
protected:
~time_get();
virtual dateorder do_date_order() const;
virtual iter_type do_get_time(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
virtual iter_type do_get_date(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
virtual iter_type do_get_weekday(iter_type first, iter_type last
ios_base& x, ios_base::iostate& st, tm *pt) const;
virtual iter_type do_get_month(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
virtual iter_type do_get_year(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
};
The template class describes an object that can serve as a locale
facet, to control conversions of sequences of type E to time
values.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
time_get::char_type
file:///D|/97/c++_1/LIBREF.TXT (207 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 207 of 619
typedef E char_type;
The type is a synonym for the template parameter E.
time_get::date_order
dateorder date_order() const;
The member function returns date_order().
time_get::do_date_order
virtual dateorder do_date_order() const;
The virtual protected member function returns a value of type
time_base::dateorder, which describes the order in which date
components are matched by do_get_date. In this implementation, the
value is time_base::mdy, corresponding to dates of the form
December 2, 1979.
time_get::do_get_date
virtual iter_type do_get_date(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The virtual protected member function endeavors to match sequential
elements beginning at first in the sequence [first, last) until it
has recognized a complete, nonempty date input field. If
successful, it converts this field to its equivalent value as the
components tm::tm_mon, tm::tm_day, and tm::tm_year, and stores the
results in pt->tm_mon, pt->tm_day, and pt->tm_year, respectively.
It returns an iterator designating the first element beyond the
date input field. Otherwise, the function sets ios_base::failbit in
st. It returns an iterator designating the first element beyond any
prefix of a valid date input field. In either case, if the return
value equals last, the function sets ios_base::eofbit in st.
In this implementation, the date input field has the form MMM DD,
YYYY, where:
lMMM is matched by calling get_month, giving the month.
lDD is a sequence of decimal digits whose corresponding numeric
value must be in the range [1, 31], giving the day of the
month.
lYYYY is matched by calling get_year, giving the year.
lThe literal spaces and commas must match corresponding elements
in the input sequence.
time_get::do_get_month
virtual iter_type do_get_month(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The virtual protected member function endeavors to match sequential
elements beginning at first in the sequence [first, last) until it
has recognized a complete, nonempty month input field. If
file:///D|/97/c++_1/LIBREF.TXT (208 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 208 of 619
successful, it converts this field to its equivalent value as the
component tm::tm_mon, and stores the result in pt->tm_mon. It
returns an iterator designating the first element beyond the month
input field. Otherwise, the function sets ios_base::failbit in st.
It returns an iterator designating the first element beyond any
prefix of a valid month input field. In either case, if the return
value equals last, the function sets ios_base::eofbit in st.
The month input field is a sequence that matches the longest of a
set of locale-specific sequences, such as Jan, January, Feb,
February. The converted value is the number of months since
January.
time_get::do_get_time
virtual iter_type do_get_time(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The virtual protected member function endeavors to match sequential
elements beginning at first in the sequence [first, last) until it
has recognized a complete, nonempty time input field. If
successful, it converts this field to its equivalent value as the
components tm::tm_hour, tm::tm_min, and tm::tm_sec, and stores the
results in pt->tm_hour, pt->tm_min, and pt->tm_sec, respectively.
It returns an iterator designating the first element beyond the
time input field. Otherwise, the function sets ios_base::failbit in
st. It returns an iterator designating the first element beyond any
prefix of a valid time input field. In either case, if the return
value equals last, the function sets ios_base::eofbit in st.
In this implementation, the time input field has the form HH:MM:SS,
where:
lHH is a sequence of decimal digits whose corresponding numeric
value must be in the range [0, 24), giving the hour of the day.
lMM is a sequence of decimal digits whose corresponding numeric
value must be in the range [0, 60), giving the minutes past the
hour.
lSS is a sequence of decimal digits whose corresponding numeric
value must be in the range [0, 60), giving the seconds past the
minute.
lThe literal colons must match corresponding elements in the
input sequence.
time_get::do_get_weekday
virtual iter_type do_get_weekday(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The virtual protected member function endeavors to match sequential
elements beginning at first in the sequence [first, last) until it
has recognized a complete, nonempty weekday input field. If
successful, it converts this field to its equivalent value as the
component tm::tm_wday, and stores the result in pt->tm_wday. It
returns an iterator designating the first element beyond the
weekday input field. Otherwise, the function sets ios_base::failbit
in st. It returns an iterator designating the first element beyond
file:///D|/97/c++_1/LIBREF.TXT (209 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 209 of 619
any prefix of a valid weekday input field. In either case, if the
return value equals last, the function sets ios_base::eofbit in st.
The weekday input field is a sequence that matches the longest of a
set of locale-specific sequences, such as Sun, Sunday, Mon, Monday.
The converted value is the number of days since Sunday.
time_get::do_get_year
virtual iter_type do_get_year(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The virtual protected member function endeavors to match sequential
elements beginning at first in the sequence [first, last) until it
has recognized a complete, nonempty year input field. If
successful, it converts this field to its equivalent value as the
component tm::tm_year, and stores the result in pt->tm_year. It
returns an iterator designating the first element beyond the year
input field. Otherwise, the function sets ios_base::failbit in st.
It returns an iterator designating the first element beyond any
prefix of a valid year input field. In either case, if the return
value equals last, the function sets ios_base::eofbit in st.
The year input field is a sequence of decimal digits whose
corresponding numeric value must be in the range [1900, 2036). The
stored value is this value minus 1900. In this implementation, a
numeric value in the range [0, 136) is also permissible. It is
stored unchanged.
time_get::get_date
iter_type get_date(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The member function returns do_get_date(first, last, x, st, pt).
time_get::get_month
iter_type get_month(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The member function returns do_get_month(first, last, x, st, pt).
time_get::get_time
iter_type get_time(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The member function returns do_get_time(first, last, x, st, pt).
time_get::get_weekday
iter_type get_weekday(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The member function returns do_get_weekday(first, last, x, st, pt).
file:///D|/97/c++_1/LIBREF.TXT (210 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 210 of 619
time_get::get_year
iter_type get_year(iter_type first, iter_type last,
ios_base& x, ios_base::iostate& st, tm *pt) const;
The member function returns do_get_year(first, last, x, st, pt).
time_get::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter InIt.
time_get::time_get
explicit time_get(size_t refs = 0);
The constructor initializes its base object with locale::facet
(refs).
time_get_byname
template<class E, class InIt>
class time_get_byname : public time_get<E, InIt> {
public:
explicit time_get_byname(const char *s, size_t refs = 0);
protected:
~time_get_byname();
};
The template class describes an object that can serve as a locale
facet of type time_get<E, InIt>. Its behavior is determined by the
named locale s. The constructor initializes its base object with
time_get<E, InIt>(refs).
time_put
template<class E, class OutIt = ostreambuf_iterator<E> >
class time_put : public locale::facet {
public:
typedef E char_type;
typedef OutIt iter_type;
explicit time_put(size_t refs = 0);
iter_type put(iter_type next, ios_base& x,
tm *pt, char fmt, char mod = 0) const;
iter_type put(iter_type next, ios_base& x,
tm *pt, const E *first, const E *last) const;
static locale::id id;
protected:
~time_put();
virtual iter_type do_put(iter_type next, ios_base& x,
tm *pt, char fmt, char mod = 0) const;
};
The template class describes an object that can serve as a locale
facet, to control conversions of time values to sequences of type
file:///D|/97/c++_1/LIBREF.TXT (211 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 211 of 619
E.
As with any locale facet, the static object id has an initial
stored value of zero. The first attempt to access its stored value
stores a unique positive value in id.
time_put::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
time_put::do_put
virtual iter_type do_put(iter_type next, ios_base& x,
tm *pt, char fmt, char mod = 0) const;
The virtual protected member function generates sequential elements
beginning at next from time values stored in the object *pt, of
type tm. The function returns an iterator designating the next
place to insert an element beyond the generated output.
The output is generated by the same rules used by strftime, with a
last argument of pt, for generating a series of char elements into
array. (Each such char element is assumed to map to an
element of type E by a simple one-to-one mapping.) If mod equals
zero, the effective format is "%F", where F equals fmt. Otherwise,
the effective format is "%MF", where M equals mod.
time_put::put
iter_type put(iter_type next, ios_base& x,
tm *pt, char fmt, char mod = 0) const;
iter_type put(iter_type next, ios_base& x,
tm *pt, const E *first, const E *last) const;
The first member function returns do_put(next, x, pt, fmt, mod).
The second member function copies to *next++ any element in the
interval [first, last) other than a percent (%). For a percent
followed by a character C in the interval [first, last), the
function instead evaluates next = do_put(next, x, pt, C, 0) and
skips past C. If, however, C is a qualifier character from the set
EOQ#, followed by a character C2 in the interval [first, last), the
function instead evaluates next = do_put(next, x, pt, C2, C) and
skips past C2.
time_put::iter_type
typedef InIt iter_type;
The type is a synonym for the template parameter OutIt.
time_put::time_put
explicit time_put(size_t refs = 0);
The constructor initializes its base object with locale::facet
file:///D|/97/c++_1/LIBREF.TXT (212 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 212 of 619
(refs).
time_put_byname
template<class E, class OutIt>
class time_put_byname : public time_put<E, OutIt> {
public:
explicit time_put_byname(const char *s, size_t refs = 0);
protected:
~time_put_byname();
};
The template class describes an object that can serve as a locale
facet of type time_put<E, OutIt>. Its behavior is determined by the
named locale s. The constructor initializes its base object with
time_put<E, OutIt>(refs).
tolower
template<class E>
E tolower(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). tolower
(c).
toupper
template<class E>
E toupper(E c, const locale& loc) const;
The template function returns use_facet< ctype<E> >(loc). toupper
(c).
use_facet
template<class Facet>
const Facet& use_facet(const locale& loc,
const Facet *fac, bool make_it);
The template function returns a reference to the locale facet of
class Facet listed within the locale object loc. If no such object
is listed, the function throws an object of class bad_cast.
In this implementation, make_it instructs the function to generate
the locale facet on demand. But you should write _USE(loc, Facet),
or _USEFAC(loc, Facet) in place of use_facet(loc, (Facet *)0,
make_it), because the second and third parameters are a nonstandard
extension. The former is strongly preferred when looking up a facet
that should always be present -- it generates the requested facet
on demand, if necessary. The latter will report that the locale
initially constructed by locale() has no facets.
<map>
namespace std {
template<class Key, class T, class Pred, class A>
class map;
file:///D|/97/c++_1/LIBREF.TXT (213 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 213 of 619
template<class Key, class T, class Pred, class A>
class multimap;
// TEMPLATE FUNCTIONS
template<class Key, class T, class Pred, class A>
bool operator==(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator==(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator!=(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator!=(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<=(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<=(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>=(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>=(
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
void swap(
const map<Key, T, Pred, A>& lhs,
const map<Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
void swap(
file:///D|/97/c++_1/LIBREF.TXT (214 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 214 of 619
const multimap<Key, T, Pred, A>& lhs,
const multimap<Key, T, Pred, A>& rhs);
};
Include the STL standard header <map> to define the container
template classes map and multimap, and their supporting templates.
map
allocator_type . begin . clear . const_iterator . const_reference .
const_reverse_iterator . count .
difference_type . empty . end .
equal_range . erase . find . get_allocator . insert . iterator .
key_comp . key_compare . key_type . lower_bound . map . max_size .
operator[] . rbegin .
reference . referent_type . rend .
reverse_iterator . size .
size_type . swap . upper_bound .
value_comp . value_compare . value_type
template<class Key, class T, class Pred = less<Key>, class A = alloc
class map {
public:
typedef Key key_type;
typedef T referent_type;
typedef Pred key_compare;
typedef A allocator_type;
typedef pair<const Key, T> value_type;
class value_compare;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::rebind<value_type>::other::reference reference;
typedef A::rebind<value_type>::other::const_reference const_refe
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
explicit map(const Pred& comp = Pred(), const A& al = A());
map(const map& x);
map(const value_type *first, const value_type *last,
const Pred& comp = Pred(),
const A& al = A());
iterator begin();
const_iterator begin() const;
iterator end();
iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
A::reference operator[](const Key& key);
file:///D|/97/c++_1/LIBREF.TXT (215 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
pair<iterator, bool> insert(const value_type& x);
file:///D|/97/c++_1/LIBREF.TXT (216 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 215 of 619
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
void clear();
void swap(map x);
key_compare key_comp() const;
value_compare value_comp() const;
iterator find(const Key& key);
const_iterator find(const Key& key) const;
size_type count(const Key& key) const;
iterator lower_bound(const Key& key);
const_iterator lower_bound(const Key& key) const;
iterator upper_bound(const Key& key);
const_iterator upper_bound(const Key& key) const;
pair<iterator, iterator> equal_range(const Key& key);
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type pair<const Key, T>. The first
element of each pair is the sort key and the second is its
associated value. The sequence is represented in a way that permits
lookup, insertion, and removal of an arbitrary element with a
number of operations proportional to the logarithm of the number of
elements in the sequence (logarithmic time). Moreover, inserting an
element invalidates no iterators, and removing an element
invalidates only those iterators that point at the removed element.
The object orders the sequence it controls by calling a stored
function object of type Pred. You access this stored object by
calling the member function key_comp(). Such a function object must
impose a total order on sort keys. For any element x that precedes
y in the sequence, key_comp()(y.first, x.first) is false. (For the
default function object less<Key>, sort keys never decrease in
value.) Unlike template class multimap, an object of template class
map ensures that key_comp()(x.first, y.first) is true. (Each key is
unique.)
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
map::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
map::begin
file:///D|/97/c++_1/LIBREF.TXT (217 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 216 of 619
const_iterator begin() const;
iterator begin();
The member function returns a bidirectional iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
map::clear
void clear() const;
The member function calls erase( begin(), end()).
See the related sample program.
map::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant
bidirectional iterator for the controlled sequence. It is described
here as a synonym for the unspecified type T1.
map::const_reference
typedef A::rebind<value_type>::other::const_reference const_referenc
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
map::const_reverse_iterator
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
The type describes an object that can serve as a constant reverse
bidirectional iterator for the controlled sequence.
map::count
size_type count(const Key& key) const;
The member function returns the number of elements x in the range
[lower_bound(key), upper_bound(key)).
map::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
map::empty
file:///D|/97/c++_1/LIBREF.TXT (218 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 217 of 619
bool empty() const;
The member function returns true for an empty controlled sequence.
map::end
const_iterator end() const;
iterator end();
The member function returns a bidirectional iterator that points
just beyond the end of the sequence.
See the related sample program.
map::equal_range
pair<iterator, iterator> equal_range(const Key& key);
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
The member function returns a pair of iterators x such that x.first
== lower_bound(key) and x.second == upper_bound(key).
map::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements in the interval [first, last). Both return an iterator
that designates the first element remaining beyond any elements
removed, or end() if no such element exists.
The third member function removes the elements with sort keys in
the range [lower_bound(key), upper_bound(key)). It returns the
number of elements it removes.
See the related sample program.
map::find
iterator find(const Key& key);
const_iterator find(const Key& key) const;
The member function returns an iterator that designates the
earliest element in the controlled sequence whose sort key equals
key. If no such element exists, the iterator equals end().
See the related sample program.
map::get_allocator
A get_allocator() const;
file:///D|/97/c++_1/LIBREF.TXT (219 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 218 of 619
The member function returns allocator.
map::insert
pair<iterator, bool> insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
The first member function determines whether an element y exists in
the sequence whose key matches that of x. (The keys match if !
key_comp()(x. first, y.first) && !key_comp()(y.first, x.first).) If
not, it creates such an element y and initializes it with x. The
function then determines the iterator it that designates y. If an
insertion occurred, the function returns pair(it, true). Otherwise,
it returns pair(it, false).
The second member function returns insert(x), using it as a
starting place within the controlled sequence to search for the
insertion point. (Insertion can occur in amortized constant time,
instead of logarithmic time, if the insertion point immediately
follows it.) The third member function inserts the sequence of
element values in the range [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(InIt first, InIt last);
is replaced by:
void insert(const value_type *first, const value_type *last);
See the related sample program.
map::iterator
typedef T0 iterator;
The type describes an object that can serve as a bidirectional
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
map::key_comp
key_compare key_comp() const;
The member function returns the stored function object that
determines the order of elements in the controlled sequence. The
stored object determines the member function:
bool operator(const Key& x, const Key& y);
which returns true if x strictly precedes y in the sort order.
map::key_compare
file:///D|/97/c++_1/LIBREF.TXT (220 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 219 of 619
typedef Pred key_compare;
The type describes a function object that can compare two sort keys
to determine the relative order of any two elements in the
controlled sequence.
map::key_type
typedef Key key_type;
The type describes the sort key object stored in each element of
the controlled sequence.
map::lower_bound
iterator lower_bound(const Key& key);
const_iterator lower_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(x. first, key) is false.
If no such element exists, the function returns end().
map::map
explicit map(const Pred& comp = Pred(), const A& al = A());
map(const map& x);
map(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
The constructors with an argument named comp store the function
object so that it can be later returned by calling key_comp(). All
constructors also store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
copy of the sequence controlled by x. The last constructor
specifies the sequence of element values [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
map(InIt first, InIt last,
const Pred& comp = Pred(), const A& al = A());
is replaced by:
map(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
map::max_size
size_type max_size() const;
file:///D|/97/c++_1/LIBREF.TXT (221 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 220 of 619
The member function returns the length of the longest sequence that
the object can control.
See the related sample program.
map::operator[]
A::reference operator[](const Key& key);
The member function determines the iterator it as the return value
of insert( value_type(key, T()). (It inserts an element with the
specified key if no such element exists.) It then returns a
reference to (*it). second.
map::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. Hence, it
designates the beginning of the reverse sequence.
map::reference
typedef A::rebind<value_type>::other::reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
map::referent_type
typedef T referent_type;
The type is a synonym for the template parameter T.
map::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse bidirectional iterator that
points at the first element of the sequence (or just beyond the end
of an empty sequence). Hence, it designates the end of the reverse
sequence.
map::reverse_iterator
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
The type describes an object that can serve as a reverse
bidirectional iterator for the controlled sequence.
map::size
file:///D|/97/c++_1/LIBREF.TXT (222 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 221 of 619
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
map::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
map::swap
void swap(map& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
map::upper_bound
iterator upper_bound(const Key& key);
const_iterator upper_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(key, x.first) is true.
If no such element exists, the function returns end().
map::value_comp
value_compare value_comp() const;
The member function returns a function object that determines the
order of elements in the controlled sequence.
map::value_compare
class value_compare
: public binary_function<value_type, value_type, bool> {
public:
bool operator()(const value_type& x, const value_type& y)
{return (comp(x.first, x.second)); }
protected:
value_compare(key_compare pr)
: comp(pr) {}
key_compare comp;
};
The type describes a function object that can compare the sort keys
in two elements to determine their relative order in the controlled
file:///D|/97/c++_1/LIBREF.TXT (223 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 222 of 619
sequence. The function object stores an object comp of type
key_type. The member function operator() uses this object to
compare the sort-key components of two elements.
map::value_type
typedef pair<const Key, T> value_type;
The type describes an element of the controlled sequence.
multimap
allocator_type . begin . clear . const_iterator . const_reference .
const_reverse_iterator . count .
difference_type . empty . end .
equal_range . erase . find . get_allocator . insert . iterator .
key_comp . key_compare .
key_type . lower_bound . max_size .
multimap . rbegin .
reference . referent_type . rend .
reverse_iterator . size .
size_type . swap . upper_bound .
value_comp . value_compare . value_type
template<class Key, class T, class Pred = less<Key>, class A = alloc
class multimap {
public:
typedef Key key_type;
typedef T referent_type;
typedef Pred key_compare;
typedef A allocator_type;
typedef pair<const Key, T> value_type;
class value_compare;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::rebind<value_type>::other::reference reference;
typedef A::rebind<value_type>::other::const_reference const_refe
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
explicit multimap(const Pred& comp = Pred(), const A& al = A());
multimap(const multimap& x);
multimap(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
iterator begin();
const_iterator begin() const;
iterator end();
iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
size_type size() const;
size_type max_size() const;
bool empty() const;
file:///D|/97/c++_1/LIBREF.TXT (224 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
A get_allocator() const;
file:///D|/97/c++_1/LIBREF.TXT (225 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 223 of 619
iterator insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
void clear();
void swap(multimap x);
key_compare key_comp() const;
value_compare value_comp() const;
iterator find(const Key& key);
const_iterator find(const Key& key) const;
size_type count(const Key& key) const;
iterator lower_bound(const Key& key);
const_iterator lower_bound(const Key& key) const;
iterator upper_bound(const Key& key);
const_iterator upper_bound(const Key& key) const;
pair<iterator, iterator> equal_range(const Key& key);
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type pair<const Key, T>. The first
element of each pair is the sort key and the second is its
associated value. The sequence is represented in a way that permits
lookup, insertion, and removal of an arbitrary element with a
number of operations proportional to the logarithm of the number of
elements in the sequence (logarithmic time). Moreover, inserting an
element invalidates no iterators, and removing an element
invalidates only those iterators that point at the removed element.
The object orders the sequence it controls by calling a stored
function object of type Pred. You access this stored object by
calling the member function key_comp(). Such a function object must
impose a total order on sort keys. For any element x that precedes
y in the sequence, key_comp()(y.first, x.first) is false. (For the
default function object less<Key>, sort keys never decrease in
value.) Unlike template class map, an object of template class
multimap does not ensure that key_comp()(x.first, y.first) is true.
(Keys need not be unique.)
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
multimap::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
multimap::begin
file:///D|/97/c++_1/LIBREF.TXT (226 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 224 of 619
const_iterator begin() const;
iterator begin();
The member function returns a bidirectional iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
multimap::clear
void clear() const;
The member function calls erase( begin(), end()).
multimap::const_reference
typedef A::rebind<value_type>::other::const_reference const_referenc
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
multimap::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant
bidirectional iterator for the controlled sequence. It is described
here as a synonym for the unspecified type T1.
multimap::count
size_type count(const Key& key) const;
The member function returns the number of elements x in the range
[lower_bound(key), upper_bound(key)).
multimap::const_reverse_iterator
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
The type describes an object that can serve as a constant reverse
bidirectional iterator for the controlled sequence.
multimap::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
multimap::empty
bool empty() const;
file:///D|/97/c++_1/LIBREF.TXT (227 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 225 of 619
The member function returns true for an empty controlled sequence.
multimap::end
const_iterator end() const;
iterator end();
The member function returns a bidirectional iterator that points
just beyond the end of the sequence.
multimap::equal_range
pair<iterator, iterator> equal_range(const Key& key);
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
The member function returns a pair of iterators x such that x.first
== lower_bound(key) and x.second == upper_bound(key).
multimap::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements in the range [first, last). Both return an iterator that
designates the first element remaining beyond any elements removed,
or end() if no such element exists.
The third member removes the elements with sort keys in the range
[lower_bound(key), upper_bound(key)). It returns the number of
elements it removes.
multimap::find
iterator find(const Key& key);
const_iterator find(const Key& key) const;
The member function returns an iterator that designates the
earliest element in the controlled sequence whose sort key equals
key. If no such element exists, the iterator equals end().
multimap::get_allocator
A get_allocator() const;
The member function returns allocator.
multimap::insert
iterator insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
file:///D|/97/c++_1/LIBREF.TXT (228 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 226 of 619
The first member function inserts the element x in the controlled
sequence, then returns the iterator that designates the inserted
element. The second member function returns insert(x), using it as
a starting place within the controlled sequence to search for the
insertion point. (Insertion can occur in amortized constant time,
instead of logarithmic time, if the insertion point immediately
follows it.) The third member function inserts the sequence of
element values in the range [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(InIt first, InIt last);
is replaced by:
void insert(const value_type *first, const value_type *last);
multimap::iterator
typedef T0 iterator;
The type describes an object that can serve as a bidirectional
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
multimap::key_comp
key_compare key_comp() const;
The member function returns the stored function object that
determines the order of elements in the controlled sequence. The
stored object defines the member function:
bool operator(const Key& x, const Key& y);
which returns true if x strictly precedes y in the sort order.
multimap::key_compare
typedef Pred key_compare;
The type describes a function object that can compare two sort keys
to determine the relative order of any two elements in the
controlled sequence.
multimap::key_type
typedef Key key_type;
The type describes the sort key object stored in each element of
the controlled sequence.
multimap::lower_bound
file:///D|/97/c++_1/LIBREF.TXT (229 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 227 of 619
iterator lower_bound(const Key& key);
const_iterator lower_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(x. first, key) is false.
If no such element exists, the function returns end().
multimap::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
multimap::multimap
explicit multimap(const Pred& comp = Pred(), const A& al = A());
multimap(const multimap& x);
multimap(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
The constructors with an argument named comp store the function
object so that it can be later returned by calling key_comp(). All
constructors also store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
copy of the sequence controlled by x. The member template
constructor specifies the sequence of element values [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
multimap(InIt first, InIt last,
const Pred& comp = Pred(), const A& al = A());
is replaced by:
multimap(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
multimap::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. Hence, it
designates the beginning of the reverse sequence.
multimap::reference
typedef A::rebind<value_type>::other::reference reference;
file:///D|/97/c++_1/LIBREF.TXT (230 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 228 of 619
The type describes an object that can serve as a reference to an
element of the controlled sequence.
multimap::referent_type
typedef T referent_type;
The type is a synonym for the template parameter T.
multimap::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse bidirectional iterator that
points at the first element of the sequence (or just beyond the end
of an empty sequence). Hence, it designates the end of the reverse
sequence.
multimap::reverse_iterator
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
The type describes an object that can serve as a reverse
bidirectional iterator for the controlled sequence.
multimap::size
size_type size() const;
The member function returns the length of the controlled sequence.
multimap::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
multimap::swap
void swap(multimap& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
multimap::upper_bound
iterator upper_bound(const Key& key);
const_iterator upper_bound(const Key& key) const;
file:///D|/97/c++_1/LIBREF.TXT (231 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 229 of 619
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(key, x.first) is true.
If no such element exists, the function returns end().
multimap::value_comp
value_compare value_comp() const;
The member function returns a function object that determines the
order of elements in the controlled sequence.
multimap::value_compare
class value_compare
: public binary_function<value_type, value_type, bool> {
public:
bool operator()(const value_type& x, const value_type& y)
{return (comp(x.first, x.second)); }
protected:
value_compare(key_compare pr)
: comp(pr) {}
key_compare comp;
};
The type describes a function object that can compare the sort keys
in two elements to determine their relative order in the controlled
sequence. The function object stores an object comp of type
key_type. The member function operator() uses this object to
compare the sort-key components of two elements.
multimap::value_type
typedef pair<const Key, T> value_type;
The type describes an element of the controlled sequence.
operator!=
template<class Key, class T, class Pred, class A>
bool operator!=(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator!=(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class Key, class T, class Pred, class A>
bool operator==(
const map <Key, T, Pred, A>& lhs,
file:///D|/97/c++_1/LIBREF.TXT (232 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 230 of 619
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator==(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The first template function overloads operator== to compare two
objects of template class map. The second template function
overloads operator== to compare two objects of template class
multimap. Both functions return lhs.size() == rhs.size() && equal
(lhs. begin(), lhs. end(), rhs.begin()).
operator<
template<class Key, class T, class Pred, class A>
bool operator<(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The first template function overloads operator< to compare two
objects of template class map. The second template function
overloads operator< to compare two objects of template class
multimap. Both functions return lexicographical_compare(lhs. begin
(), lhs. end(), rhs.begin(), rhs.end()).
operator<=
template<class Key, class T, class Pred, class A>
bool operator<=(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator<=(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class Key, class T, class Pred, class A>
bool operator>(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The template function returns rhs < lhs.
operator>=
file:///D|/97/c++_1/LIBREF.TXT (233 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 231 of 619
template<class Key, class T, class Pred, class A>
bool operator>=(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
bool operator>=(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The template function returns !(lhs < rhs).
swap
template<class Key, class T, class Pred, class A>
void swap(
const map <Key, T, Pred, A>& lhs,
const map <Key, T, Pred, A>& rhs);
template<class Key, class T, class Pred, class A>
void swap(
const multimap <Key, T, Pred, A>& lhs,
const multimap <Key, T, Pred, A>& rhs);
The template function executes lhs.swap(rhs).
<memory>
namespace std {
// TEMPLATE CLASSES
template<class T>
class allocator;
class allocator<void>;
template<class FwdIt, class T>
class raw_storage_iterator;
template<class T>
class auto_ptr;
// TEMPLATE OPERATORS
template<class T>
bool operator==(allocator<T>& lhs,
allocator<T>& rhs);
template<class T>
bool operator!=(allocator<T>& lhs,
allocator<T>& rhs);
template<class T>
void operator delete(void *p, size_t n, allocator& al);
template<class T>
void *operator new(size_t n, allocator& al);
// TEMPLATE FUNCTIONS
template<class T>
pair<T *, ptrdiff_t> get_temporary_buffer(ptrdiff_t n, T *);
template<class T>
void return_temporary_buffer(T *p);
template<class InIt, class FwdIt>
FwdIt uninitialized_copy(InIt first, InIt last, FwdIt result);
template<class FwdIt, class T>
void uninitialized_fill(FwdIt first, FwdIt last, const T& x);
template<class FwdIt, class Size, class T>
file:///D|/97/c++_1/LIBREF.TXT (234 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 232 of 619
void uninitialized_fill_n(FwdIt first, Size n, const T& x);
};
Include the STL standard header <memory> to define a class, an
operator, and several templates that help allocate and free
objects.
allocator
template<class T>
class allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T *pointer;
typedef const T *const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
pointer address(reference x) const;
const_pointer address(const_reference x) const;
allocator();
allocator<T>& operator=(const allocator<T>);
pointer allocate(size_type n, const void *hint);
void deallocate(pointer p, size_type n);
void construct(pointer p, const T& val);
void destroy(pointer p);
size_type max_size() const;
};
The template class describes an object that manages storage
allocation and freeing for arrays of objects of type T. An object
of class allocator is the default allocator object specified in the
constructors for several container template classes in the Standard
C++ library.
Template class allocator supplies several type definitions that are
rather pedestrian. They hardly seem worth defining. But another
class with the same members might choose more interesting
alternatives. Constructing a container with an allocator object of
such a class gives individual control over allocation and freeing
of elements controlled by that container.
For example, an allocator object might allocate storage on a
private heap. Or it might allocate storage on a far heap, requiring
nonstandard pointers to access the allocated objects. Or it might
specify, through the type definitions it supplies, that elements be
accessed through special accessor objects that manage shared
memory, or perform automatic garbage collection. Hence, a class
that allocates storage using an allocator object should always use
these types for declaring pointer and reference objects (as do the
containers in the Standard C++ library).
Thus, an allocator defines the types (among others):
lpointer -- behaves like a pointer to T
lconst_pointer -- behaves like a const pointer to T
lreference -- behaves like a reference to T
file:///D|/97/c++_1/LIBREF.TXT (235 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 233 of 619
lconst_reference -- behaves like a const reference to T
These types specify the form that pointers and references must take
for allocated elements. (allocator::types<T>::pointer is not
necessarily the same as T * for all allocator objects, even though
it has this obvious definition for class allocator.)
In this implementation, if a translator does not support member
template functions, it omits the type-mapping member template
class:
template<class U>
struct rebind {
typedef allocator<U> other;
};
Thus, how you write an allocator is constrained. A container may
need to allocate and free objects other than type T, but cannot use
the rebind mechanism to derive a suitable allocator object. This
means you cannot write an allocator that uses any pointer or
reference types that differ from those used by allocator, and you
must supply the member function:
char *_Charalloc(size_type n);
which allocates an object of size n bytes and returns a pointer to
its first byte.
allocator::address
pointer address(reference x) const;
const_pointer address(const_reference x) const;
The member functions return the address of x, in the form that
pointers must take for allocated elements.
allocator::allocate
pointer allocate(size_type n, const void *hint);
The member function allocates storage for an array of n elements of
type T, by calling operator new(n). It returns a pointer to the
allocated object. The hint argument helps some allocators in
improving locality of reference -- a valid choice is the address of
an object earlier allocated by the same allocator object, and not
yet deallocated. To supply no hint, use a null pointer argument
instead.
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
pointer allocate(size_type n, const U *hint);
is replaced by:
pointer allocate(size_type n, const void *hint);
file:///D|/97/c++_1/LIBREF.TXT (236 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 234 of 619
allocator::allocator
allocator();
allocator(const allocator<T>);
The constructor does nothing. In general, however, an allocator
object constructed from another allocator object should compare
equal to it (and hence permit intermixing of object allocation and
freeing between the two allocator objects).
In this implementation, if a translator does not support member
template functions, the template constructor:
template<class U>
allocator(const allocator<U>);
is replaced by:
allocator(const allocator<T>);
which is the copy constructor.
allocator::const_pointer
typedef const T *pointer;
The pointer type describes an object p that can designate, via the
expression *p, any const object that an object of template class
allocator can allocate.
allocator::const_reference
typedef const T& const_reference;
The reference type describes an object x that can designate any
const object that an object of template class allocator can
allocate.
allocator::construct
void construct(pointer p, const T& val);
The member function constructs an object of type T at p by
evaluating the placement new expression new ((void *)p) T(val).
allocator::deallocate
void deallocate(pointer p, size_type n);
The member function frees storage for the array of n objects of
type T beginning at p, by calling operator delete(p). The pointer p
must have been earlier returned by a call to allocate for an
allocator object that compares equal to *this, allocating an array
object of the same size and type.
allocator::destroy
file:///D|/97/c++_1/LIBREF.TXT (237 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 235 of 619
void destroy(pointer p);
The member function destroys the object designated by p, by calling
p->T::~T().
allocator::difference_type
typedef ptrdiff_t difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in a sequence
that an object of template class allocator can allocate.
allocator::max_size
size_type max_size() const;
The member function returns the length of the longest sequence of
elements of type T that an object of class allocator might be able
to allocate.
allocator::operator=
allocator<T>& operator=(const allocator<T>);
The template assignment operator does nothing. In general, however,
an allocator object assigned to another allocator object should
compare equal to it (and hence permit intermixing of object
allocation and freeing between the two allocator objects).
In this implementation, if a translator does not support member
template functions, the template assignment operator:
template<class U>
allocator<T>& operator=(const allocator<U>);
is replaced by:
allocator<T>& operator=(const allocator<T>);
which is the default assignment operator.
allocator::pointer
typedef T *pointer;
The pointer type describes an object p that can designate, via the
expression *p, any object that an object of template class
allocator can allocate.
allocator::reference
typedef T& reference;
The reference type describes an object x that can designate any
object that an object of template class allocator can allocate.
file:///D|/97/c++_1/LIBREF.TXT (238 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 236 of 619
allocator::size_type
typedef size_t size_type;
The unsigned integer type describes an object that can represent
the length of any sequence that an object of template class
allocator can allocate.
allocator::value_type
typedef T value_type;
The type is a synonym for the template parameter T.
allocator<void>
class allocator<void> {
typedef void *pointer;
typedef const void *const_pointer;
typedef void value_type;
allocator();
template<class U>
allocator(const allocator<U>);
template<class U>
operator=(const allocator<U>);
};
The class explicitly specializes template class allocator for type
void. It defines only the types const_pointer, pointer,
value_type.
auto_ptr
template<class T>
class auto_ptr {
public:
typedef T element_type;
explicit auto_ptr(T *p = 0) throw();
auto_ptr(const auto_ptr<T>& rhs) throw();
auto_ptr<T>& operator=(auto_ptr<T>& rhs) throw();
~auto_ptr();
T& operator*() const throw();
T *operator->() const throw();
T *get() const throw();
T *release() const throw();
};
The class describes an object that stores a pointer to an allocated
object of type T. The stored pointer must either be null or
designate an object allocated by a new expression. The object also
stores an ownership indicator. An object constructed with a non-
null pointer owns the pointer. It transfers ownership if its stored
value is assigned to another object. The destructor for auto_ptr<T>
deletes the allocated object if it owns it. Hence, an object of
class auto_ptr<T> ensures that an allocated object is automatically
deleted when control leaves a block, even via a thrown exception.
file:///D|/97/c++_1/LIBREF.TXT (239 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 237 of 619
auto_ptr::auto_ptr
explicit auto_ptr(T *p = 0) throw();
auto_ptr(const auto_ptr(auto_ptr<T>& rhs) throw();
The first constructor stores p as the pointer to the allocated
object. It stores true as the ownership indicator only if p != 0.
The second constructor transfers ownership of the pointer stored in
rhs, by storing both the pointer value and the ownership indicator
from rhs in the constructed object. It effectively releases the
pointer by calling rhs.release().
In this implementation, if a translator does not support member
template functions, the template:
template<class U>
auto_ptr(const auto_ptr(auto_ptr<U>& rhs) throw();
is replaced by:
auto_ptr(const auto_ptr(auto_ptr<T>& rhs);
auto_ptr::~auto_ptr
~auto_ptr();
If the ownership indicator is true, the destructor deletes the
object designated by the stored pointer p by evaluating the delete
expression delete p.
auto_ptr::element_type
typedef T element_type;
The type is a synonym for the template parameter T.
auto_ptr::get
T *get() const throw();
The member function returns the stored pointer.
auto_ptr::operator=
auto_ptr<T>& operator=(auto_ptr<>& rhs) throw();
The assignment operator deletes any pointer p that it owns, by
evaluating the delete expression delete p. It then transfers
ownership of the pointer stored in rhs, by storing both the pointer
value and the ownership indicator from rhs in *this. It effectively
releases the pointer by calling rhs.release(). The function returns
*this.
In this implementation, if a translator does not support member
template functions, the template:
file:///D|/97/c++_1/LIBREF.TXT (240 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 238 of 619
template<class U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs) throw();
is replaced by:
auto_ptr<T>& operator=(auto_ptr<T>& rhs);
auto_ptr::operator*
T& operator*() const throw();
The indirection operator effectively returns *get(). Hence, the
stored pointer must not be null.
auto_ptr::operator->
T *operator->() const throw();
The selection operator effectively returns get(), so that the
expression al->m behaves the same as (al.get())->m, where al is an
object of class auto_ptr<T>. Hence, the stored pointer must not be
null, and T must be a class, structure, or union type.
auto_ptr::release
T *release() throw();
The member function sets the ownership indicator to false, then
returns the stored pointer.
get_temporary_buffer
template<class T>
pair<T *, ptrdiff_t> get_temporary_buffer(ptrdiff_t n, T *);
The template function allocates storage for a sequence of at most n
elements of type T, from an unspecified source (which may well be
the standard heap used by operator new). It returns a value pr, of
type pair<T *, ptrdiff_t>. If the function allocates storage,
pr.first designates the allocated storage and pr.second is the
number of elements in the longest sequence the storage can hold.
Otherwise, pr.first is a null pointer.
In this implementation, if a translator does not support member
template functions, the template:
template<class T>
pair<T *, ptrdiff_t> get_temporary_buffer(ptrdiff_t n);
is replaced by:
template<class T>
pair<T *, ptrdiff_t> get_temporary_buffer(ptrdiff_t n, T *);
operator!=
file:///D|/97/c++_1/LIBREF.TXT (241 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 239 of 619
template<class T>
bool operator!=(allocator<T>& lhs,
allocator<T>& rhs);
The template operator returns false.
operator==
template<class T>
bool operator==(allocator<T>& lhs,
allocator<T>& rhs);
The template operator returns true. (Two allocator objects should
compare equal only if an object allocated through one can be
deallocated through the other. If the value of one object is
determined from another by assignment or by construction, the two
objects should compare equal.)
operator delete
template<class T>
void operator delete(void *p, size_t n, allocator<T>& al);
The template operator function lets you write a placement delete
expression that deallocates storage under control of the allocator
object al, as in delete (n, al) p. The function effectively calls
al.deallocate(p, n).
operator new
template<class T>
void *operator new(size_t n, allocator<T>& al);
The template operator function lets you write a placement new
expression that allocates storage under control of the allocator
object al, as in new(al) U, to allocate and construct a new object
of type U. The function effectively returns
allocator<T>::rebind<char>::other(al).allocate(n, (void *)0).
raw_storage_iterator
template<class FwdIt, class T>
class raw_storage_iterator
: public iterator<output_iterator_tag, void, void> {
public:
typedef FwdIt iterator_type;
typedef T element_type;
explicit raw_storage_iterator(FwdIt it);
raw_storage_iterator<FwdIt, T>& operator*();
raw_storage_iterator<FwdIt, T>& operator=(const T& val);
raw_storage_iterator<FwdIt, T>& operator++();
raw_storage_iterator<FwdIt, T> operator++(int);
};
The class describes an output iterator that constructs objects of
type T in the sequence it generates. An object of class
file:///D|/97/c++_1/LIBREF.TXT (242 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 240 of 619
raw_storage_iterator<FwdIt, T> accesses storage through a forward
iterator object, of class FwdIt, that you specify when you
construct the object. For an object it of class FwdIt, the
expression &*it must designate unconstructed storage for the next
object (of type T) in the generated sequence.
raw_storage_iterator::element_type
typedef T element_type;
The type is a synonym for the template parameter T.
raw_storage_iterator::iterator_type
typedef FwdIt iterator_type;
The type is a synonym for the template parameter FwdIt.
raw_storage_iterator::operator*
raw_storage_iterator<FwdIt, T>& operator*();
The indirection operator returns *this (so that operator=(const T&)
can perform the actual store in an expression such as *x = val).
raw_storage_iterator::operator=
raw_storage_iterator<FwdIt, T>& operator=(const T& val);
The assignment operator constructs the next object in the output
sequence using the stored iterator value it, by evaluating the
placement new expression new ((void *)&*it) T(val). The function
returns *this.
raw_storage_iterator::operator++
raw_storage_iterator<FwdIt, T>& operator++();
raw_storage_iterator<FwdIt, T> operator++(int);
The first (preincrement) operator increments the stored output
iterator object, then returns *this.
The second (postincrement) operator makes a copy of *this,
increments the stored output iterator object, then returns the
copy.
raw_storage_iterator::raw_storage_iterator
explicit raw_storage_iterator(FwdIt it);
The constructor stores it as the output iterator object.
return_temporary_buffer
template<class T>
void return_temporary_buffer(T *p);
file:///D|/97/c++_1/LIBREF.TXT (243 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 241 of 619
The template function frees the storage designated by p, which must
be earlier allocated by a call to get_temporary_buffer.
uninitialized_copy
template<class InIt, class FwdIt>
FwdIt uninitialized_copy(InIt first, InIt last, FwdIt result);
The template function effectively executes:
while (first != last)
new ((void *)&*result++) T(*first++);
where T is the type of *first.
uninitialized_fill
template<class FwdIt, class T>
void uninitialized_fill(FwdIt first, FwdIt last, const T& x);
The template function effectively executes:
while (first != last)
new ((void *)&*first++) T(x);
uninitialized_fill_n
template<class FwdIt, class Size, class T>
void uninitialized_fill_n(FwdIt first, Size n, const T& x);
The template function effectively executes:
while (0 < n--)
new ((void *)&*first++) T(x);
<numeric>
namespace std {
template<class InIt, class T>
T accumulate(InIt first, InIt last, T val);
template<class InIt, class T, class Pred>
T accumulate(InIt first, InIt last, T val, Pred pr);
template<class InIt1, class InIt2, class T>
T product(InIt1 first1, InIt1 last1,
Init2 first2, T val);
template<class InIt1, class InIt2, class T,
class Pred1, class Pred2>
T product(InIt1 first1, InIt1 last1,
Init2 first2, T val, Pred1 pr1, Pred2 pr2);
template<class InIt, class OutIt>
OutIt partial_sum(InIt first, InIt last,
OutIt result);
template<class InIt, class OutIt, class Pred>
OutIt partial_sum(InIt first, InIt last,
OutIt result, Pred pr);
template<class InIt, class OutIt>
file:///D|/97/c++_1/LIBREF.TXT (244 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 242 of 619
OutIt adjacent_difference(InIt first, InIt last,
OutIt result);
template<class InIt, class OutIt, class Pred>
OutIt adjacent_difference(InIt first, InIt last,
OutIt result, Pred pr);
};
Include the STL standard header <numeric> to define several
template functions useful for computing numeric values. The
descriptions of these templates employ a number of conventions
common to all algorithms.
accumulate
template<class InIt, class T>
T accumulate(InIt first, InIt last, T val);
template<class InIt, class T, class Pred>
T accumulate(InIt first, InIt last, T val, Pred pr);
The first template function repeatedly replaces val with val + *I,
for each value of the InIt iterator I in the interval [first,
last). It then returns val.
The second template function repeatedly replaces val with pr(val,
*I), for each value of the InIt iterator I in the interval [first,
last). It then returns val.
See the related sample program.
adjacent_difference
template<class InIt, class OutIt>
OutIt adjacent_difference(InIt first, InIt last,
OutIt result);
template<class InIt, class OutIt, class Pred>
OutIt adjacent_difference(InIt first, InIt last,
OutIt result, Pred pr);
The first template function stores successive values beginning at
result, for each value of the InIt iterator I in the interval
[first, last). The first value val stored (if any) is *I. Each
subsequent value stored is *I - val, and val is replaced by *I. The
function returns result incremented last - first times.
The second template function stores successive values beginning at
result, for each value of the InIt iterator I in the interval
[first, last). The first value val stored (if any) is *I. Each
subsequent value stored is pr(*I, val), and val is replaced by *I.
The function returns result incremented last - first times.
See the related sample program.
inner_product
template<class InIt1, class InIt2, class T>
T product(InIt1 first1, InIt1 last1,
Init2 first2, T val);
file:///D|/97/c++_1/LIBREF.TXT (245 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 243 of 619
template<class InIt1, class InIt2, class T,
class Pred1, class Pred2>
T product(InIt1 first1, InIt1 last1,
Init2 first2, T val, Pred1 pr1, Pred2 pr2);
The first template function repeatedly replaces val with val + (*I1
* *I2), for each value of the InIt1 iterator I1 in the interval
[first1, last2). In each case, the InIt2 iterator I2 equals first2
+ (I1 - first1). The function returns val.
The second template function repeatedly replaces val with pr1(val,
pr2(*I1, *I2)), for each value of the InIt1 iterator I1 in the
interval [first1, last2). In each case, the InIt2 iterator I2
equals first2 + (I1 - first1). The function returns val.
See the related sample program.
partial_sum
template<class InIt, class OutIt>
OutIt partial_sum(InIt first, InIt last,
OutIt result);
template<class InIt, class OutIt, class Pred>
OutIt partial_sum(InIt first, InIt last,
OutIt result, Pred pr);
The first template function stores successive values beginning at
result, for each value of the InIt iterator I in the interval
[first, last). The first value val stored (if any) is *I. Each
subsequent value val stored is val + *I. The function returns
result incremented last - first times.
The second template function stores successive values beginning at
result, for each value of the InIt iterator I in the interval
[first, last). The first value val stored (if any) is *I. Each
subsequent value val stored is pr(val, *I). The function returns
result incremented last - first times.
See the related sample program.
<ostream>
namespace std {
template<class E, class T = char_traits<E> >
class basic_ostream;
typedef basic_ostream<char, char_traits<char> > ostream;
typedef basic_ostream<wchar_t, char_traits<wchar_t> > wostream;
// INSERTERS
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, cons
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, E c)
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (246 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 244 of 619
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os
// MANIPULATORS
template class<E, T>
basic_ostream<E, T>& endl(basic_ostream<E, T> os);
template class<E, T>
basic_ostream<E, T>& ends(basic_ostream<E, T> os);
template class<E, T>
basic_ostream<E, T>& flush(basic_ostream<E, T> os);
};
Include the iostreams standard header <ostream> to define template
class basic_ostream, which mediates extractions for the iostreams
classes. The header also defines several related manipulators.
(This header is typically included for you by another of the
iostreams headers. You seldom have occasion to include it
directly.)
basic_ostream
basic_ostream . flush . operator<< . opfx . osfx . put . seekp .
sentry . tellp . write
template <class E, class T = char_traits<E> >
class basic_ostream {
public:
class sentry;
explicit basic_ostream(basic_streambuf<E, T> *sb);
virtual ~ostream();
bool opfx();
void osfx();
basic_ostream& operator<<(basic_ostream& (*pf)(basic_ostream&));
basic_ostream& operator<<(basic_ios<E, T>& (*pf)(basic_ios<E, T>
basic_ostream& operator<<(ios_base<E, T>& (*pf)(ios_base<E, T>&)
basic_ostream& operator<<(basic_streambuf<E, T> *sb);
basic_ostream& operator<<(const char *s);
basic_ostream& operator<<(char c);
basic_ostream& operator<<(bool n);
basic_ostream& operator<<(short n);
basic_ostream& operator<<(unsigned short n);
basic_ostream& operator<<(int n);
basic_ostream& operator<<(unsigned int n);
basic_ostream& operator<<(long n);
basic_ostream& operator<<(unsigned long n);
basic_ostream& operator<<(float n);
basic_ostream& operator<<(double n);
basic_ostream& operator<<(long double n);
basic_ostream& operator<<(void * n);
basic_ostream& put(E c);
basic_ostream& write(E *s, streamsize n);
basic_ostream& flush();
pos_type tellp();
basic_ostream& seekp(pos_type pos);
basic_ostream& seekp(off_type off, ios_base::seek_dir way);
};
file:///D|/97/c++_1/LIBREF.TXT (247 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 245 of 619
The template class describes an object that controls insertion of
elements and encoded objects into a stream buffer with elements of
type E, whose character traits are determined by the class T.
Most of the member functions that overload operator<< are formatted
output functions. They follow the pattern:
iostate state = goodbit;
const sentry ok(*this);
if (ok)
{try
{convert and insert elements
accumulate flags in state}
catch (...)
{if (exceptions() & badbit)
throw;
setstate(badbit); }}
width(0); // except for operator<<(E)
setstate(state);
return (*this);
Two other member functions are unformatted output functions. They
follow the pattern:
iostate state = goodbit;
const sentry ok(*this);
if (!ok)
state |= badbit;
else
{try
{obtain and insert elements
accumulate flags in state}
catch (...)
{if (rdstate() & badbit)
throw;
setstate(badbit); }}
setstate(state);
return (*this);
Both groups of functions call setstate(badbit) if they encounter a
failure while inserting elements.
An object of class basic_ostream<E, T> stores only a virtual public
base object of class basic_ios<E, T>.
basic_ostream::basic_ostream
explicit basic_ostream(basic_streambuf<E, T> *sb);
The constructor initializes the base class by calling init(sb).
basic_ostream::flush
basic_ostream& flush();
If rdbuf() is not a null pointer, the function calls rdbuf()-
file:///D|/97/c++_1/LIBREF.TXT (248 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 246 of 619
>pubsync(). If that returns -1, the function calls setstate
(badbit). It returns *this.
basic_ostream::operator<<
basic_ostream& operator<<(
basic_ostream& (*pf)(basic_ostream&));
basic_ostream& operator<<(
basic_ios<E, T>& (*pf)(basic_ios<E, T>&));
basic_ostream& operator<<(
ios_base<E, T>& (*pf)(ios_base<E, T>&));
basic_ostream& operator<<(
basic_streambuf<E, T> *sb);
basic_ostream& operator<<(const char *s);
basic_ostream& operator<<(char c);
basic_ostream& operator<<(bool n);
basic_ostream& operator<<(short n);
basic_ostream& operator<<(unsigned short n);
basic_ostream& operator<<(int n);
basic_ostream& operator<<(unsigned int n);
basic_ostream& operator<<(long n);
basic_ostream& operator<<(unsigned long n);
basic_ostream& operator<<(float n);
basic_ostream& operator<<(double n);
basic_ostream& operator<<(long double n);
basic_ostream& operator<<(void *n);
The first member function ensures that an expression of the form
ostr <<: endl calls endl(ostr), then returns *this. The second and
third functions ensure that other manipulators, such as hex behave
similarly. The remaining functions are all formatted output
functions.
The function:
basic_ostream& operator<<(
basic_streambuf<E, T> *sb);
extracts elements from sb, if sb is not a null pointer, and inserts
them. Extraction stops on end-of-file, or if an extraction throws
an exception (which is rethrown). It also stops, without extracting
the element in question, if an insertion fails. If the function
inserts no elements, or if an extraction throws an exception, the
function calls setstate(failbit). In any case, the function returns
*this.
The function:
basic_ostream& operator<<(const char *s);
determines the length n = strlen(s) of the sequence beginning at s,
and inserts the widened sequence. Each element c of the sequence is
widened by calling use_facet< ctype<E> >( getloc()). widen(c). If n
< width(), then the function also inserts a repetition of width() -
n fill characters. The repetition precedes the sequence if (flags()
& adjustfield != left. Otherwise, the repetition follows the
sequence.
file:///D|/97/c++_1/LIBREF.TXT (249 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 247 of 619
The function:
basic_ostream& operator<<(char c);
inserts the widened element use_facet< ctype<E> >( getloc()). widen
(c). It returns *this.
The function:
basic_ostream& operator<<(bool n);
converts n to a Boolean field and inserts it by calling
use_facet<num_put<E, OutIt>(getloc()). put(OutIt( rdbuf()), *this,
getloc(), n). Here, OutIt is defined as ostreambuf_iterator<E, T>.
The function returns *this.
The functions:
basic_ostream& operator<<(short n);
basic_ostream& operator<<(unsigned short n);
basic_ostream& operator<<(int n);
basic_ostream& operator<<(unsigned int n);
basic_ostream& operator<<(long n);
basic_ostream& operator<<(unsigned long n);
basic_ostream& operator<<(void *n);
each convert n to a numeric field and insert it by calling
use_facet<num_put<E, OutIt>(getloc()). put(OutIt( rdbuf()), *this,
getloc(), n). Here, OutIt is defined as ostreambuf_iterator<E, T>.
The function returns *this.
The functions:
basic_ostream& operator<<(float n);
basic_ostream& operator<<(double n);
basic_ostream& operator<<(long double n);
each convert n to a numeric field and insert it by calling
use_facet<num_put<E, OutIt>(getloc()). put(OutIt( rdbuf()), *this,
getloc(), n). Here, OutIt is defined as ostreambuf_iterator<E, T>.
The function returns *this.
basic_ostream::opfx
bool opfx();
If good() is true, and tie() is not a null pointer, the member
function calls tie->flush(). It returns good().
You should not call opfx directly. It is called as needed by an
object of class sentry.
basic_ostream::osfx
void osfx();
file:///D|/97/c++_1/LIBREF.TXT (250 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 248 of 619
If flags() & unitbuf is nonzero, the member function calls flush().
You should not call osfx directly. It is called as needed by an
object of class sentry.
basic_ostream::put
basic_ostream& put(E c);
The unformatted output function inserts the element c. It returns
*this.
basic_ostream::seekp
basic_ostream& seekp(pos_type pos);
basic_ostream& seekp(off_type off, ios_base::seek_dir way);
If fail() is false, the first member function calls rdbuf()->
pubseekpos(pos). If fail() is false, the second function calls
rdbuf()-> pubseekoff(off, way). Both functions return *this.
basic_ostream::sentry
class sentry {
public:
explicit sentry(basic_ostream<E, T>& os);
operator bool() const;
};
The nested class describes an object whose declaration structures
the formatted output functions and the unformatted output
functions. The constructor effectively calls os.opfx() and stores
the return value. operator bool() delivers this return value. The
destructor effectively calls os.osfx(), but only if
uncaught_exception() returns false.
basic_ostream::tellp
pos_type tellp();
If fail() is false, the member function returns rdbuf()->
pubseekoff(0, cur, in). Otherwise, it returns streampos(-1).
basic_ostream::write
basic_ostream& write(const E *s, streamsize n);
The unformatted output function inserts the sequence of n elements
beginning at s.
endl
template class<E, T>
basic_ostream<E, T>& endl(basic_ostream<E, T> os);
The manipulator calls os.put(os. widen('\n')), then calls os.flush
(). It returns os.
file:///D|/97/c++_1/LIBREF.TXT (251 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 249 of 619
ends
template class<E, T>
basic_ostream<E, T>& ends(basic_ostream<E, T> os);
The manipulator calls os.put(E('\0')). It returns os.
flush
template class<E, T>
basic_ostream<E, T>& flush(basic_ostream<E, T> os);
The manipulator calls os.flush(). It returns os.
operator<<
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, const E
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, E c);
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, co
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, sig
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, co
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, uns
The template function:
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, const E
determines the length n = T::length(s) of the sequence beginning at
s, and inserts the sequence. If n < os.width(), then the function
also inserts a repetition of width() - n fill characters. The
repetition precedes the sequence if (os.flags() & adjustfield !=
left. Otherwise, the repetition follows the sequence. The function
returns os.
The template function:
template<class E, class T>
basic_ostream<E, T>& operator<<(basic_ostream<E, T> os, E c);
is a formatted output function that inserts the element c. It
returns os.
The template function:
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, co
returns os << (const char *)s.
file:///D|/97/c++_1/LIBREF.TXT (252 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 250 of 619
The template function:
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, si
returns os << (char)c.
The template function:
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, co
returns os << (const char *)s.
The template function:
template<class T>
basic_ostream<char, T>& operator<<(basic_ostream<char, T> os, un
returns os << (char)c.
ostream
typedef basic_ostream<char, char_traits<char> > ostream;
The type is a synonym for template class basic_ostream, specialized
for elements of type char with default character
wostream
typedef basic_ostream<wchar_t, char_traits<wchar_t> > wostream;
The type is a synonym for template class basic_ostream, specialized
for elements of type wchar_t with default character traits.
<queue>
namespace std {
template<class T, class Cont>
class queue;
template<class T, class Cont, class Pred>
class priority_queue;
// TEMPLATE FUNCTIONS
template<class T, class Cont>
bool operator==(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
template<class T, class Cont>
bool operator!=(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
template<class T, class Cont>
bool operator<(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
template<class T, class Cont>
bool operator>(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
template<class T, class Cont>
file:///D|/97/c++_1/LIBREF.TXT (253 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 251 of 619
bool operator<=(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
template<class T, class Cont>
bool operator>=(const queue<T, Cont>& lhs,
const queue<T, Cont>&);
};
Include the STL standard header <queue> to define the template
classes priority_queue and queue, and two supporting templates.
operator!=
template<class T, class Cont>
bool operator!=(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class T, class Cont>
bool operator==(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
The template function overloads operator== to compare two objects
of template class queue. The function returns lhs.c == rhs.c.
operator<
template<class T, class Cont>
bool operator<(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
The template function overloads operator< to compare two objects of
template class queue. The function returns lhs.c < rhs.c.
operator<=
template<class T, class Cont>
bool operator<=(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class Cont>
bool operator>(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class Cont>
bool operator>=(const queue <T, Cont>& lhs,
const queue <T, Cont>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (254 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 252 of 619
The template function returns !(lhs < rhs).
priority_queue
template<class T,
class Cont = vector<T>,
class Pred = less<Cont::value_type> >
class priority_queue {
public:
typedef Cont::allocator_type allocator_type;
typedef Cont::value_type value_type;
typedef Cont::size_type size_type;
explicit priority_queue(const Pred& pr = Pred(),
const allocator_type& al = allocator_type());
priority_queue(const value_type *first, const value_type *last,
const Pred& pr = Pred(), const allocator_type& al = allocato
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
value_type& top();
const value_type& top() const;
void push(const value_type& x);
void pop();
protected:
Cont c;
Pred comp;
};
The template class describes an object that controls a varying-
length sequence of elements. The object allocates and frees storage
for the sequence it controls through a protected object named c, of
class Cont. The type T of elements in the controlled sequence must
match value_type.
The sequence is ordered using a protected object named comp. After
each insertion or removal of the top element (at position zero),
for the iterators P0 and Pi designating elements at positions 0 and
i, comp(*P0, *Pi) is false. (For the default template parameter
less<Cont::value_type>, the top element of the sequence compares
largest, or highest priority.)
An object of class Cont must supply random-access iterators and
several public members defined the same as for deque and vector
(both of which are suitable candidates for class Cont). The
required members are:
typedef T value_type;
typedef T0 size_type;
Cont(const A& al);
Cont(InIt first, InIt last, const allocator_type& al);
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
const value_type& front() const;
value_type& front();
void push_back(const value_type& x);
file:///D|/97/c++_1/LIBREF.TXT (255 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 253 of 619
void pop_back();
Here, T0 is an unspecified type that meets the stated requirements.
priority_queue::allocator_type
typedef Cont::allocator_type allocator_type;
The type is a synonym for Cont::allocator_type.
priority_queue::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
See the related sample program.
priority_queue::get_allocator
allocator_type get_allocator() const;
The member function returns c.get_allocator().
priority_queue::pop
void pop();
The member function removes the first element of the controlled
sequence, which must be non-empty, then reorders it.
See the related sample program.
priority_queue::priority_queue
explicit priority_queue(const Pred& pr = Pred(),
const allocator_type& al = allocator_type());
priority_queue(const value_type *first, const value_type *last,
const Pred& pr = Pred(), const allocator_type& al = allocator_ty
Both constructors store pr in comp and effectively initialize the
stored object with c(al), to specify an empty initial controlled
sequence. The template constructor then calls push(x) for x, an
iterator of class InIt in the range [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
priority_queue(InIt first, InIt last,
const Pred& pr = Pred(), const allocator_type& al = allocato
is replaced by:
priority_queue(const value_type *first, const value_type *last,
const Pred& pr = Pred(), const allocator_type& al = allocator_ty
file:///D|/97/c++_1/LIBREF.TXT (256 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 254 of 619
priority_queue::push
void push(const T& x);
The member function inserts an element with value x at the end of
the controlled sequence, then reorders it.
See the related sample program.
priority_queue::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
priority_queue::size_type
typedef Cont::size_type size_type;
The type is a synonym for Cont::size_type.
priority_queue::top
value_type& top();
const value_type& top() const;
The member function returns a reference to the first (highest
priority) element of the controlled sequence, which must be non-
empty.
See the related sample program.
priority_queue::value_type
typedef Cont::value_type value_type;
The type is a synonym for Cont::value_type.
queue
template<class T,
class Cont = deque<T> >
class queue {
public:
typedef Cont::allocator_type allocator_type;
typedef Cont::value_type value_type;
typedef Cont::size_type size_type;
explicit queue(const allocator_type& al = allocator_type()) cons
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
value_type& top();
const value_type& top() const;
void push(const value_type& x);
file:///D|/97/c++_1/LIBREF.TXT (257 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 255 of 619
void pop();
protected:
Cont c;
};
The template class describes an object that controls a varying-
length sequence of elements. The object allocates and frees storage
for the sequence it controls through a protected object named c, of
class Cont. The type T of elements in the controlled sequence must
match value_type.
An object of class Cont must supply several public members defined
the same as for deque and list (both of which are suitable
candidates for class Cont). The required members are:
typedef T value_type;
typedef T0 size_type;
Cont(const allocator_type& al);
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
value_type& front();
const value_type& front() const;
value_type& back();
const value_type& back() const;
void push_back(const value_type& x);
void pop_front();
Here, T0 is an unspecified type that meets the stated requirements.
queue::allocator_type
typedef Cont::allocator_type allocator_type;
The type is a synonym for Cont::allocator_type.
queue::back
value_type& back();
const value_type& back() const;
The member function returns a reference to the last element of the
controlled sequence, which must be non-empty.
See the related sample program.
queue::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
See the related sample program.
queue::front
value_type& front();
file:///D|/97/c++_1/LIBREF.TXT (258 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 256 of 619
const value_type& front() const;
The member function returns a reference to the first element of the
controlled sequence, which must be non-empty.
See the related sample program.
queue::get_allocator
allocator_type get_allocator() const;
The member function returns c.get_allocator().
queue::pop
void pop();
The member function removes the last element of the controlled
sequence, which must be non-empty.
See the related sample program.
queue::push
void push(const T& x);
The member function inserts an element with value x at the end of
the controlled sequence.
See the related sample program.
queue::queue
explicit queue(const allocator_type& al = allocator_type());
The constructor initializes the stored object with c(al), to
specify an empty initial controlled sequence.
queue::size
size_type size() const;
The member function returns the length of the controlled sequence.
queue::size_type
typedef Cont::size_type size_type;
The type is a synonym for Cont::size_type.
queue::top
value_type& top();
const value_type& top() const;
The member function returns a reference to the first element of the
controlled sequence, which must be non-empty.
file:///D|/97/c++_1/LIBREF.TXT (259 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 257 of 619
queue::value_type
typedef Cont::value_type value_type;
The type is a synonym for Cont::value_type.
<set>
namespace std {
template<class Key, class Pred, class A>
class set;
template<class Key, class Pred, class A>
class multiset;
// TEMPLATE FUNCTIONS
template<class Key, class Pred, class A>
bool operator==(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator==(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator!=(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator!=(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<=(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<=(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>=(
file:///D|/97/c++_1/LIBREF.TXT (260 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 258 of 619
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>=(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
void swap(
const set<Key, Pred, A>& lhs,
const set<Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
void swap(
const multiset<Key, Pred, A>& lhs,
const multiset<Key, Pred, A>& rhs);
};
Include the STL standard header <set> to define the container
template classes set and multiset, and their supporting templates.
multiset
allocator_type . begin .
clear . const_iterator . const_reference .
const_reverse_iterator . count . difference_type . empty . end .
equal_range . erase . find . get_allocator . insert . iterator .
key_comp . key_compare .
key_type . lower_bound . max_size .
multiset . rbegin reference
. . rend . reverse_iterator . size .
size_type . swap . upper_bound . value_comp . value_compare .
value_type
template<class Key, class Pred = less<Key>, class A = allocator<Key>
class multiset {
public:
typedef Key key_type;
typedef Pred key_compare;
typedef Key value_type;
typedef Pred value_compare;
typedef A allocator_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::rebind<value_type>::other::const_reference reference;
typedef A::rebind<value_type>::other::const_reference const_refe
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::const_pointer,
difference_type> reverse_iterator;
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::pointer,
difference_type> const_reverse_iterator;
explicit multiset(const Pred& comp = Pred(), const A& al = A());
multiset(const multiset& x);
multiset(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
const_iterator begin() const;
iterator end() const;
const_reverse_iterator rbegin() const;
file:///D|/97/c++_1/LIBREF.TXT (261 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
const_reverse_iterator rend() const;
file:///D|/97/c++_1/LIBREF.TXT (262 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 259 of 619
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
iterator insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
void clear();
void swap(multiset x);
key_compare key_comp() const;
value_compare value_comp() const;
const_iterator find(const Key& key) const;
size_type count(const Key& key) const;
const_iterator lower_bound(const Key& key) const;
const_iterator upper_bound(const Key& key) const;
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type const Key. Each element serves
as both a sort key and a value. The sequence is represented in a
way that permits lookup, insertion, and removal of an arbitrary
element with a number of operations proportional to the logarithm
of the number of elements in the sequence (logarithmic time).
Moreover, inserting an element invalidates no iterators, and
removing an element invalidates only those iterators that point at
the removed element.
The object orders the sequence it controls by calling a stored
function object of type Pred. You access this stored object by
calling the member function key_comp(). Such a function object must
impose a total order on sort keys. For any element x that precedes
y in the sequence, key_comp()(y, x) is false. (For the default
function object less<Key>, sort keys never decrease in value.)
Unlike template class set, an object of template class multiset
does not ensure that key_comp()(x, y) is true. (Keys need not be
unique.)
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
multiset::allocator_type
yypedef A allocator_type;
The type is a synonym for the template parameter A.
multiset::begin
file:///D|/97/c++_1/LIBREF.TXT (263 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 260 of 619
const_iterator begin() const;
The member function returns a bidirectional iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
multiset::clear
void clear() const;
The member function calls erase( begin(), end()).
multiset::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant
bidirectional iterator for the controlled sequence. It is described
here as a synonym for the unspecified type T1.
multiset::const_reference
typedef A::rebind<value_type>::other::const_reference const_referenc
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
multiset::const_reverse_iterator
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
The type describes an object that can serve as a constant reverse
bidirectional iterator for the controlled sequence.
multiset::count
size_type count(const Key& key) const;
The member function returns the number of elements x in the range
[lower_bound(key), upper_bound(key)).
multiset::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
multiset::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
file:///D|/97/c++_1/LIBREF.TXT (264 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 261 of 619
multiset::end
const_iterator end() const;
The member function returns a bidirectional iterator that points
just beyond the end of the sequence.
multiset::equal_range
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
The member function returns a pair of iterators x such that x.first
== lower_bound(key) and x.second == upper_bound(key).
multiset::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements in the range [first, last). Both return an iterator that
designates the first element remaining beyond any elements removed,
or end() if no such element exists.
The third member removes the elements with sort keys in the range
[lower_bound(key), upper_bound(key)). It returns the number of
elements it removes.
multiset::find
const_iterator find(const Key& key) const;
The member function returns an iterator that designates the
earliest element in the controlled sequence whose sort key equals
key. If no such element exists, the iterator equals end().
multiset::get_allocator
A get_allocator() const;
The member function returns allocator.
multiset::insert
iterator insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
The first member function inserts the element x in the controlled
sequence, then returns the iterator that designates the inserted
element. The second member function returns insert(x), using it as
a starting place within the controlled sequence to search for the
insertion point. (Insertion can occur in amortized constant time,
file:///D|/97/c++_1/LIBREF.TXT (265 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 262 of 619
instead of logarithmic time, if the insertion point immediately
follows it.) The third member function inserts the sequence of
element values in the range [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(InIt first, InIt last);
is replaced by:
void insert(const value_type *first, const value_type *last);
multiset::iterator
typedef T0 iterator;
The type describes an object that can serve as a bidirectional
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
multiset::key_comp
key_compare key_comp() const;
The member function returns the stored function object that
determines the order of elements in the controlled sequence. The
stored object defines the member function:
bool operator(const Key& x, const Key& y);
which returns true if x strictly precedes y in the sort order.
multiset::key_compare
typedef Pred key_compare;
The type describes a function object that can compare two sort keys
to determine the relative order of any two elements in the
controlled sequence.
multiset::key_type
typedef Key key_type;
The type describes the sort key object that constitutes each
element of the controlled sequence.
multiset::lower_bound
const_iterator lower_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(x, key) is false.
file:///D|/97/c++_1/LIBREF.TXT (266 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 263 of 619
If no such element exists, the function returns end().
multiset::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
multiset::multiset
explicit multiset(const Pred& comp = Pred(), const A& al = A());
multiset(const multiset& x);
multiset(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
The constructors with an argument named comp store the function
object so that it can be later returned by calling key_comp(). All
constructors also store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
copy of the sequence controlled by x. The last constructor
specifies the sequence of element values [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
multiset(InIt first, InIt last,
const Pred& comp = Pred(), const A& al = A());
is replaced by:
multiset(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
multiset::rbegin
const_reverse_iterator rbegin() const;
The member function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. Hence, it
designates the beginning of the reverse sequence.
multiset::reference
typedef A::rebind<value_type>::other::const_reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
multiset::rend
const_reverse_iterator rend() const;
file:///D|/97/c++_1/LIBREF.TXT (267 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 264 of 619
The member function returns a reverse bidirectional iterator that
points at the first element of the sequence (or just beyond the end
of an empty sequence). Hence, it designates the end of the reverse
sequence.
multiset::reverse_iterator
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
The type describes an object that can serve as a reverse
bidirectional iterator for the controlled sequence.
multiset::size
size_type size() const;
The member function returns the length of the controlled sequence.
multiset::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
multiset::swap
void swap(multiset& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
multiset::upper_bound
const_iterator upper_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(key, x) is true.
If no such element exists, the function returns end().
multiset::value_comp
value_compare value_comp() const;
The member function returns a function object that determines the
order of elements in the controlled sequence.
multiset::value_compare
file:///D|/97/c++_1/LIBREF.TXT (268 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 265 of 619
typedef Pred value_compare;
The type describes a function object that can compare two elements
as sort keys to determine their relative order in the controlled
sequence.
multiset::value_type
typedef Key value_type;
The type describes an element of the controlled sequence.
operator!=
template<class Key, class Pred, class A>
bool operator!=(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator!=(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class Key, class Pred, class A>
bool operator==(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator==(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The first template function overloads operator== to compare two
objects of template class set. The second template function
overloads operator== to compare two objects of template class
multiset. Both functions return lhs.size() == rhs.size() && equal
(lhs. begin(), lhs. end(), rhs.begin()).
operator<
template<class Key, class Pred, class A>
bool operator<(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The first template function overloads operator< to compare two
objects of template class set. The second template function
overloads operator< to compare two objects of template class
file:///D|/97/c++_1/LIBREF.TXT (269 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 266 of 619
multiset. Both functions return lexicographical_compare(lhs. begin
(), lhs. end(), rhs.begin(), rhs.end()).
operator<=
template<class Key, class Pred, class A>
bool operator<=(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator<=(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class Key, class Pred, class A>
bool operator>(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The template function returns rhs < lhs.
operator>=
template<class Key, class Pred, class A>
bool operator>=(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
bool operator>=(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
The template function returns !(lhs < rhs).
set
allocator_type . begin . clear . const_iterator . <
b>const_reference . const_reverse_iterator . count .
difference_type . empty end
. . equal_range . erase . find .
get_allocator . insert . iterator . key_comp . key_compare .
key_type . lower_bound . set . max_size . rbegin . reference . rend
. reverse_iterator . size . size_type . swap . upper_bound .
value_comp . value_ compare . value_type
template<class Key, class Pred = less<Key>, class A = allocator<Key>
class set {
public:
typedef Key key_type;
typedef Pred key_compare;
file:///D|/97/c++_1/LIBREF.TXT (270 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 267 of 619
typedef Key value_type;
typedef Pred value_compare;
typedef A allocator_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::rebind<value_type>::other::const_reference reference;
typedef A::rebind<value_type>::other::const_reference const_refe
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
explicit set(const Pred& comp = Pred(), const A& al = A());
set(const set& x);
set(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
const_iterator begin() const;
iterator end() const;
const_reverse_iterator rbegin() const;
const_reverse_iterator rend() const;
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
pair<iterator, bool> insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(InIt first, InIt last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
void clear();
void swap(set x);
key_compare key_comp() const;
value_compare value_comp() const;
const_iterator find(const Key& key) const;
size_type count(const Key& key) const;
const_iterator lower_bound(const Key& key) const;
const_iterator upper_bound(const Key& key) const;
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type const Key. Each element serves
as both a sort key and a value. The sequence is represented in a
way that permits lookup, insertion, and removal of an arbitrary
element with a number of operations proportional to the logarithm
of the number of elements in the sequence (logarithmic time).
Moreover, inserting an element invalidates no iterators, and
removing an element invalidates only those iterators that point at
the removed element.
file:///D|/97/c++_1/LIBREF.TXT (271 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 268 of 619
The object orders the sequence it controls by calling a stored
function object of type Pred. You access this stored object by
calling the member function key_comp(). Such a function object must
impose a total order on sort keys. For any element x that precedes
y in the sequence, key_comp()(y, x) is false. (For the default
function object less<Key>, sort keys never decrease in value.)
Unlike template class multiset, an object of template class set
ensures that key_comp()(x, y) is true. (Each key is unique.)
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
set::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
set::begin
const_iterator begin() const;
The member function returns a bidirectional iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
See the related sample program.
set::clear
void clear() const;
The member function calls erase( begin(), end()).
See the related sample program.
set::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant
bidirectional iterator for the controlled sequence. It is described
here as a synonym for the unspecified type T1.
set::const_reference
typedef A::rebind<value_type>::other::const_reference const_referenc
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
set::const_reverse_iterator
file:///D|/97/c++_1/LIBREF.TXT (272 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 269 of 619
typedef reverse_bidirectional_iterator<const_iterator,
value_type, const_reference, A::const_pointer,
difference_type> const_reverse_iterator;
The type describes an object that can serve as a constant reverse
bidirectional iterator for the controlled sequence.
set::count
size_type count(const Key& key) const;
The member function returns the number of elements x in the range
[lower_bound(key), upper_bound(key)).
See the related sample program.
set::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
set::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
See the related sample program.
set::end
const_iterator end() const;
The member function returns a bidirectional iterator that points
just beyond the end of the sequence.
See the related sample program.
set::equal_range
pair<const_iterator, const_iterator>
equal_range(const Key& key) const;
The member function returns a pair of iterators x such that x.first
== lower_bound(key) and x.second == upper_bound(key).
set::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
size_type erase(const Key& key);
The first member function removes the element of the controlled
file:///D|/97/c++_1/LIBREF.TXT (273 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 270 of 619
sequence pointed to by it. The second member function removes the
elements in the range [first, last). Both return an iterator that
designates the first element remaining beyond any elements removed,
or end() if no such element exists.
The third member removes the elements with sort keys in the range
[lower_bound(key), upper_bound(key)). It returns the number of
elements it removes.
set::find
const_iterator find(const Key& key) const;
The member function returns an iterator that designates the
earliest element in the controlled sequence whose sort key equals
key. If no such element exists, the iterator equals end().
See the related sample program.
set::get_allocator
A get_allocator() const;
The member function returns allocator.
set::insert
pair<iterator, bool> insert(const value_type& x);
iterator insert(iterator it, const value_type& x);
void insert(const value_type *first, const value_type *last);
The first member function determines whether an element y exists in
the sequence whose key matches that of x. (The keys match if !
key_comp()(x, y) && !key_comp()(y, x).) If not, it creates such an
element y and initializes it with x. The function then determines
the iterator it that designates y. If an insertion occurred, the
function returns pair(it, true). Otherwise, it returns pair(it,
false).
The second member function returns insert(x), using it as a
starting place within the controlled sequence to search for the
insertion point. (Insertion can occur in amortized constant time,
instead of logarithmic time, if the insertion point immediately
follows it.) The third member function inserts the sequence of
element values in the range [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(InIt first, InIt last);
is replaced by:
void insert(const value_type *first, const value_type *last);
set::iterator
file:///D|/97/c++_1/LIBREF.TXT (274 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 271 of 619
typedef T0 iterator;
The type describes an object that can serve as a bidirectional
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
set::key_comp
key_compare key_comp() const;
The member function returns the stored function object that
determines the order of elements in the controlled sequence. The
stored object defines the member function:
bool operator(const Key& x, const Key& y);
which returns true if x strictly precedes y in the sort order.
See the related sample program.
set::key_compare
typedef Pred key_compare;
The type describes a function object that can compare two sort keys
to determine the relative order of any two elements in the
controlled sequence.
set::key_type
typedef Key key_type;
The type describes the sort key object that constitutes each
element of the controlled sequence.
set::lower_bound
const_iterator lower_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(x, key) is false.
If no such element exists, the function returns end().
set::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
See the related sample program.
set::rbegin
file:///D|/97/c++_1/LIBREF.TXT (275 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 272 of 619
const_reverse_iterator rbegin() const;
The member function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. Hence, it
designates the beginning of the reverse sequence.
See the related sample program.
set::reference
typedef A::rebind<value_type>::other::const_reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
set::rend
const_reverse_iterator rend() const;
The member function returns a reverse bidirectional iterator that
points at the first element of the sequence (or just beyond the end
of an empty sequence). Hence, it designates the end of the reverse
sequence.
See the related sample program.
set::reverse_iterator
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::pointer,
difference_type> reverse_iterator;
The type describes an object that can serve as a reverse
bidirectional iterator for the controlled sequence.
set::set
explicit set(const Pred& comp = Pred(), const A& al = A());
set(const set& x);
set(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
The constructors with an argument named comp store the function
object so that it can be later returned by calling key_comp(). All
constructors also store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
copy of the sequence controlled by x. The last constructor
specifies the sequence of element values [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
set(InIt first, InIt last,
file:///D|/97/c++_1/LIBREF.TXT (276 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 273 of 619
const Pred& comp = Pred(), const A& al = A());
is replaced by:
set(const value_type *first, const value_type *last,
const Pred& comp = Pred(), const A& al = A());
set::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
set::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
set::swap
void swap(set& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
See the related sample program.
set::upper_bound
const_iterator upper_bound(const Key& key) const;
The member function returns an iterator that designates the
earliest element x in the controlled sequence for which key_comp()
(key, x) is true.
If no such element exists, the function returns end().
set::value_comp
value_compare value_comp() const;
The member function returns a function object that determines the
order of elements in the controlled sequence.
See the related sample program.
set::value_compare
typedef Pred value_compare;
file:///D|/97/c++_1/LIBREF.TXT (277 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 274 of 619
The type describes a function object that can compare two elements
as sort keys to determine their relative order in the controlled
sequence.
set::value_type
typedef Key value_type;
The type describes an element of the controlled sequence.
swap
template<class Key, class Pred, class A>
void swap(
const multiset <Key, Pred, A>& lhs,
const multiset <Key, Pred, A>& rhs);
template<class Key, class Pred, class A>
void swap(
const set <Key, Pred, A>& lhs,
const set <Key, Pred, A>& rhs);
The template function executes lhs.swap(rhs).
<sstream>
namespace std {
template<class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_stringbuf;
typedef basic_stringbuf<char> stringbuf;
typedef basic_stringbuf<wchar_t> wstringbuf;
template<class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_istringstream;
typedef basic_istringstream<char> istringstream;
typedef basic_istringstream<wchar_t> wistringstream;
template<class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_ostringstream;
typedef basic_ostringstream<char> ostringstream;
typedef basic_ostringstream<wchar_t> wostringstream;
template<class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_stringstream;
typedef basic_stringstream<char> stringstream;
typedef basic_stringstream<wchar_t> wstringstream;
};
Include the iostreams standard header <sstream> to define several
template classes that support iostreams operations on sequences
stored in an allocated array object. Such sequences are easily
converted to and from objects of template class basic_string.
file:///D|/97/c++_1/LIBREF.TXT (278 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 275 of 619
basic_stringbuf
template <class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_stringbuf {
public:
basic_stringbuf(ios_base::openmode mode =
ios_base::in | ios_base::out);
basic_stringbuf(basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in | ios_base::out);
basic_string<E, T, A> str() const;
void str(basic_string<E, T, A>& x);
protected:
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode mode = ios_base::in | ios_base::out);
virtual pos_type seekpos(pos_type sp,
ios_base::openmode mode = ios_base::in | ios_base::out);
virtual int_type underflow();
virtual int_type pbackfail(int_type c = T::eof());
virtual int_type overflow(int_type c = T::eof());
};
The template class describes a stream buffer that controls the
transmission of elements to and from a sequence of elements stored
in an array object. The object is allocated, extended, and freed as
necessary to accommodate changes in the sequence.
An object of class basic_stringbuf<E, T, A> stores a copy of the
ios_base::openmode argument from its constructor as its stringbuf
mode mode:
lIf mode & ios_base::in is nonzero, the input buffer is
accessible.
lIf mode & ios_base::out is nonzero, the output buffer is
accessible.
basic_stringbuf::basic_stringbuf
basic_stringbuf(ios_base::openmode mode =
ios_base::in | ios_base::out);
basic_stringbuf(basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in | ios_base::out);
The first constructor stores a null pointer in all the pointers
controlling the input buffer and the output buffer. It also stores
mode as the stringbuf mode.
The second constructor allocates a copy of the sequence controlled
by x, an object of class basic_string<E, T, A>. If mode &
ios_base::in is nonzero, it sets the input buffer to begin reading
at the start of the sequence. If mode & ios_base::out is nonzero,
it sets the output buffer to begin writing at the start of the
sequence. It also stores mode as the stringbuf mode.
basic_stringbuf::overflow
file:///D|/97/c++_1/LIBREF.TXT (279 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 276 of 619
virtual int_type overflow(int_type c = T::eof());
If c does not compare equal to T::eof(), the protected virtual
member function endeavors to insert the element T::to_char_type(c)
into the output buffer. It can do so in various ways:
lIf a write position is available, it can store the element into
the write position and increment the next pointer for the
output buffer.
lIt can make a write position available by allocating new or
additional storage for the output buffer. (Extending the output
buffer this way also extends any associated input buffer.)
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns T::not_eof(c).
basic_stringbuf::pbackfail
virtual int_type pbackfail(int_type c = T::eof());
The protected virtual member function endeavors to put back an
element into the input buffer, then make it the current element
(pointed to by the next pointer). If c compares equal to T::eof(),
the element to push back is effectively the one already in the
stream before the current element. Otherwise, that element is
replaced by x = T::to_char_type(c). The function can put back an
element in various ways:
lIf a putback position is available, and the element stored
there compares equal to x, it can simply decrement the next
pointer for the input buffer.
lIf a putback position is available, and if the stringbuf mode
permits the sequence to be altered (mode & ios_base::out is
nonzero), it can store x into the putback position and
decrement the next pointer for the input buffer.
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns T::not_eof(c).
basic_stringbuf::seekoff
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode mode = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class basic_stringbuf<E, T, A>, a stream position consists purely
of a stream offset. Offset zero designates the first element of the
controlled sequence.
The new position is determined as follows:
lIf way == ios_base::beg, the new position is the beginning of
the stream plus off.
lIf way == ios_base::cur, the new position is the current stream
position plus off.
file:///D|/97/c++_1/LIBREF.TXT (280 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 277 of 619
lIf way == ios_base::end, the new position is the end of the
stream plus off.
If mode & ios_base::in is nonzero, the function alters the next
position to read in the input buffer. If mode & ios_base::out is
nonzero, the function alters the next position to write in the
output buffer. For a stream to be affected, its buffer must exist.
For a positioning operation to succeed, the resulting stream
position must lie within the controlled sequence. If the function
affects both stream positions, way must be ios_base::beg or
ios_base::end and both streams must be positioned at the same
element. Otherwise (or if neither position is affected), the
positioning operation fails.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position. Otherwise, it fails and
returns an invalid stream position.
basic_stringbuf::seekpos
virtual pos_type seekpos(pos_type sp,
ios_base::openmode mode = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class basic_stringbuf<E, T, A>, a stream position consists purely
of a stream offset. Offset zero designates the first element of the
controlled sequence. The new position is determined by sp.
If mode & ios_base::in is nonzero, the function alters the next
position to read in the input buffer. If mode & ios_base::out is
nonzero, the function alters the next position to write in the
output buffer. For a stream to be affected, its buffer must exist.
For a positioning operation to succeed, the resulting stream
position must lie within the controlled sequence. Otherwise (or if
neither position is affected), the positioning operation fails.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position. Otherwise, it fails and
returns an invalid stream position.
basic_stringbuf::str
basic_string<E, T, A> str() const;
void str(basic_string<E, T, A>& x);
The first member function returns an object of class
basic_string<E, T, allocator>, whose controlled sequence is a copy
of the sequence controlled by *this. The sequence copied depends on
the stored stringbuf mode mode:
lIf mode & ios_base::out is nonzero and an output buffer exists,
the sequence is the entire output buffer (epptr() - pbase()
elements beginning with pbase()).
lOtherwise, if mode & ios_base::in is nonzero and an input
buffer exists, the sequence is the entire input buffer (egptr()
- eback() elements beginning with eback()).
file:///D|/97/c++_1/LIBREF.TXT (281 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 278 of 619
lOtherwise, the copied sequence is empty.
The second member function deallocates any sequence currently
controlled by *this. It then allocates a copy of the sequence
controlled by x. If mode & ios_base::in is nonzero, it sets the
input buffer to begin reading at the beginning of the sequence. If
mode & ios_base::out is nonzero, it sets the output buffer to begin
writing at the beginning of the sequence.
basic_stringbuf::underflow
virtual int_type underflow();
The protected virtual member function endeavors to extract the
current element c from the input buffer, then advance the current
stream position, and return the element as T::to_int_type(c). It
can do so in only one way: If a read position is available, it
takes c as the element stored in the read position and advances the
next pointer for the input buffer.
If the function cannot succeed, it returns T::eof(). Otherwise, it
returns the current element in the input stream, converted as
described above.
basic_istringstream
template <class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_istringstream : public basic_istream<E, T> {
public:
explicit basic_istringstream(ios_base::openmode mode = ios_base:
explicit basic_istringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in);
basic_stringbuf<E, T, A> *rdbuf() const;
basic_string<E, T, A>& str();
void str(const basic_string<E, T, A>& x);
};
The template class describes an object that controls extraction of
elements and encoded objects from a stream buffer of class
basic_stringbuf<E, T, A>, with elements of type E, whose character
traits are determined by the class T, and whose elements are
allocated by an allocator of class A. The object stores an object
of class basic_stringbuf<E, T, A>.
basic_istringstream::basic_istringstream
explicit basic_istringstream(ios_base::openmode mode = ios_base::in)
explicit basic_istringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in);
The first constructor initializes the base class by calling
basic_istream(sb), where sb is the stored object of class
basic_stringbuf<E, T, A>. It also initializes sb by calling
basic_stringbuf<E, T, A>(mode | ios_base::in).
file:///D|/97/c++_1/LIBREF.TXT (282 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 279 of 619
The second constructor initializes the base class by calling
basic_istream(sb). It also initializes sb by calling
basic_stringbuf<E, T, A>(x, mode | ios_base::in).
basic_istringstream::rdbuf
basic_stringbuf<E, T, A> *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to basic_stringbuf<E, T, A>.
basic_istringstream::str
basic_string<E, T, A> str() const;
void str(basic_string<E, T, A>& x);
The first member function returns rdbuf()-> str(). The second
member function calls rdbuf()-> str(x).
basic_ostringstream
template <class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_ostringstream : public basic_ostream<E, T> {
public:
explicit basic_ostringstream(ios_base::openmode mode = ios_base:
explicit basic_ostringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::out);
basic_stringbuf<E, T, A> *rdbuf() const;
basic_string<E, T, A>& str();
void str(const basic_string<E, T, A>& x);
};
The template class describes an object that controls insertion of
elements and encoded objects into a stream buffer of class
basic_stringbuf<E, T, A>, with elements of type E, whose character
traits are determined by the class T, and whose elements are
allocated by an allocator of class A. The object stores an object
of class basic_stringbuf<E, T, A>.
basic_ostringstream::basic_ostringstream
explicit basic_ostringstream(ios_base::openmode mode = ios_base::out
explicit basic_ostringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::out);
The first constructor initializes the base class by calling
basic_ostream(sb), where sb is the stored object of class
basic_stringbuf<E, T, A>. It also initializes sb by calling
basic_stringbuf<E, T, A>(mode | ios_base::out).
The second constructor initializes the base class by calling
basic_ostream(sb). It also initializes sb by calling
basic_stringbuf<E, T, A>(x, mode | ios_base::out).
file:///D|/97/c++_1/LIBREF.TXT (283 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 280 of 619
basic_ostringstream::rdbuf
basic_stringbuf<E, T, A> *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to basic_stringbuf<E, T, A>.
basic_ostringstream::str
basic_string<E, T, A> str() const;
void str(basic_string<E, T, A>& x);
The first member function returns rdbuf()-> str(). The second
member function calls rdbuf()-> str(x).
basic_stringstream
template <class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_stringstream : public basic_iostream<E, T> {
public:
explicit basic_stringstream(ios_base::openmode mode = ios_base::
explicit basic_stringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in | ios_base::out);
basic_stringbuf<E, T, A> *rdbuf() const;
basic_string<E, T, A>& str();
void str(const basic_string<E, T, A>& x);
};
The template class describes an object that controls insertion and
extraction of elements and encoded objects using a stream buffer of
class basic_stringbuf<E, T, A>, with elements of type E, whose
character traits are determined by the class T, and whose elements
are allocated by an allocator of class A. The object stores an
object of class basic_stringbuf<E, T, A>.
basic_stringstream::basic_stringstream
explicit basic_stringstream(ios_base::openmode mode = ios_base::in |
explicit basic_stringstream(const basic_string<E, T, A>& x,
ios_base::openmode mode = ios_base::in | ios_base::out);
The first constructor initializes the base class by calling
basic_iostream(sb), where sb is the stored object of class
basic_stringbuf<E, T, A>. It also initializes sb by calling
basic_stringbuf<E, T, A>(mode).
The second constructor initializes the base class by calling
basic_ostream(sb). It also initializes sb by calling
basic_stringbuf<E, T, A>(x, mode).
basic_stringstream::rdbuf
basic_stringbuf<E, T, A> *rdbuf() const
file:///D|/97/c++_1/LIBREF.TXT (284 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 281 of 619
The member function returns the address of the stored stream
buffer, of type pointer to basic_stringbuf<E, T, A>.
basic_stringstream::str
basic_string<E, T, A> str() const;
void str(basic_string<E, T, A>& x);
The first member function returns rdbuf()-> str(). The second
member function calls rdbuf()-> str(x).
istringstream
typedef basic_istringstream<char> istringstream;
The type is a synonym for template class basic_istringstream,
specialized for elements of type
ostringstream
typedef basic_ostringstream<char> ostringstream;
The type is a synonym for template class basic_ostringstream,
specialized for elements of type
stringbuf
typedef basic_stringbuf<char> stringbuf;
The type is a synonym for template class basic_stringbuf,
specialized for elements of type
stringstream
typedef basic_stringstream<char> stringstream;
The type is a synonym for template class basic_stringstream,
specialized for elements of type
wistringstream
typedef basic_istringstream<wchar_t> wistringstream;
The type is a synonym for template class basic_istringstream,
specialized for elements of type wchar_t.
wostringstream
typedef basic_ostringstream<wchar_t> wostringstream;
The type is a synonym for template class basic_ostringstream,
specialized for elements of type wchar_t.
wstringbuf
typedef basic_stringbuf<wchar_t> wstringbuf;
file:///D|/97/c++_1/LIBREF.TXT (285 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 282 of 619
The type is a synonym for template class basic_stringbuf,
specialized for elements of type wchar_t.
wstringstream
typedef basic_stringstream<wchar_t> wstringstream;
The type is a synonym for template class basic_stringstream,
specialized for elements of type wchar_t.
<stack>
namespace std {
template<class T, class Cont>
class stack;
// TEMPLATE FUNCTIONS
template<class T, class Cont>
bool operator==(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
template<class T, class Cont>
bool operator!=(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
template<class T, class Cont>
bool operator<(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
template<class T, class Cont>
bool operator>(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
template<class T, class Cont>
bool operator<=(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
template<class T, class Cont>
bool operator>=(const stack<T, Cont>& lhs,
const stack<T, Cont>&);
};
Include the STL standard header <stack> to define the template
class stack and two supporting templates.
operator!=
template<class T, class Cont>
bool operator!=(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function returns !(lhs == rhs).
operator==
template<class T, class Cont>
bool operator==(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function overloads operator== to compare two objects
of template class stack. The function returns lhs.c == rhs.c.
file:///D|/97/c++_1/LIBREF.TXT (286 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 283 of 619
See the related sample program.
operator<
template<class T, class Cont>
bool operator<(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function overloads operator< to compare two objects of
template class stack. The function returns lhs.c < rhs.c.
See the related sample program.
operator<=
template<class T, class Cont>
bool operator<=(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class Cont>
bool operator>(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class Cont>
bool operator>=(const stack <T, Cont>& lhs,
const stack <T, Cont>& rhs);
The template function returns !(lhs < rhs).
stack
template<class T,
class Cont = deque<T> >
class stack {
public:
typedef Cont::allocator_type allocator_type;
typedef Cont::value_type value_type;
typedef Cont::size_type size_type;
explicit stack(const allocator_type& al = allocator_type()) cons
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
value_type& top();
const value_type& top() const;
void push(const value_type& x);
void pop();
protected:
Cont c;
file:///D|/97/c++_1/LIBREF.TXT (287 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 284 of 619
};
The template class describes an object that controls a varying-
length sequence of elements. The object allocates and frees storage
for the sequence it controls through a protected object named c, of
class Cont. The type T of elements in the controlled sequence must
match value_type.
An object of class Cont must supply several public members defined
the same as for deque, list, and vector (all of which are suitable
candidates for class Cont). The required members are:
typedef T value_type;
typedef T0 size_type;
Cont(const allocator_type& al);
bool empty() const;
size_type size() const;
allocator_type get_allocator() const;
value_type& back();
const value_type& back() const;
void push_back(const value_type& x);
void pop_back();
Here, T0 is an unspecified type that meets the stated requirements.
stack::allocator_type
typedef Cont::allocator_type allocator_type;
The type is a synonym for Cont::allocator_type.
stack::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
See the related sample program.
stack::get_allocator
allocator_type get_allocator() const;
The member function returns c.get_allocator().
stack::pop
void pop();
The member function removes the last element of the controlled
sequence, which must be non-empty.
stack::push
void push(const T& x);
The member function inserts an element with value x at the end of
file:///D|/97/c++_1/LIBREF.TXT (288 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 285 of 619
the controlled sequence.
stack::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
stack::size_type
typedef Cont::size_type size_type;
The type is a synonym for Cont::size_type.
stack::stack
explicit stack(const allocator_type& al = allocator_type());
The constructor initializes the stored object with c(al), to
specify an empty initial controlled sequence.
stack::top
value_type& top();
const value_type& top() const;
The member function returns a reference to the last element of the
controlled sequence, which must be non-empty.
See the related sample program.
stack::value_type
typedef Cont::value_type value_type;
The type is a synonym for Cont::value_type.
<stdexcept>
namespace std {
class logic_error;
class domain_error;
class invalid_argument;
class length_error;
class out_of_range;
class runtime_error;
class range_error;
class overflow_error;
class underflow_error;
};
Include the standard header <stdexcept> to define several classes
used for reporting exceptions. The classes form a derivation
hierarchy, as indicated by the indenting above, all derived from
class exception.
file:///D|/97/c++_1/LIBREF.TXT (289 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 286 of 619
domain_error
class domain_error : public logic_error {
public:
domain_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report a domain error. The value returned by what() is
what_arg.data().
invalid_argument
class invalid_argument : public logic_error {
public:
invalid_argument(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report an invalid argument. The value returned by what() is
what_arg.data().
length_error
class length_error : public logic_error {
public:
length_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report an attempt to generate an object too long to be specified.
The value returned by what() is what_arg.data().
logic_error
class logic_error : public exception {
public:
logic_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report errors presumably detectable before the program executes,
such as violations of logical preconditions. The value returned by
what() is what_arg.data().
out_of_range
class out_of_range : public logic_error {
public:
out_of_range(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report an argument that is out of its valid range. The value
returned by what() is what_arg.data().
file:///D|/97/c++_1/LIBREF.TXT (290 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 287 of 619
overflow_error
class overflow_error : public runtime_error {
public:
overflow_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report an arithmetic overflow. The value returned by what() is
what_arg.data().
range_error
class range_error : public runtime_error {
public:
range_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report a range error. The value returned by what() is what_arg.data
().
runtime_error
class runtime_error : public exception {
public:
runtime_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report errors presumably detectable only when the program executes.
The value returned by what() is what_arg.data().
underflow_error
class underflow_error : public runtime_error {
public:
underflow_error(const string& what_arg);
};
The class serves as the base class for all exceptions thrown to
report an arithmetic underflow. The value returned by what() is
what_arg.data().
<streambuf>
namespace std {
template<class E, class T = char_traits<E> >
class basic_streambuf;
typedef basic_streambuf<char, char_traits<char> > streambuf;
typedef basic_streambuf<wchar_t, char_traits<wchar_t> > wstreamb
};
Include the iostreams standard header <streambuf> to define
template class basic_streambuf, which is basic to the operation of
the iostreams classes. (This header is typically included for you
file:///D|/97/c++_1/LIBREF.TXT (291 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 288 of 619
by another of the iostreams headers. You seldom have occasion to
include it directly.)
basic_streambuf
char_type . eback egptr
. . epptr . gbump . getloc . gptr . imbue .
in_avail . int_type . off_type . overflow . pbackfail . pbase .
pbump . pos_type . pptr . pubimbue . pubseekoff . pubseekpos .
pubsetbuf . pubsync . sbumpc . seekoff . seekpos . setbuf . setg .
setp . sgetc . sgetn . showmanyc . snextc . sputbackc . sputc .
sputn . sungetc .
sync . traits_type . uflow . underflow . xsgetn .
xsputn
template <class E, class T = char_traits<E> >
class basic_streambuf {
public:
typedef E char_type;
typedef T traits_type;
typedef T::int_type int_type;
typedef T::pos_type pos_type;
typedef T::off_type off_type;
virtual ~streambuf();
locale pubimbue(const locale& loc);
locale getloc() const;
basic_streambuf *pubsetbuf(E *s, streamsize n);
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_base::in | ios_base::out);
int pubsync();
streamsize in_avail();
int_type snextc();
int_type sbumpc();
int_type sgetc();
streamsize sgetn(E *s, streamsize n);
int_type sputbackc(E c);
int_type sungetc();
int_type sputc(E c);
streamsize sputn(const E *s, streamsize n);
protected:
basic_streambuf();
E *eback() const;
E *gptr() const;
E *egptr() const;
void gbump(int n);
void setg(E *gbeg, E *gnext, E *gend);
E *pbase() const;
E *pptr() const;
E *epptr() const;
void pbump(int n);
void setp(E *pbeg, E *pend);
virtual void imbue(const locale &loc);
virtual basic_streambuf *setbuf(E *s, streamsize n);
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);
file:///D|/97/c++_1/LIBREF.TXT (292 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
file:///D|/97/c++_1/LIBREF.TXT (293 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 289 of 619
virtual int sync();
virtual int showmanyc();
virtual streamsize xsgetn(E *s, streamsize n);
virtual int_type underflow();
virtual int_type uflow();
virtual int_type pbackfail(int_type c = T::eof());
virtual streamsize xsputn(const E *s, streamsize n);
virtual int_type overflow(int_type c = T::eof());
};
The template class describes an abstract base class for deriving a
stream buffer, which controls the transmission of elements to and
from a specific representation of a stream. An object of class
basic_streambuf<E, T> helps control a stream with elements of type
E, whose character traits are determined by the class T.
Every stream buffer conceptually controls two independent streams,
in fact, one for extractions (input) and one for insertions
(output). A specific representation may, however, make either or
both of these streams inaccessible. It typically maintains some
relationship between the two streams. What you insert into the
output stream of a basic_stringbuf<E, T> object, for example, is
what you later extract from its input stream. When you position one
stream of a basic_filebuf<E, T> object, you position the other
stream in tandem.
The public interface to template class basic_streambuf supplies the
operations common to all stream buffers, however specialized. The
protected interface supplies the operations needed for a specific
representation of a stream to do its work. The protected virtual
member functions let you tailor the behavior of a derived stream
buffer for a specific representation of a stream. Each of the
derived stream buffers in the Standard C++ library describes how it
specializes the behavior of its protected virtual member functions.
Documented here is the default behavior for the base class, which
is often to do nothing.
The remaining protected member functions control copying to and
from any storage supplied to buffer transmissions to and from
streams. An input buffer, for example, is characterized by:
leback(), a pointer to the beginning of the buffer
lgptr(), a pointer to the next element to read
legptr(), a pointer just past the end of the buffer
Similarly, an output buffer is characterized by:
lpbase(), a pointer to the beginning of the buffer
lpptr(), a pointer to the next element to write
lepptr(), a pointer just past the end of the buffer
For any buffer, the protocol is:
lIf the next pointer is null, no buffer exists. Otherwise, all
three pointers point into the same sequence. (They can be
safely compared for order.)
lFor an output buffer, if the next pointer compares less than
file:///D|/97/c++_1/LIBREF.TXT (294 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 290 of 619
the end pointer, you can store an element at the write position
designated by the next pointer.
lFor an input buffer, if the next pointer compares less than the
end pointer, you can read an element at the read position
designated by the next pointer.
lFor an input buffer, if the beginning pointer compares less
than the next pointer, you can put back an element at the
putback position designated by the decremented next pointer.
Any protected virtual member functions you write for a class
derived from basic_streambuf<E, T> must cooperate in maintaining
this protocol.
An object of class basic_streambuf<E, T> stores the six pointers
described above. It also stores a locale object in an object of
type locale for potential use by a derived stream buffer.
basic_streambuf::basic_streambuf
basic_streambuf();
The protected constructor stores a null pointer in all the pointers
controlling the input buffer and the output buffer. It also stores
locale::classic() in the locale object.
basic_streambuf::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
basic_streambuf::eback
E *eback() const;
The member function returns a pointer to the beginning of the input
buffer.
basic_streambuf::egptr
E *egptr() const;
The member function returns a pointer just past the end of the
input buffer.
basic_streambuf::epptr
E *epptr() const;
The member function returns a pointer just past the end of the
output buffer.
basic_streambuf::gbump
void gbump(int n);
The member function adds n to the next pointer for the input
file:///D|/97/c++_1/LIBREF.TXT (295 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 291 of 619
buffer.
basic_streambuf::getloc
locale getloc() const;
The member function returns the stored locale object.
basic_streambuf::gptr
E *gptr() const;
The member function returns a pointer to the next element of the
input buffer.
basic_streambuf::imbue
virtual void imbue(const locale &loc);
The default behavior is to do nothing.
basic_streambuf::in_avail
streamsize in_avail();
If a read position is available, the member function returns egptr
() - gptr(). Otherwise, it returns showmanyc().
basic_streambuf::int_type
typedef T::int_type int_type;
The type is a synonym for T::int_type.
basic_streambuf::off_type
typedef T::off_type off_type;
The type is a synonym for T::off_type.
basic_streambuf::overflow
virtual int_type overflow(int_type c = T::eof());
If c does not compare equal to T::eof(), the protected virtual
member function endeavors to insert the element T::to_char_type(c)
into the output stream. It can do so in various ways:
lIf a write position is available, it can store the element into
the write position and increment the next pointer for the
output buffer.
lIt can make a write position available by allocating new or
additional storage for the output buffer.
lIt can make a write position available by writing out, to some
external destination, some or all of the elements between the
beginning and next pointers for the output buffer.
file:///D|/97/c++_1/LIBREF.TXT (296 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 292 of 619
If the function cannot succeed, it returns T::eof() or throws an
exception. Otherwise, it returns T::not_eof(c). The default
behavior is to return T::eof().
basic_streambuf::pbackfail
virtual int_type pbackfail(int_type c = T::eof());
The protected virtual member function endeavors to put back an
element into the input stream, then make it the current element
(pointed to by the next pointer). If c compares equal to T::eof(),
the element to push back is effectively the one already in the
stream before the current element. Otherwise, that element is
replaced by T::to_char_type(c). The function can put back an
element in various ways:
lIf a putback position is available, it can store the element
into the putback position and decrement the next pointer for
the input buffer.
lIt can make a putback position available by allocating new or
additional storage for the input buffer.
lFor a stream buffer with common input and output streams, it
can make a putback position available by writing out, to some
external destination, some or all of the elements between the
beginning and next pointers for the output buffer.
If the function cannot succeed, it returns T::eof() or throws an
exception. Otherwise, it returns some other value. The default
behavior is to return T::eof().
basic_streambuf::pbase
E *pbase() const;
The member function returns a pointer to the beginning of the
output buffer.
basic_streambuf::pbump
void pbump(int n);
The member function adds n to the next pointer for the output
buffer.
basic_streambuf::pos_type
typedef T::pos_type pos_type;
The type is a synonym for T::pos_type.
basic_streambuf::pptr
E *pptr() const;
The member function returns a pointer to the next element of the
output buffer.
file:///D|/97/c++_1/LIBREF.TXT (297 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 293 of 619
basic_streambuf::pubimbue
locale pubimbue(const locale& loc);
The member function stores loc in the locale object, calls imbue(),
and then returns the previous value stored in the locale object.
basic_streambuf::pubseekoff
pos_type pubseekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
The member function returns seekoff(off, way, which).
basic_streambuf::pubseekpos
pos_type pubseekpos(pos_type sp,
ios_base::openmode which = ios_base::in | ios_base::out);
The member function returns seekpos(sp, which).
basic_streambuf::pubsetbuf
basic_streambuf *pubsetbuf(E *s, streamsize n);
The member function returns setbuf(s, n).
basic_streambuf::pubsync
int pubsync();
The member function returns sync().
basic_streambuf::sbumpc
int_type sbumpc();
If a read position is available, the member function returns
T::to_int_type( *gptr()) and increments the next pointer for the
input buffer. Otherwise, it returns uflow().
basic_streambuf::seekoff
virtual pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. The new position is
determined as follows:
lIf way == ios_base::beg, the new position is the beginning of
the stream plus off.
lIf way == ios_base::cur, the new position is the current stream
position plus off.
lIf way == ios_base::end, the new position is the end of the
stream plus off.
file:///D|/97/c++_1/LIBREF.TXT (298 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 294 of 619
Typically, if which & ios_base::in is nonzero, the input stream is
affected, and if which & ios_base::out is nonzero, the output
stream is affected. Actual use of this parameter varies among
derived stream buffers, however.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position (or one of them). Otherwise,
it returns an invalid stream position. The default behavior is to
return an invalid stream position.
basic_streambuf::seekpos
virtual pos_type seekpos(pos_type sp,
ios_base::openmode which = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. The new position is
sp.
Typically, if which & ios_base::in is nonzero, the input stream is
affected, and if which & ios_base::out is nonzero, the output
stream is affected. Actual use of this parameter varies among
derived stream buffers, however.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position (or one of them). Otherwise,
it returns an invalid stream position. The default behavior is to
return an invalid stream position.
basic_streambuf::setbuf
virtual basic_streambuf *setbuf(E *s, streamsize n);
The protected virtual member function performs an operation
peculiar to each derived stream buffer. (See, for example,
basic_filebuf.) The default behavior is to return this.
basic_streambuf::setg
void setg(E *gbeg, E *gnext, E *gend);
The member function stores gbeg in the beginning pointer, gnext in
the next pointer, and gend in the end pointer for the input buffer.
basic_streambuf::setp
void setp(E *pbeg, E *pend);
void setp(E *pbeg, E *pnext, E *pend);
The member function stores pbeg in the beginning pointer, pnext in
the next pointer, and pend in the end pointer for the output
buffer.
basic_streambuf::sgetc
int_type sgetc();
file:///D|/97/c++_1/LIBREF.TXT (299 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 295 of 619
If a read position is available, the member function returns
T::to_int_type( *gptr()) Otherwise, it returns underflow().
basic_streambuf::sgetn
streamsize sgetn(E *s, streamsize n);
The member function returns sgetn(s, n).
basic_streambuf::showmanyc
virtual int showmanyc();
The protected virtual member function returns a count of the number
of characters that can be extracted from the input stream without
the program experiencing an indefinite wait. The default behavior
is to return zero.
basic_streambuf::snextc
int_type snextc();
The member function calls sbumpc() and, if that function returns
T::eof(), returns T::eof(). Otherwise, it returns sgetc().
basic_streambuf::sputbackc
int_type sputbackc(E c);
If a putback position is available and c compares equal to the
character stored in that position, the member function decrements
the next pointer for the input buffer and returns ch, which is the
value T::to_int_type(c). Otherwise, it returns pbackfail(ch).
basic_streambuf::sputc
int_type sputc(E c);
If a write position is available, the member function stores c in
the write position, increments the next pointer for the output
buffer, and returns ch, which is the value T::to_int_type(c).
Otherwise, it returns overflow(ch).
basic_streambuf::sputn
streamsize sputn(const E *s, streamsize n);
The member function returns sputn(s, n).
basic_streambuf::sungetc
int_type sungetc();
If a putback position is available, the member function decrements
the next pointer for the input buffer and returns T::to_int_type
( *gptr()). Otherwise it returns pbackfail().
file:///D|/97/c++_1/LIBREF.TXT (300 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 296 of 619
basic_streambuf::sync
virtual int sync();
The protected virtual member function endeavors to synchronize the
controlled streams with any associated external streams. Typically,
this involves writing out any elements between the beginning and
next pointers for the output buffer. It does not involve putting
back any elements between the next and end pointers for the input
buffer. If the function cannot succeed, it returns -1. The default
behavior is to return zero.
basic_streambuf::traits_type
typedef T traits_type;
The type is a synonym for the template parameter T.
basic_streambuf::uflow
virtual int_type uflow();
The protected virtual member function endeavors to extract the
current element c from the input stream, then advance the current
stream position, and return the element as T::to_int_type(c). It
can do so in various ways:
lIf a read position is available, it takes c as the element
stored in the read position and advances the next pointer for
the input buffer.
lIt can read an element directly, from some external source, and
deliver it as the value c.
lFor a stream buffer with common input and output streams, it
can make a read position available by writing out, to some
external destination, some or all of the elements between the
beginning and next pointers for the output buffer. Or it can
allocate new or additional storage for the input buffer. The
function then reads in, from some external source, one or more
elements.
If the function cannot succeed, it returns T::eof(), or throws an
exception. Otherwise, it returns the current element c in the input
stream, converted as described above, and advances the next pointer
for the input buffer. The default behavior is to call underflow()
and, if that function returns T::eof(), to return T::eof().
Otherwise, the function returns the current element c in the input
stream, converted as described above, and advances the next pointer
for the input buffer.
basic_streambuf::underflow
virtual int_type underflow();
The protected virtual member function endeavors to extract the
current element c from the input stream, without advancing the
current stream position, and return it as T::to_int_type(c). It can
file:///D|/97/c++_1/LIBREF.TXT (301 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 297 of 619
do so in various ways:
lIf a read position is available, c is the element stored in the
read position.
lIt can make a read position available by allocating new or
additional storage for the input buffer, then reading in, from
some external source, one or more elements.
If the function cannot succeed, it returns T::eof(), or throws an
exception. Otherwise, it returns the current element in the input
stream, converted as described above. The default behavior is to
return T::eof().
basic_streambuf::xsgetn
virtual streamsize xsgetn(E *s, streamsize n);
The protected virtual member function extracts up to n elements
from the input stream, as if by repeated calls to sbumpc, and
stores them in the array beginning at s. It returns the number of
elements actually extracted.
basic_streambuf::xsputn
virtual streamsize xsputn(const E *s, streamsize n);
The protected virtual member function inserts up to n elements into
the output stream, as if by repeated calls to sputc, from the array
beginning at s. It returns the number of elements actually
inserted.
streambuf
typedef basic_streambuf<char, char_traits<char> > streambuf;
The type is a synonym for template class basic_streambuf,
specialized for elements of type char with default character
wstreambuf
typedef basic_streambuf<wchar_t, char_traits<wchar_t> > wstreambuf;
The type is a synonym for template class basic_streambuf,
specialized for elements of type wchar_t with default character
traits.
<string>
basic_string . char_traits . char_traits<char> .
char_traits<wchar_t> . getline . operator+ . operator!= .
operator== . operator< . operator<< . operator<= . operator> .
operator>= . operator>> . string . swap . wstring
namespace std {
// TEMPLATE CLASSES
template<class E>
struct char_traits;
file:///D|/97/c++_1/LIBREF.TXT (302 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 298 of 619
struct char_traits<char>;
struct char_traits<wchar_t>;
template<class E,
class T = char_traits<E>,
class A = allocator<E> >
class basic_string;
typedef basic_string<char> string;
typedef basic_string>wchar_t> wstring;
// TEMPLATE FUNCTIONS
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
E rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
E lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator==(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator==(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator==(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator!=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator!=(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator!=(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator<(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (303 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 299 of 619
template<class E, class T, class A>
bool operator<(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator<(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator>(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator<=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator<=(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator<=(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>=(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator>=(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
void swap(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
basic_ostream<E>& operator<<(
basic_ostream <E>& os,
const basic_string<E, T, A>& str);
template<class E, class T, class A>
basic_istream<E>& operator>>(
basic_istream <E>& is,
basic_string<E, T, A>& str);
template<class E, class T, class A>
file:///D|/97/c++_1/LIBREF.TXT (304 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 300 of 619
basic_istream<E, T>& getline(
basic_istream <E, T>& is,
basic_string<E, T, A>& str);
template<class E, class T, class A>
basic_istream<E, T>& getline(
basic_istream <E, T>& is,
basic_string<E, T, A>& str,
E delim);
};
Include the standard header <string> to define the container
template class basic_string and various supporting templates.
basic_string
allocator_type . append . assign . at . basic_string . begin .
c_str . capacity .
char_type . compare . const_iterator .
const_pointer . const_reference . const_reverse_iterator . copy .
data . difference_type . empty . end . erase . find .
find_first_not_of . find_first_of . find_last_not_of . find_last_of
. get_allocator . insert . iterator . length . max_size . npos .
operator+= . operator= . operator[] . pointer . rbegin . reference
. rend . replace . reserve . resize . reverse_iterator . rfind .
size . size_type substr
. . swap . traits_type . value_type
template<class E,
class T = char_traits<E>,
class A = allocator<T> >
class basic_string {
public:
typedef T traits_type;
typedef A allocator_type;
typedef T::char_type char_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::pointer pointer;
typedef A::const_pointer const_pointer;
typedef A::reference reference;
typedef A::const_reference const_reference;
typedef A::value_type value_type;
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_iterator<iterator, value_type,
reference, pointer, difference_type>
reverse_iterator;
typedef reverse_iterator<const_iterator, value_type,
const_reference, const_pointer, difference_type>
const_reverse_iterator;
static const size_type npos = -1;
explicit basic_string(const A& al = A());
basic_string(const basic_string& rhs);
basic_string(const basic_string& rhs, size_type pos, size_type n
const A& al = A());
basic_string(const E *s, size_type n, const A& al = A());
basic_string(const E *s, const A& al = A());
basic_string(size_type n, E c, const A& al = A());
basic_string(const_iterator first, const_iterator last,
file:///D|/97/c++_1/LIBREF.TXT (305 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
file:///D|/97/c++_1/LIBREF.TXT (306 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 301 of 619
const A& al = A());
basic_string& operator=(const basic_string& rhs);
basic_string& operator=(const E *s);
basic_string& operator=(E c);
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;
const_reference at(size_type pos) const;
reference at(size_type pos);
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
const E *c_str() const;
const E *data() const;
size_type length() const;
size_type size() const;
size_type max_size() const;
void resize(size_type n, E c = E());
size_type capacity() const;
void reserve(size_type n = 0);
bool empty() const;
basic_string& operator+=(const basic_string& rhs);
basic_string& operator+=(const E *s);
basic_string& operator+=(E c);
basic_string& append(const basic_string& str);
basic_string& append(const basic_string& str,
size_type pos, size_type n);
basic_string& append(const E *s, size_type n);
basic_string& append(const E *s);
basic_string& append(size_type n, E c);
basic_string& append(const_iterator first, const_iterator last);
basic_string& assign(const basic_string& str);
basic_string& assign(const basic_string& str,
size_type pos, size_type n);
basic_string& assign(const E *s, size_type n);
basic_string& assign(const E *s);
basic_string& assign(size_type n, E c);
basic_string& assign(const_iterator first, const_iterator last);
basic_string& insert(size_type p0,
const basic_string& str);
basic_string& insert(size_type p0,
const basic_string& str, size_type pos, size_type n);
basic_string& insert(size_type p0,
const E *s, size_type n);
basic_string& insert(size_type p0, const E *s);
basic_string& insert(size_type p0, size_type n, E c);
iterator insert(iterator it, E c);
void insert(iterator it, size_type n, E c);
void insert(iterator it,
const_iterator first, const_iterator last);
basic_string& erase(size_type p0 = 0, size_type n = npos);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
file:///D|/97/c++_1/LIBREF.TXT (307 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 302 of 619
basic_string& replace(size_type p0, size_type n0,
const basic_string& str);
basic_string& replace(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
basic_string& replace(size_type p0, size_type n0,
const E *s, size_type n);
basic_string& replace(size_type p0, size_type n0,
const E *s);
basic_string& replace(size_type p0, size_type n0,
size_type n, E c);
basic_string& replace(iterator first0, iterator last0,
const basic_string& str);
basic_string& replace(iterator first0, iterator last0,
const E *s, size_type n);
basic_string& replace(iterator first0, iterator last0,
const E *s);
basic_string& replace(iterator first0, iterator last0,
size_type n, E c);
basic_string& replace(iterator first0, iterator last0,
const_iterator first, const_iterator last);
size_type copy(E *s, size_type n, size_type pos = 0) const;
void swap(basic_string& str);
size_type find(const basic_string& str,
size_type pos = 0) const;
size_type find(const E *s, size_type pos, size_type n) const;
size_type find(const E *s, size_type pos = 0) const;
size_type find(E c, size_type pos = 0) const;
size_type rfind(const basic_string& str,
size_type pos = npos) const;
size_type rfind(const E *s, size_type pos,
size_type n = npos) const;
size_type rfind(const E *s, size_type pos = npos) const;
size_type rfind(E c, size_type pos = npos) const;
size_type find_first_of(const basic_string& str,
size_type pos = 0) const;
size_type find_first_of(const E *s, size_type pos,
size_type n) const;
size_type find_first_of(const E *s, size_type pos = 0) const;
size_type find_first_of(E c, size_type pos = 0) const;
size_type find_last_of(const basic_string& str,
size_type pos = npos) const;
size_type find_last_of(const E *s, size_type pos,
size_type n = npos) con/t;
size_type find_last_of(const E *s, size_type pos = npos) const;
size_type find_last_of(E c, size_type pos = npos) const;
size_type find_first_not_of(const basic_string& str,
size_type pos = 0) const;
size_type find_first_not_of(const E *s, size_type pos,
size_type n) const;
size_type find_first_not_of(const E *s, size_type pos = 0) const
size_type find_first_not_of(E 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 E *s, size_type pos,
size_type n) const;
size_type find_last_not_of(const E *s,
size_type pos = npos) const;
file:///D|/97/c++_1/LIBREF.TXT (308 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 303 of 619
size_type find_last_not_of(E 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 p0, size_type n0,
const basic_string& str);
int compare(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
int compare(const E *s) const;
int compare(size_type p0, size_type n0,
const E *s) const;
int compare(size_type p0, size_type n0,
const E *s, size_type pos) const;
A get_allocator() const;
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type E. Such an element type must
not require explicit construction or destruction, and it must be
suitable for use as the E parameter to basic_istream or
basic_ostream. (A "plain old data structure," or POD, from C
generally meets this criterion.) The Standard C++ library provides
two specializations of this template class, with the type
definitions string, for elements of type char, and wstring,
elements of type wchar_t.
Various important properties of the elements in a basic_string
specialization are described by the class T. A class that specifies
these character traits must have the same external interface as an
object of template class char_traits.
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. (Class char_traits has no provision
for alternative addressing schemes, such as might be required to
implement a far heap.) Note that allocator is not copied when the
object is assigned.
The sequences controlled by an object of template class
basic_string are usually called strings. These objects should not
be confused, however, with the null-terminated C strings used
throughout the Standard C++ library.
Many member functions require an operand sequence of elements of
type E. You can specify such an operand sequence several ways:
lc -- a sequence of one element with value c
ln, c -- a repetition of n elements each with value c
ls -- a null-terminated sequence (such as a C string, for E of
type char) beginning at s (which must not be a null
where the terminating element is the value E(0) and is not part
of the operand sequence
ls, n -- a sequence of n elements beginning at s (which must not
be a null pointer)
lstr -- the sequence specified by the basic_string object str
file:///D|/97/c++_1/LIBREF.TXT (309 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 304 of 619
lstr, pos, n -- the substring of the basic_string object str
with up to n elements (or through the end of the string,
whichever comes first) beginning at position pos
lfirst, last -- a sequence of elements delimited by the
iterators first and last, in the range [first, last)
If a position argument (such as pos above) is beyond the end of the
string on a call to a basic_string member function, the function
reports an out-of-range error by throwing an object of class
out_of_range.
If a function is asked to generate a sequence longer than max_size
() elements, the function reports a length error by throwing an
object of class length_error.
basic_string::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
basic_string::append
basic_string& append(const E *s);
basic_string& append(const E *s, size_type n);
basic_string& append(const basic_string& str,
size_type pos, size_type n);
basic_string& append(const basic_string& str);
basic_string& append(size_type n, E c);
basic_string& append(const_iterator first, const_iterator last);
The member template function appends the operand sequence to the
end of the sequence controlled by *this, then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
basic_string& append(InIt first, InIt last);
is replaced by:
basic_string& append(const_iterator first, const_iterator last);
See the related sample program.
basic_string::assign
basic_string& assign(const E *s);
basic_string& assign(const E *s, size_type n);
basic_string& assign(const basic_string& str,
size_type pos, size_type n);
basic_string& assign(const basic_string& str);
basic_string& assign(size_type n, E c);
basic_string& assign(const_iterator first, const_iterator last);
Each member function replaces the sequence controlled by *this with
file:///D|/97/c++_1/LIBREF.TXT (310 of 626) [28/10/2007 12:33:46 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 305 of 619
the operand sequence, then returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
basic_string& assign(InIt first, InIt last);
is replaced by:
basic_string& assign(const_iterator first, const_iterator last);
basic_string::at
const_reference at(size_type pos) const;
reference at(size_type pos);
Each member function returns a reference to the element of the
controlled sequence at position pos, or reports an out-of-range
error.
basic_string::basic_string
basic_string(const E *s, const A& al = A());
basic_string(const E *s, size_type n, const A& al = A());
basic_string(const basic_string& rhs);
basic_string(const basic_string& rhs, size_type pos, size_type n,
const A& al = A());
basic_string(size_type n, E c, const A& al = A());
explicit basic_string(const A& al = A());
basic_string(const_iterator first, const_iterator last,
const A& al = A());
Each constructor stores the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initializes the
controlled sequence to a copy of the operand sequence specified by
the remaining operands. The explicit constructor specifies an empty
initial controlled sequence.
In this implementation, if a translator does not support member
template functions, the template:
template <class InIt>
basic_string(InIt first, InIt last, const A& al = A());
is replaced by:
basic_string(const_iterator first, const_iterator last,
const A& al = A());
basic_string::begin
const_iterator begin() const;
iterator begin();
Each member function returns a random-access iterator that points
at the first element of the sequence (or just beyond the end of an
file:///D|/97/c++_1/LIBREF.TXT (311 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 306 of 619
empty sequence).
basic_string::c_str
const E *c_str() const;
The member function returns a pointer to a nonmodifiable C string
constructed by adding a terminating null element (E(0)) to the
controlled sequence. Calling any non-const member function for
*this can invalidate the pointer.
basic_string::capacity
size_type capacity() const;
The member function returns the storage currently allocated to hold
the controlled sequence, a value at least as large as size().
basic_string::char_type
typedef T::char_type char_type;
The type is a synonym for the template parameter E.
basic_string::compare
int compare(const basic_string& str) const;
int compare(size_type p0, size_type n0,
const basic_string& str);
int compare(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
int compare(const E *s) const;
int compare(size_type p0, size_type n0,
const E *s) const;
int compare(size_type p0, size_type n0,
const E *s, size_type pos) const;
Each member function compares up to n0 elements of the controlled
sequence beginning with position p0, or the entire controlled
sequence if these arguments are not supplied, to the operand
sequence. The function returns:
lA negative value if the first differing element in the
controlled sequence compares less than the corresponding
element in the operand sequence (as determined by T::compare),
or if the two have a common prefix but the operand sequence is
longer.
lZero if the two compare equal element by element and are the
same length.
lA positive value otherwise.
basic_string::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant random-
access iterator for the controlled sequence. It is described here
file:///D|/97/c++_1/LIBREF.TXT (312 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 307 of 619
as a synonym for the unspecified type T1.
basic_string::const_pointer
typedef A::const_pointer const_pointer;
The type describes an object that can serve as a constant pointer
to an element of the controlled sequence.
basic_string::const_reference
typedef A::const_reference const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
basic_string::const_reverse_iterator
typedef reverse_iterator<const_iterator, value_type,
const_reference, const_pointer, difference_type>
const_reverse_iterator;
The type describes an object that can serve as a constant reverse
iterator for the controlled sequence.
basic_string::copy
size_type copy(E *s, size_type n, size_type pos = 0) const;
The member function copies up to n elements from the controlled
sequence, beginning at position pos, to the array of E, beginning
at s. It returns the number of elements actually copied.
See the related sample program.
basic_string::data
const E *data() const;
The member function returns a pointer to the first element of the
sequence (or, for an empty sequence, a non-null pointer that cannot
be dereferenced).
basic_string::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
basic_string::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
file:///D|/97/c++_1/LIBREF.TXT (313 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 308 of 619
basic_string::end
const_iterator end() const;
iterator end();
Each member function returns a random-access iterator that points
just beyond the end of the sequence.
basic_string::erase
iterator erase(iterator first, iterator last);
iterator erase(iterator it);
basic_string& erase(size_type p0 = 0, size_type n = npos);
The first member function removes the elements of the controlled
sequence in the range [first, last). The second member function
removes the element of the controlled sequence pointed to by it.
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
The third member function removes up to n elements of the
controlled sequence beginning at position p0, then returns *this.
basic_string::find
size_type find(E c, size_type pos = 0) const;
size_type find(const E *s, size_type pos = 0) const;
size_type find(const E *s, size_type pos, size_type n) const;
size_type find(const basic_string& str, size_type pos = 0) const;
Each member function finds the first (lowest beginning position)
subsequence in the controlled sequence, beginning on or after
position pos, that matches the operand sequence specified by the
remaining operands. If it succeeds, it returns the position where
the matching subsequence begins. Otherwise, the function returns
npos.
basic_string::find_first_not_of
size_type find_first_not_of(E c, size_type pos = 0) const;
size_type find_first_not_of(const E *s, size_type pos = 0) const;
size_type find_first_not_of(const E *s, size_type pos,
size_type n) const;
size_type find_first_not_of(const basic_string& str,
size_type pos = 0) const;
Each member function finds the first (lowest position) element of
the controlled sequence, at or after position pos, that matches
none of the elements in the operand sequence specified by the
remaining operands. If it succeeds, it returns the position.
Otherwise, the function returns npos.
basic_string::find_first_of
size_type find_first_of(E c, size_type pos = 0) const;
size_type find_first_of(const E *s, size_type pos = 0) const;
file:///D|/97/c++_1/LIBREF.TXT (314 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 309 of 619
size_type find_first_of(const E *s, size_type pos, size_type n) cons
size_type find_first_of(const basic_string& str,
size_type pos = 0) const;
Each member function finds the first (lowest position) element of
the controlled sequence, at or after position pos, that matches any
of the elements in the operand sequence specified by the remaining
operands. If it succeeds, it returns the position. Otherwise, the
function returns npos.
See the related sample program.
basic_string::find_last_not_of
size_type find_last_not_of(E c, size_type pos = npos) const;
size_type find_last_not_of(const E *s, size_type pos = npos) const;
size_type find_last_not_of(const E *s, size_type pos, size_type n)
size_type find_last_not_of(const basic_string& str,
size_type pos = npos) const;
Each member function finds the last (highest position) element of
the controlled sequence, at or before position pos, that matches
none of the elements in the operand sequence specified by the
remaining operands. If it succeeds, it returns the position.
Otherwise, the function returns npos.
basic_string::find_last_of
size_type find_last_of(E c, size_type pos = npos) const;
size_type find_last_of(const E *s, size_type pos = npos) const;
size_type find_last_of(const E *s, size_type pos, size_type n = npos
size_type find_last_of(const basic_string& str,
size_type pos = npos) const;
Each member function finds the last (highest position) element of
the controlled sequence, at or before position pos, that matches
any of the elements in the operand sequence specified by the
remaining operands. If it succeeds, it returns the position.
Otherwise, the function returns npos.
basic_string::get_allocator
A get_allocator() const;
The member function returns allocator.
basic_string::insert
basic_string& insert(size_type p0, const E *s);
basic_string& insert(size_type p0, const E *s, size_type n);
basic_string& insert(size_type p0,
const basic_string& str);
basic_string& insert(size_type p0,
const basic_string& str, size_type pos, size_type n);
basic_string& insert(size_type p0, size_type n, E c);
iterator insert(iterator it, E c);
void insert(iterator it, const_iterator first, const_iterator last);
file:///D|/97/c++_1/LIBREF.TXT (315 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 310 of 619
void insert(iterator it, size_type n, E c);
Each member function inserts, before position p0 or before the
element pointed to by it in the controlled sequence, the operand
sequence specified by the remaining operands. A function that
returns a value returns *this.
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(iterator it, InIt first, InIt last);
is replaced by:
void insert(iterator it, const_iterator first, const_iterator last);
basic_string::iterator
typedef T0 iterator;
The type describes an object that can serve as a random-access
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
basic_string::length
size_type length() const;
The member function returns the length of the controlled sequence
(same as size()).
basic_string::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
basic_string::npos
static const size_type npos = -1;
The constant is the largest representable value of type size_type.
It is assuredly larger than max_size(); hence it serves as either a
very large value or as a special code.
basic_string::operator+=
basic_string& operator+=(E c);
basic_string& operator+=(const E *s);
basic_string& operator+=(const basic_string& rhs);
Each operator appends the operand sequence to the end of the
sequence controlled by *this, then returns *this.
basic_string::operator=
file:///D|/97/c++_1/LIBREF.TXT (316 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 311 of 619
basic_string& operator=(E c);
basic_string& operator=(const E *s);
basic_string& operator=(const basic_string&nmp rhs);
Each operator replaces the sequence controlled by *this with the
operand sequence, then returns *this.
basic_string::operator[]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Each member function returns a reference to the element of the
controlled sequence at position pos. If that position is invalid,
the behavior is undefined.
basic_string::pointer
typedef A::pointer pointer;
The type describes an object that can serve as a pointer to an
element of the controlled sequence.
basic_string::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse iterator that points just
beyond the end of the controlled sequence. Hence, it designates the
beginning of the reverse sequence.
basic_string::reference
typedef A::reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
basic_string::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
Each member function returns a reverse iterator that points at the
first element of the sequence (or just beyond the end of an empty
sequence). Hence, it designates the end of the reverse sequence.
basic_string::replace
basic_string& replace(size_type p0, size_type n0,
const E *s);
basic_string& replace(size_type p0, size_type n0,
const E *s, size_type n);
basic_string& replace(size_type p0, size_type n0,
const basic_string& str);
file:///D|/97/c++_1/LIBREF.TXT (317 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 312 of 619
basic_string& replace(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
basic_string& replace(size_type p0, size_type n0,
size_type n, E c);
basic_string& replace(iterator first0, iterator last0,
const E *s);
basic_string& replace(iterator first0, iterator last0,
const E *s, size_type n);
basic_string& replace(iterator first0, iterator last0,
const basic_string& str);
basic_string& replace(iterator first0, iterator last0,
size_type n, E c);
basic_string& replace(iterator first0, iterator last0,
const_iterator first, const_iterator last);
Each member function replaces up to n0 elements of the controlled
sequence beginning with position p0, or the elements of the
controlled sequence beginning with the one pointed to by first, up
to but not including last. The replacement is the operand sequence
specified by the remaining operands. The function then returns
*this.
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
basic_string& replace(iterator first0, iterator last0,
InIt first, InIt last);
is replaced by:
basic_string& replace(iterator first0, iterator last0,
const_iterator first, const_iterator last);
basic_string::reserve
void reserve(size_type n = 0);
The member function ensures that capacity() henceforth returns at
least n.
basic_string::resize
void resize(size_type n, E c = E());
The member function ensures that size() henceforth returns n. If it
must lengthen the controlled sequence, it appends elements with
value c.
See the related sample program.
basic_string::reverse_iterator
typedef reverse_iterator<iterator, value_type,
reference, pointer, difference_type>
reverse_iterator;
file:///D|/97/c++_1/LIBREF.TXT (318 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 313 of 619
The type describes an object that can serve as a reverse iterator
for the controlled sequence.
basic_string::rfind
size_type rfind(E c, size_type pos = npos) const;
size_type rfind(const E *s, size_type pos = npos) const;
size_type rfind(const E *s, size_type pos, size_type n = npos) const
size_type rfind(const basic_string& str,
size_type pos = npos) const;
Each member function finds the last (highest beginning position)
subsequence in the controlled sequence, beginning on or before
position pos, that matches the operand sequence specified by the
remaining operands. If it succeeds, it returns the position where
the matching subsequence begins. Otherwise, the function returns
npos.
basic_string::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
basic_string::size_type
typedef A::size_type size_type;
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
basic_string::substr
basic_string substr(size_type pos = 0,
size_type n = npos) const;
The member function returns an object whose controlled sequence is
a copy of up to n elements of the controlled sequence beginning at
position pos.
basic_string::swap
void swap(basic_string& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
basic_string::traits_type
typedef T traits_type;
file:///D|/97/c++_1/LIBREF.TXT (319 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 314 of 619
The type is a synonym for the template parameter T.
basic_string::value_type
typedef A::value_type value_type;
The type is a synonym for the template parameter E.
char_traits
struct char_traits<E> {
typedef E char_type;
typedef T1 int_type;
typedef T2 pos_type;
typedef T3 off_type;
typedef T4 state_type;
static void assign(E& x, const E& y);
static E *assign(E *x, size_t n, const E& y);
static bool eq(const E& x, const E& y);
static bool lt(const E& x, const E& y);
static int compare(const E *x, const E *y, size_t n);
static size_t length(const E *x);
static E *copy(E *x, const E *y, size_t n);
static E *move(E *x, const E *y, size_t n);
static const E *find(const E *x, size_t n, const E& y);
static E to_char_type(const int_type& ch);
static int_type to_int_type(const E& c);
static bool eq_int_type(const int_type& ch1, const int_type& ch2
static int_type eof();
static int_type not_eof(const int_type& ch);
};
The template class describes various character traits for type E.
The template class basic_string as well as several iostreams
template classes, including basic_ios, use this information to
manipulate elements of type E. Such an element type must not
require explicit construction or destruction. A bitwise copy has
the same effect as an assignment.
char_traits::assign
static void assign(E& x, const E& y);
static E *assign(E *x, size_t n, const E& y);
The first static member function assigns y to x. The second static
member function assigns y to each element X[N] for N in the range
[0, N).
char_traits::char_type
typedef E char_type;
The type is a synonym for the template parameter E.
char_traits::compare
file:///D|/97/c++_1/LIBREF.TXT (320 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 315 of 619
static int compare(const E *x, const E *y, size_t n);
The static member function compares the sequence of length n
beginning at x to the sequence of the same length beginning at y.
The function returns:
lA negative value if the first differing element in x (as
determined by eq) compares less than the corresponding element
in y (as determined by lt).
lZero if the two compare equal element by element.
lA positive value otherwise.
char_traits::copy
static E *copy(E *x, const E *y, size_t n);
The static member function copies the sequence of n elements
beginning at y to the array beginning at x, then returns x. The
source and destination must not overlap.
char_traits::eof
static int_type eof();
The static member function returns a value that represents end-of-
file (such as EOF or WEOF). If the value is also representable as
type E, it must correspond to no valid value of that type.
char_traits::eq
static bool eq(const E& x, const E& y);
The static member function returns true if x compares equal to y.
char_traits::eq_int_type
static bool eq_int_type(const int_type& ch1, const int_type& ch2);
The static member function returns true if ch1 == ch2.
char_traits::find
static const E *find(const E *x, size_t n, const E& y);
The static member function determines the lowest N in the range [0,
n) for which eq(x[N], y) is true. If successful, it returns x + N.
Otherwise, it returns a null pointer.
char_traits::int_type
typedef T1 int_type;
The type is (typically) an integer type T1 that describes an object
that can represent any element of the controlled sequence as well
as the value returned by eof(). It must be possible to type cast a
value of type E to int_type then back to E without altering the
file:///D|/97/c++_1/LIBREF.TXT (321 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 316 of 619
original value. In addition, the expression int_type('\0') must
yield the code that terminates a null-terminated string for
elements of type E. Also, the expression int_type('\n') must yield
a suitable newline character of type E.
char_traits::length
static size_t length(const E *x);
The static member function returns the number of elements N in the
sequence beginning at x up to but not including the element x[N]
that compares equal to E(0).
char_traits::lt
static bool lt(const E& x, const E& y);
The static member function returns true if x compares less than y.
char_traits::move
static E *move(E *x, const E *y, size_t n);
The static member function copies the sequence of n elements
beginning at y to the array beginning at x, and then returns x. The
source and destination may overlap.
char_traits::not_eof
static int_type not_eof(const int_type& ch);
If !eq_int_type( eof(), ch), the static member function returns ch.
Otherwise, it returns a value other than eof().
char_traits::off_type
typedef T3 off_type;
The type is a signed integer type T3 that describes an object that
can store a byte offset involved in various stream positioning
operations. It is typically a synonym for streamoff, but in any
case it has essentially the same properties as that type.
char_traits::pos_type
typedef T2 pos_type;
The type is an opaque type T2 that describes an object that can
store all the information needed to restore an arbitrary file-
position indicator within a stream. It is typically a synonym for
streampos, but in any case it has essentially the same properties
as that type.
char_traits::state_type
typedef T4 state_type;
file:///D|/97/c++_1/LIBREF.TXT (322 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 317 of 619
The type is an opaque type T4 that describes an object that can
represent a conversion state. It is typically a synonym for
mbstate_t, but in any case it has essentially the same properties
as that type.
char_traits::to_char_type
static E to_char_type(const int_type& ch);
The static member function returns ch, represented as type E. A
value of ch that cannot be so represented yields an unspecified
result.
char_traits::to_int_type
static int_type to_int_type(const E& c);
The static member function returns ch, represented as type
int_type. It should always be true that to_char_type(to_int_type(c)
== c for any value of c.
char_traits<char>
class char_traits<char>;
The class is an explicit specialization of template class
char_traits for elements of type char (so it can take advantage
library functions that manipulate objects of this type).
char_traits<wchar_t>
class char_traits<wchar_t>;
The class is an explicit specialization of template class
char_traits for elements of type wchar_t (so it can take advantage
of library functions that manipulate objects of this type).
getline
template<class E, class T, class A>
basic_istream<E, T>& getline(
basic_istream <E, T>& is,
basic_string<E, T, A>& str);
template<class E, class T, class A>
basic_istream<E, T>& getline(
basic_istream <E, T>& is,
basic_string<E, T, A>& str,
E delim);
The first template function returns getline(is, str, is.widen
('\n')).
The second template function replaces the sequence controlled by
str with a sequence of elements extracted from the stream is. In
order of testing, extraction stops:
file:///D|/97/c++_1/LIBREF.TXT (323 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 318 of 619
1.At end of file.
2.After the function extracts an element that compares equal to
delim, in which case the element is neither put back nor
appended to the controlled sequence.
3.After the function extracts is.max_size() elements, in which
case the function calls setstate(ios_base::failbit).
If the function extracts no elements, it calls setstate(failbit).
In any case, it returns *this.
See the related sample program.
operator+
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const basic_string<E, T, A>& lhs,
E rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
const E *lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
basic_string<E, T, A> operator+(
E lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator+ to concatenate two
objects of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).append(rhs).
See the related sample program.
operator!=
template<class E, class T, class A>
bool operator!=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator!=(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator!=(
const E *lhs,
const basic_string<E, T, A>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (324 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 319 of 619
Each template function overloads operator!= to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) != 0.
See the related sample program.
operator==
template<class E, class T, class A>
bool operator==(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator==(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator==(
const E *lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator== to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) == 0.
See the related sample program.
operator<
template<class E, class T, class A>
bool operator<(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator<(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator<(
const E *lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator< to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) < 0.
See the related sample program.
operator<<
template<class E, class T, class A>
basic_ostream<E, T>& operator<<(
basic_ostream <E, T>& os,
const basic_string<E, T, A>& str);
The template function overloads operator<< to insert an object str
file:///D|/97/c++_1/LIBREF.TXT (325 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 320 of 619
of template class basic_string into the stream os The function
effectively returns os.write( str.c_str(), str.size()).
See the related sample program.
operator<=
template<class E, class T, class A>
bool operator<=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator<=(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator<=(
const E *lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator<= to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) <= 0.
See the related sample program.
operator>
template<class E, class T, class A>
bool operator>(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>(
const basic_string<E, T, A>& lhs,
const E *rhs);
template<class E, class T, class A>
bool operator>(
const E *lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator> to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) > 0.
See the related sample program.
operator>=
template<class E, class T, class A>
bool operator>=(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
template<class E, class T, class A>
bool operator>=(
const basic_string<E, T, A>& lhs,
const E *rhs);
file:///D|/97/c++_1/LIBREF.TXT (326 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 321 of 619
template<class E, class T, class A>
bool operator>=(
const E *lhs,
const basic_string<E, T, A>& rhs);
Each template function overloads operator>= to compare two objects
of template class basic_string. All effectively return
basic_string<E, T, A>(lhs).compare(rhs) >= 0.
See the related sample program.
operator>>
template<class E, class T, class A>
basic_istream<E, T>& operator>>(
basic_istream <E, T>& is,
const basic_string<E, T, A>& str);
The template function overloads operator>> to replace the sequence
controlled by str with a sequence of elements extracted from the
stream is. Extraction stops:
lAt end of file.
lAfter the function extracts is.width() elements, if that value
is nonzero.
lAfter the function extracts is.max_size() elements.
lAfter the function extracts an element c for which use_facet<
ctype<E> >( getloc()). is( ctype<E>::space, c) is true, in
which case the character is put back.
If the function extracts no elements, it calls setstate
(ios_base::failbit). In any case, it calls width(0) and returns
*this.
See the related sample program.
string
typedef basic_string<char> string;
The type describes a specialization of template class basic_string
for elements of type
swap
template<class T, class A>
void swap(
const basic_string<E, T, A>& lhs,
const basic_string<E, T, A>& rhs);
The template function executes swap(lhs, rhs).
wstring
typedef basic_string<wchar_t> wstring;
The type describes a specialization of template class basic_string
file:///D|/97/c++_1/LIBREF.TXT (327 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 322 of 619
for elements of type wchar_t.
<strstream>
namespace std {
class strstreambuf;
class istrstream;
class ostrstream;
class strstream;
};
Include the iostreams standard header <strstream> to define several
classes that support iostreams operations on sequences stored in an
allocated array of char object. Such sequences are easily
to and from C strings.
strstreambuf
class strstreambuf : public streambuf {
public:
explicit strstreambuf(streamsize n = 0);
strstreambuf(void (*palloc)(size_t),
void (*pfree)(void *));
strstreambuf(char *gp, streamsize n,
char *pp = 0);
strstreambuf(signed char *gp, streamsize n,
signed char *pp = 0);
strstreambuf(unsigned char *gp, streamsize n,
unsigned char *pp = 0);
strstreambuf(const char *gp, streamsize n);
strstreambuf(const signed char *gp, streamsize n);
strstreambuf(const unsigned char *gp, streamsize n);
void freeze(bool frz = true) const;
char *str();
streamsize pcount();
protected:
virtual streampos seekoff(streamoff off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual streampos seekpos(streampos sp,
ios_base::openmode which = ios_base::in | ios_base::out);
virtual int underflow();
virtual int pbackfail(int c = EOF);
virtual int overflow(int c = EOF);
};
The class describes a stream buffer that controls the transmission
of elements to and from a sequence of elements stored in a char
object. Depending on how it is constructed, the object can be
allocated, extended, and freed as necessary to accommodate changes
in the sequence.
An object of class strstreambuf stores several bits of mode
information as its strstreambuf mode. These bits indicate whether
the controlled sequence:
lHas been allocated, and hence needs to be freed eventually.
lIs modifiable.
file:///D|/97/c++_1/LIBREF.TXT (328 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 323 of 619
lIs extendable by reallocating storage.
lHas been frozen and hence needs to be unfrozen before the
object is destroyed, or freed (if allocated) by an agency other
than the object.
A controlled sequence that is frozen cannot be modified or
extended, regardless of the state of these separate mode bits.
The object also stores pointers to two functions that control
strstreambuf allocation. If these are null pointers, the object
devises its own method of allocating and freeing storage for the
controlled sequence.
strstreambuf::freeze
void freeze(bool frz = true) const;
If frz is true, the function alters the stored strstreambuf mode to
make the controlled sequence frozen. Otherwise, it makes the
controlled sequence not frozen.
strstreambuf::pcount
streamsize pcount();
The member function returns a count of the number of elements
written to the controlled sequence. Specifically, if pptr() is a
null pointer, the function returns zero. Otherwise, it returns pptr
() - pbase().
strstreambuf::strstreambuf
explicit strstreambuf(streamsize n = 0);
strstreambuf(void (*palloc)(size_t),
void (*pfree)(void *));
strstreambuf(char *gp, streamsize n,
char *pp = 0);
strstreambuf(signed char *gp, streamsize n,
signed char *pp = 0);
strstreambuf(unsigned char *gp, streamsize n,
unsigned char *pp = 0);
strstreambuf(const char *gp, streamsize n);
strstreambuf(const signed char *gp, streamsize n);
strstreambuf(const unsigned char *gp, streamsize n);
The first constructor stores a null pointer in all the pointers
controlling the input buffer, the output buffer, and strstreambuf
allocation. It sets the stored strstreambuf mode to make the
controlled sequence modifiable and extendable.
The second constructor behaves much as the first, except that it
stores palloc as the pointer to the function to call to allocate
storage, and pfree as the pointer to the function to call to free
that storage.
The three constructors:
file:///D|/97/c++_1/LIBREF.TXT (329 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 324 of 619
strstreambuf(char *gp, streamsize n,
char *pp = 0);
strstreambuf(signed char *gp, streamsize n,
signed char *pp = 0);
strstreambuf(unsigned char *gp, streamsize n,
unsigned char *pp = 0);
also behave much as the first, except that gp designates the array
object used to hold the controlled sequence. (Therefore, it must
not be a null pointer.) The number of elements N in the array is
determined as follows:
lIf (n > 0), then N is n.
lIf (n == 0), then N is strlen((const char *)gp).
lIf (n < 0), then N is INT_MAX.
If pp is a null pointer, the function establishes just an input
buffer, by executing:
setg(gp, gp, gp + N);
Otherwise, it establishes both input and output buffers, by
executing:
setg(gp, gp, pp);
setp(pp, gp + N);
In this case, pp must be in the interval [gp, gp + N].
Finally, the three constructors:
strstreambuf(const char *gp, streamsize n);
strstreambuf(const signed char *gp, streamsize n);
strstreambuf(const unsigned char *gp, streamsize n);
all behave the same as:
streambuf((char *)gp, n);
except that the stored mode makes the controlled sequence neither
modifiable nor extendable.
strstreambuf::overflow
virtual int overflow(int c = EOF);
If c != EOF, the protected virtual member function endeavors to
insert the element (char)c into the output buffer. It can do so in
various ways:
lIf a write position is available, it can store the element into
the write position and increment the next pointer for the
output buffer.
lIf the stored strstreambuf mode says the controlled sequence is
modifiable, extendable, and not frozen, the function can make a
write position available by allocating new for the output
file:///D|/97/c++_1/LIBREF.TXT (330 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 325 of 619
buffer. (Extending the output buffer this way also extends any
associated input buffer.)
If the function cannot succeed, it returns EOF. Otherwise, if c ==
EOF it returns some value other than EOF. Otherwise, it returns c.
strstreambuf::pbackfail
virtual int pbackfail(int c = EOF);
The protected virtual member function endeavors to put back an
element into the input buffer, then make it the current element
(pointed to by the next pointer).
If c == EOF, the element to push back is effectively the one
already in the stream before the current element. Otherwise, that
element is replaced by x = (char)c. The function can put back an
element in various ways:
lIf a putback position is available, and the element stored
there compares equal to x, it can simply decrement the next
pointer for the input buffer.
lIf a putback position is available, and if the strstreambuf
mode says the controlled sequence is modifiable, the function
can store x into the putback position and decrement the next
pointer for the input buffer.
If the function cannot succeed, it returns EOF. Otherwise, if c ==
EOF it returns some value other than EOF. Otherwise, it returns c.
strstreambuf::seekoff
virtual streampos seekoff(streamoff off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class strstreambuf, a stream position consists purely of a stream
offset. Offset zero designates the first element of the controlled
sequence.
The new position is determined as follows:
lIf way == ios_base::beg, the new position is the beginning of
the stream plus off.
lIf way == ios_base::cur, the new position is the current stream
position plus off.
lIf way == ios_base::end, the new position is the end of the
stream plus off.
If which & ios_base::in is nonzero and the input buffer exists, the
function alters the next position to read in the input buffer. If
which & ios_base::out is also nonzero, way != ios_base::cur, and
the output buffer exists, the function also sets the next position
to write to match the next position to read.
Otherwise, if which & ios_base::out is nonzero and the output
file:///D|/97/c++_1/LIBREF.TXT (331 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 326 of 619
buffer exists, the function alters the next position to write in
the output buffer. Otherwise, the positioning operation fails. For
a positioning operation to succeed, the resulting stream position
must lie within the controlled sequence.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position. Otherwise, it fails and
returns an invalid stream position.
strstreambuf::seekpos
virtual streampos seekpos(streampos sp,
ios_base::openmode which = ios_base::in | ios_base::out);
The protected virtual member function endeavors to alter the
current positions for the controlled streams. For an object of
class strstreambuf, a stream position consists purely of a stream
offset. Offset zero designates the first element of the controlled
sequence. The new position is determined by sp.
If which & ios_base::in is nonzero and the input buffer exists, the
function alters the next position to read in the input buffer. (If
which & ios_base::out is nonzero and the output buffer exists, the
function also sets the next position to write to match the next
position to read.) Otherwise, if which & ios_base::out is nonzero
and the output buffer exists, the function alters the next position
to write in the output buffer. Otherwise, the positioning operation
fails. For a positioning operation to succeed, the resulting stream
position must lie within the controlled sequence.
If the function succeeds in altering the stream position(s), it
returns the resultant stream position. Otherwise, it fails and
returns an invalid stream position.
strstreambuf::str
char *str();
The member function calls freeze(), then returns a pointer to the
beginning of the controlled sequence. (Note that no terminating
null element exists, unless you insert one explicitly.)
strstreambuf::underflow
virtual int underflow();
The protected virtual member function endeavors to extract the
current element c from the input buffer, then advance the current
stream position, and return the element as (int)(unsigned char)c.
It can do so in only one way: If a read position is available, it
takes c as the element stored in the read position and advances the
next pointer for the input buffer.
If the function cannot succeed, it returns EOF. Otherwise, it
returns the current element in the input stream, converted as
described above.
file:///D|/97/c++_1/LIBREF.TXT (332 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 327 of 619
istrstream
class istrstream : public istream {
public:
explicit istrstream(const char *s);
explicit istrstream(char *s);
istrstream(const char *s, streamsize n);
istrstream(char *s, streamsize n);
strstreambuf *rdbuf() const;
char *str();
};
The class describes an object that controls extraction of elements
and encoded objects from a stream buffer of class strstreambuf. The
object stores an object of class strstreambuf.
istrstream::istrstream
explicit istrstream(const char *s);
explicit istrstream(char *s);
istrstream(const char *s, streamsize n);
istrstream(char *s, streamsize n);
All the constructors initialize the base class by calling istream
(sb), where sb is the stored object of class strstreambuf. The
first two constructors also initialize sb by calling strstreambuf
((const char *)s, 0). The remaining two constructors instead call
strstreambuf((const char *)s, n).
istrstream::rdbuf
strstreambuf *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to strstreambuf.
istrstream::str
char *str();
The member function returns rdbuf()-> str().
ostrstream
class ostrstream : public ostream {
public:
ostrstream();
ostrstream(char *s, streamsize n,
ios_base::openmode mode = ios_base::out);
strstreambuf *rdbuf() const;
void freeze(bool frz = true);
char *str();
streamsize pcount() const;
};
The class describes an object that controls insertion of elements
file:///D|/97/c++_1/LIBREF.TXT (333 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 328 of 619
and encoded objects into a stream buffer of class strstreambuf. The
object stores an object of class strstreambuf.
ostrstream::freeze
void freeze(bool frz = true)
The member function calls rdbuf()-> freeze(frz).
ostrstream::ostrstream
ostrstream();
ostrstream(char *s, streamsize n,
ios_base::openmode mode = ios_base::out);
Both constructors initialize the base class by calling ostream(sb),
where sb is the stored object of class strstreambuf. The first
constructor also initializes sb by calling strstreambuf(). The
second constructor initializes the base class one of two ways:
lIf mode & ios_base::app == 0, then s must designate the first
element of an array of n elements, and the constructor calls
strstreambuf(s, n, s).
lOtherwise, s must designate the first element of an array of n
elements that contains a C string whose first element is
designated by s, and the constructor calls strstreambuf(s, n, s
+ strlen(s).
ostrstream::pcount
streamsize pcount() const;
The member function returns rdbuf()-> pcount().
ostrstream::rdbuf
strstreambuf *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to strstreambuf.
ostrstream::str
char *str();
The member function returns rdbuf()-> str().
strstream
class strstream : public iostream {
public:
strstream();
strstream(char *s, streamsize n,
ios_base::openmode mode = ios_base::in | ios_base::out);
strstreambuf *rdbuf() const;
void freeze(bool frz = true);
char *str();
file:///D|/97/c++_1/LIBREF.TXT (334 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 329 of 619
streamsize pcount() const;
};
The class describes an object that controls insertion and
extraction of elements and encoded objects using a stream buffer of
class strstreambuf. The object stores an object of class
strstreambuf.
strstream::freeze
void freeze(bool frz = true)
The member function calls rdbuf()-> freeze(zfrz).
strstream::pcount
streamsize pcount() const;
The member function returns rdbuf()-> pcount().
strstream::strstream
strstream();
strstream(char *s, streamsize n,
ios_base::openmode mode = ios_base::in | ios_base::out);
Both constructors initialize the base class by calling streambuf
(sb), where sb is the stored object of class strstreambuf. The
first constructor also initializes sb by calling strstreambuf().
The second constructor initializes the base class one of two ways:
lIf mode & ios_base::app == 0, then s must designate the first
element of an array of n elements, and the constructor calls
strstreambuf(s, n, s).
lOtherwise, s must designate the first element of an array of n
elements that contains a C string whose first element is
designated by s, and the constructor calls strstreambuf(s, n, s
+ strlen(s).
strstream::rdbuf
strstreambuf *rdbuf() const
The member function returns the address of the stored stream
buffer, of type pointer to strstreambuf.
strstream::str
char *str();
The member function returns rdbuf()-> str().
<utility>
namespace std {
// TEMPLATE CLASSES
template<class T, class U>
file:///D|/97/c++_1/LIBREF.TXT (335 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 330 of 619
struct pair;
// TEMPLATE FUNCTIONS
template<class T, class U>
pair<T, U> make_pair(const T& x, const U& y);
template<class T, class U>
bool operator==(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator!=(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator<(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator>(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator<=(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator>=(const pair<T, U>& x, const pair<T, U>& y);
namespace rel_ops {
template<class T>
bool operator!=(const T& x, const T& y);
template<class T>
bool operator<=(const T& x, const T& y);
template<class T>
bool operator>(const T& x, const T& y);
template<class T>
bool operator>=(const T& x, const T& y);
};
};
Include the STL standard header <utility> to define several
templates of general use throughout the Standard Template Library.
Four template operators -- operator!=, operator<=, operator>, and
operator>= -- define a total ordering on pairs of operands of the
same type, given definitions of operator== and operator<.
If an implementation supports namespaces, these template operators
are defined in the rel_ops namespace, nested within the std
namespace. If you wish to use these template operators, write the
declaration:
using namespace std::rel_ops;
which promotes the template operators into the current namespace.
make_pair
template<class T, class U>
pair<T, U> make_pair(const T& x, const U& y);
The template function returns pair<T, U>(x, y).
See the related sample program.
operator!=
template<class T>
bool operator!=(const T& x, const T& y);
file:///D|/97/c++_1/LIBREF.TXT (336 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 331 of 619
template<class T, class U>
bool operator!=(const pair<T, U>& x, const pair<T, U>& y);
The template function returns !(x == y).
See the related sample program.
operator==
template<class T, class U>
bool operator==(const pair<T, U>& x, const pair<T, U>& y);
The template function returns x.first == y.first && x.second ==
y.second.
See the related sample program.
operator<
template<class T, class U>
bool operator<(const pair<T, U>& x, const pair<T, U>& y);
template<class T, class U>
bool operator<(const pair<T, U>& x, const pair<T, U>& y);
The template function returns x.first < y.first || !(y.first <
x.first && x.second < y.second.
See the related sample program.
operator<=
template<class T>
bool operator<=(const T& x, const T& y);
template<class T, class U>
bool operator<=(const pair<T, U>& x, const pair<T, U>& y);
The template function returns !(y < x).
See the related sample program.
operator>
template<class T>
bool operator>(const T& x, const T& y);
template<class T, class U>
bool operator>(const pair<T, U>& x, const pair<T, U>& y);
The template function returns y < x.
See the related sample program.
operator>=
template<class T>
bool operator>=(const T& x, const T& y);
template<class T, class U>
bool operator>=(const pair<T, U>& x, const pair<T, U>& y);
file:///D|/97/c++_1/LIBREF.TXT (337 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 332 of 619
The template function returns !(x < y).
See the related sample program.
pair
template<class T, class U>
struct pair {
typedef T first_type;
typedef U second_type
T first;
U second;
pair();
pair(const T& x, const U& y);
template<class V, class W>
pair(const pair<V, W>& pr);
};
The template class stores a pair of objects, first, of type T, and
second, of type U. The type definition first_type is the same as
the template parameter T, while second_type is the same as the
template parameter U.
The first (default) constructor initializes first to T() and second
to U(). The second constructor initializes first to x and second to
y. The third (template) constructor initializes first to pr.first
and second to pr.second. T and U each need supply only a single-
argument constructor and a destructor.
<valarray>
gslice . gslice_array .
indirect_array . mask_array . slice .
slice_array . valarray . valarray<bool>
abs . acos . asin . atan . atan2 . cos . cosh . exp . log . log10 .
max . min . operator!= . operator% . operator& . operator&& .
operator> . operator>> . operator>= . operator< . operator<< .
operator<= .
operator* . operator+ . operator- . operator/ .
operator== . operator^ . operator| . operator|| . pow . sin . sinh
. sqrt . tan . tanh
namespace std {
class slice;
class gslice;
// TEMPLATE CLASSES
template<class T>
class valarray;
template<class T>
class slice_array;
template<class T>
class gslice_array;
template<class T>
class mask_array;
template<class T>
class indirect_array;
// TEMPLATE FUNCTIONS
file:///D|/97/c++_1/LIBREF.TXT (338 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 333 of 619
template<class T>
valarray<T> operator*(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator*(const valarray<T> lhs,
const T& rhs);
template<class T>
valarray<T> operator*(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator/(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator/(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator/(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator%(const valarray<T>& lhs,
const vararray<T>& rhs);
template<class T>
valarray<T> operator%(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator%(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator+(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator+(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator+(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator-(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator-(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator-(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator^(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator^(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator^(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator&(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator&(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator&(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator|(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator|(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator|(const T& lhs, const valarray<T>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (339 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 334 of 619
template<class T>
valarray<T> operator<<(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator<<(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator<<(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<T> operator>>(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator>>(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator>>(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator&&(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator&&(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator&&(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<biil> operator||(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator||(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator||(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator==(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator==(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator==(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator!=(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator!=(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator!=(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator<(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator<(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator<(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator>=(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator>=(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator>=(const T& lhs, const valarray<T>& rhs);
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (340 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 335 of 619
valarray<bool> operator>(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator>(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator>(const T& lhs, const valarray<T>& rhs);
template<class T>
valarray<bool> operator<=(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator<=(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator<=(const T& lhs, const valarray<T>& rhs);
template<class T>
T max(const valarray<T>& x);
template<class T>
T min(const valarray<T>& x);
template<class T>
valarray<T> abs(const valarray<T>& x);
template<class T>
valarray<T> acos(const valarray<T>& x);
template<class T>
valarray<T> asin(const valarray<T>& x);
template<class T>
valarray<T> atan(const valarray<T>& x);
template<class T>
valarray<T> atan2(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<T> atan2(const valarray<T> x, const T& y);
template<class T>
valarray<T> atan2(const T& x, const valarray<T>& y);
template<class T>
valarray<T> cos(const valarray<T>& x);
template<class T>
valarray<T> cosh(const valarray<T>& x);
template<class T>
valarray<T> exp(const valarray<T>& x);
template<class T>
valarray<T> log(const valarray<T>& x);
template<class T>
valarray&ttT> log10(const valarray<T>& x);
template<class T>
valarray<T> pow(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<T> pow(const valarray<T> x, const T& y);
template<class T>
valarray<T> pow(const T& x, const valarray<T>& y);
template<class T>
valarray<T> sin(const valarray<T>& x);
template<class T>
valarray<T> sinh(const valarray<T>& x);
template<class T>
valarray<T> sqrt(const valarray<T>& x);
template<class T>
valarray<T> tan(const valarray<T>& x);
file:///D|/97/c++_1/LIBREF.TXT (341 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 336 of 619
template<class T>
valarray<T> tanh(const valarray<T>& x);
};
Include the standard header <valarray> to define the template class
valarray and numerous supporting template classes and functions.
These template classes and functions are permitted unusual
latitude, in the interest of improved performance. Specifically,
any function returning valarray<T> may return an object of some
other type T'. In that case, any function that accepts one or more
arguments of type valarray<T> must have overloads that accept
arbitrary combinations of those arguments, each replaced with an
argument of type T'. (Put simply, the only way you can detect such
a substitution is to go looking for it.)
abs
template<class T>
valarray<T> abs(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the absolute value of x[I].
See the related sample program.
acos
template<class T>
valarray<T> acos(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the arccosine of x[I].
See the related sample program.
asin
template<class T>
valarray<T> asin(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the arcsine of x[I].
See the related sample program.
atan
template<class T>
valarray<T> atan(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the arctangent of x[I].
See the related sample program.
atan2
file:///D|/97/c++_1/LIBREF.TXT (342 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 337 of 619
template<class T>
valarray<T> atan2(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<T> atan2(const valarray<T> x, const T& y);
template<class T>
valarray<T> atan2(const T& x, const valarray<T>& y);
The first template function returns an object of class valarray<T>,
each of whose elements I is the arctangent of x[I] / y[I]. The
second template function stores in element I the arctangent of x
[I] / y. The third template function stores in element I the
arctangent of x / y[I].
cos
template<class T>
valarray<T> cos(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the cosine of x[I].
See the related sample program.
cosh
template<class T>
valarray<T> cosh(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the hyperbolic cosine of x[I].
See the related sample program.
exp
template<class T>
valarray<T> exp(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the exponential of x[I].
See the related sample program.
gslice
class gslice {
public:
gslice();
gslice(size_t st,
const valarray<size_t> len, const valarray<size_t> str);
size_t start() const;
const valarray<size_t> size() const;
const valarray<size_t> stride() const;
};
file:///D|/97/c++_1/LIBREF.TXT (343 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 338 of 619
The class stores the parameters that characterize a gslice_array
when an object of class gslice appears as a subscript for an object
of class valarray<T>. The stored values include:
lA starting index
lA length vector of class valarray<size_t>
lA stride vector of class valarray<size_t>
The two vectors must have the same length.
gslice::gslice
gslice();
gslice(size_t st,
const valarray<size_t> len, const valarray<size_t> str);
The default constructor stores zero for the starting index, and
zero-length vectors for the length and stride vectors. The second
constructor stores st for the starting index, len for the length
vector, and str for the stride vector.
gslice::size
const valarray<size_t> size() const;
The member function returns the stored length vector.
gslice::start
size_t start() const;
The member function returns the stored starting index.
gslice::stride
const valarray<size_t> stride() const;
The member function returns the stored stride vector.
gslice_array
template<class T>
class gslice_array {
public:
typedef T value_type;
void operator=(const valarray<T> x) const;
void operator=(const T& x);
void operator*=(const valarray<T> x) const;
void operator/=(const valarray<T> x) const;
void operator%=(const valarray<T> x) const;
void operator+=(const valarray<T> x) const;
void operator-=(const valarray<T> x) const;
void operator^=(const valarray<T> x) const;
void operator&=(const valarray<T> x) const;
void operator|=(const valarray<T> x) const;
void operator<<=(const valarray<T> x) const;
file:///D|/97/c++_1/LIBREF.TXT (344 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 339 of 619
void operator>>=(const valarray<T> x) const;
void fill();
};
The class describes an object that stores a reference to an object
x of class valarray<T>, along with an object gs of class gslice,
which describes the sequence of elements to select from the
valarray<T> object.
You construct a gslice_array<T> object only by writing an
expression of the form x[gs]. The member functions of class
gslice_array then behave like the corresponding function signatures
defined for valarray<T>, except that only the sequence of selected
elements is affected.
The sequence is determined as follows. For a length vector gs.size
() of length N, construct the index vector valarray<size_t> idx(0,
N). This designates the initial element of the sequence, whose
index k within x is given by the mapping:
k = start;
for (size_t i = 0; i < gs.size()[i]; ++i)
k += idx[i] * gs.stride()[i];
The successor to an index vector value is given by:
for (size_t i = N; 0 < i--; )
if (++idx[i] < gs.size()[i])
break;
else
idx[i] = 0;
For example:
const size_t lv[] = {2, 3};
const size_t dv[] = {7, 2};
const valarray<size_t> len(lv, 2), str(dv, 2);
// x[gslice(3, len, str)] selects elements with indices
// 3, 5, 7, 10, 12, 14
indirect_array
template<class T>
class indirect_array {
public:
typedef T value_type;
void operator=(const valarray<T> x) const;
void operator=(const T& x);
void operator*=(const valarray<T> x) const;
void operator/=(const valarray<T> x) const;
void operator%=(const valarray<T> x) const;
void operator+=(const valarray<T> x) const;
void operator-=(const valarray<T> x) const;
void operator^=(const valarray<T> x) const;
void operator&=(const valarray<T> x) const;
void operator|=(const valarray<T> x) const;
void operator<<=(const valarray<T> x) const;
file:///D|/97/c++_1/LIBREF.TXT (345 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 340 of 619
void operator>>=(const valarray<T> x) const;
void fill();
};
The class describes an object that stores a reference to an object
x of class valarray<T>, along with an object xa of class
valarray<size_t>, which describes the sequence of elements to
select from the valarray<T> object.
You construct an indirect_array<T> object only by writing an
expression of the form x[xa]. The member functions of class
indirect_array then behave like the corresponding function
signatures defined for valarray<T>, except that only the sequence
of selected elements is affected.
The sequence consists of xa.size() elements, where element i
becomes the index xa[i] within x. For example:
const size_t vi[] = {7, 5, 2, 3, 8};
// x[valarray<size_t>(vi, 5)] selects elements with indices
// 7, 5, 2, 3, 8
log
template<class T>
valarray<T> log(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the natural logarithm of x[I].
See the related sample program.
log10
template<class T>
valarray<T> log10(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the base-10 logarithm of x[I].
See the related sample program.
mask_array
template<class T>
class mask_array {
public:
typedef T value_type;
void operator=(const valarray<T> x) const;
void operator=(const T& x);
void operator*=(const valarray<T> x) const;
void operator/=(const valarray<T> x) const;
void operator%=(const valarray<T> x) const;
void operator+=(const valarray<T> x) const;
void operator-=(const valarray<T> x) const;
void operator^=(const valarray<T> x) const;
void operator&=(const valarray<T> x) const;
file:///D|/97/c++_1/LIBREF.TXT (346 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 341 of 619
void operator|=(const valarray<T> x) const;
void operator<<=(const valarray<T> x) const;
void operator>>=(const valarray<T> x) const;
void fill();
};
The class describes an object that stores a reference to an object
x of class valarray<T>, along with an object ba of class
valarray<bool> which describes the sequence of elements to select
from the valarray<T> object.
You construct a mask_array<T> object only by writing an expression
of the form x[xa]. The member functions of class mask_array then
behave like the corresponding function signatures defined for
valarray<T>, except that only the sequence of selected elements is
affected.
The sequence consists of, at most, ba.size() elements. An element j
is included only if ba[j] is true. Thus, there are as many elements
in the sequence as there are true elements in ba. If i is the index
of the lowest true element in ba, then x[i] is element zero in the
selected sequence. For example:
const bool vb[] = {false, false, true, true, false, true};
// x[valarray<bool>(vb, 56] selects eleeents with indices
// 2, 3, 5
max
template<class T>
T max(const valarray<T>& x);
The template function returns the value of the largest element of
x, by applying operator< between pairs of elements of class T.
Microsoft-Specific:
To avoid conflicts with min and max in WINDEF.H, use _MIN and _MAX
instead. These macros evaluate to _cpp_min and _cpp_max,
respectively.
END Microsoft-Specific
min
template<class T>
T min(const valarray<T>& x);
The template function returns the value of the smallest element of
x, by applying operator< between pairs of elements of class T.
Microsoft-Specific:
To avoid conflicts with min and max in WINDEF.H, use _MIN and _MAX
instead. These macros evaluate to _cpp_min and _cpp_max,
respectively.
END Microsoft-Specific
operator!=
file:///D|/97/c++_1/LIBREF.TXT (347 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 342 of 619
template<class T>
valarray<bool> operator!=(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator!=(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator!=(const T& x, const valarray<T>& y);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] != y[I]. The
second template operator stores in element I x[I] != y. The third
template operator stores in element I x != y[I].
operator%
template<class T>
valarray<T> operator%(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator%(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator%(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] % y[I]. The second template
operator stores in element I x[I] % y. The third template operator
stores in element I x % y[I].
operator&
template<class T>
valarray<T> operator&(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator&(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator&(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] & y[I]. The second template
operator stores in element I x[I] & y. The third template operator
stores in element I x & y[I].
operator&&
template<class T>
valarray<bool> operator&&(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator&&(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator&&(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] && y[I]. The
second template operator stores in element I x[I] && y. The third
file:///D|/97/c++_1/LIBREF.TXT (348 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 343 of 619
template operator stores in element I x && y[I].
operator>
template<class T>
valarray<bool> operator>(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator>(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator>(const T& x, const valarray<T>& y);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] > y[I]. The second
template operator stores in element I x[I] > y. The third template
operator stores in element I x > y[I].
operator>>
template<class T>
valarray<T> operator>>(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator>>(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator>>(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] >> y[I]. The second template
operator stores in element I x[I] >> y. The third template operator
stores in element I x >> y[I].
operator>=
template<class T>
valarray<bool> operator>=(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator>=(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator>=(const T& x, const valarray<T>& y);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] >= y[I]. The
second template operator stores in element I x[I] >= y. The third
template operator stores in element I x >= y[I].
operator<
template<class T>
valarray<bool> operator<(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator<(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator<(const T& x, const valarray<T>& y);
file:///D|/97/c++_1/LIBREF.TXT (349 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 344 of 619
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] < y[I]. The second
template operator stores in element I x[I] < y. The third template
operator stores in element I x < y[I].
operator<<
template<class T>
valarray<T> operator<<(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator<<(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator<<(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] << y[I]. The second template
operator stores in element I x[I] << y. The third template operator
stores in element I x << y[I].
operator<=
template<class T>
valarray<bool> operator<=(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator<=(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator<=(const T& x, const valarray<T>& y);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] <= y[I]. The
second template operator stores in element I x[I] <= y. The third
template operator stores in element I x <= y[I].
operator*
template<class T>
valarray<T> operator*(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator*(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator*(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] * y[I]. The second template
operator stores in element I x[I] * y. The third template operator
stores in element I x * y[I].
operator+
template<class T>
valarray<T> operator+(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (350 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 345 of 619
valarray<T> operator+(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator+(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] + y[I]. The second template
operator stores in element I x[I] + y. The third template operator
stores in element I x + y[I].
operator-
template<class T>
valarray<T> operator-(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator-(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator-(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] - y[I]. The second template
operator stores in element I x[I] - y. The third template operator
stores in element I x - y[I].
operator/
template<class T>
valarray<T> operator/(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator/(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator/(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] / y[I]. The second template
operator stores in element I x[I] / y. The third template operator
stores in element I x / y[I].
operator==
template<class T>
valarray<bool> operator==(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<bool> operator==(const valarray<T> x, const T& y);
template<class T>
valarray<bool> operator==(const T& x const valarray<T>& y);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] == y[I]. The
second template operator stores in element I x[I] == y. The third
template operator stores in element I x == y[I].
operator^
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (351 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 346 of 619
valarray<T> operator^(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator^(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator^(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] ^ y[I]. The second template
operator stores in element I x[I] ^ y. The third template operator
stores in element I x ^ y[I].
operator|
template<class T>
valarray<T> operator|(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<T> operator|(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<T> operator|(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class valarray<T>,
each of whose elements I is x[I] | y[I]. The second template
operator stores in element I x[I] | y. The third template operator
stores in element I x | y[I].
operator||
template<class T>
valarray<bool> operator||(const valarray<T>& lhs,
const valarray<T>& rhs);
template<class T>
valarray<bool> operator||(const valarray<T> lhs, const T& rhs);
template<class T>
valarray<bool> operator||(const T& lhs, const valarray<T>& rhs);
The first template operator returns an object of class
valarray<bool>, each of whose elements I is x[I] || y[I]. The
second template operator stores in element I x[I] || y. The third
template operator stores in element I x || y[I].
pow
template<class T>
valarray<T> pow(const valarray<T>& x,
const valarray<T>& y);
template<class T>
valarray<T> pow(const valarray<T> x, const T& y);
template<class T>
valarray<T> pow(const T& x, const valarray<T>& y);
The first template function returns an object of class valarray<T>,
each of whose elements I is x[I] raised to the y[I] power. The
second template function stores in element I x[I] raised to the y
power. The third template function stores in element I x raised to
the y[I] power.
file:///D|/97/c++_1/LIBREF.TXT (352 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 347 of 619
See the related sample program.
sin
template<class T>
valarray<T> sin(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the sine of x[I].
See the related sample program.
sinh
template<class T>
valarray<T> sinh(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the hyperbolic sine of x[I].
See the related sample program.
slice
class slice {
public:
slice();
slice(size_t st, size_t len, size_t str);
size_t start() const;
size_t size() const;
size_t stride() const;
};
The class stores the parameters that characterize a slice_array
when an object of class slice appears as a subscript for an object
of class valarray<T>. The stored values include:
lA starting index
lA total length
lA stride, or distance between subsequent indices
slice::size
size_t size() const;
The member function returns the stored total length.
slice::start
size_t start() const;
The member function returns the stored starting index.
slice::slice
slice();
file:///D|/97/c++_1/LIBREF.TXT (353 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 348 of 619
slice(size_t st,
const valarray<size_t> len, const valarray<size_t> str);
The default constructor stores zeros for the starting index, total
length, and stride. The second constructor stores st for the
starting index, len for the total length, and str for the stride.
slice::stride
size_t stride() const;
The member function returns the stored stride.
slice_array
template<class T>
class slice_array {
public:
typedef T value_type;
void operator=(const valarray<T> x) const;
void operator=(const T& x);
void operator*=(const valarray<T> x) const;
void operator/=(const valarray<T> x) const;
void operator%=(const valarray<T> x) const;
void operator+=(const valarray<T> x) const;
void operator-=(const valarray<T> x) const;
void operator^=(const valarray<T> x) const;
void operator&=(const valarray<T> x) const;
void operator|=(const valarray<T> x) const;
void operator<<=(const valarray<T> x) const;
void operator>>=(const valarray<T> x) const;
void fill();
};
The class describes an object that stores a reference to an object
x of class valarray<T>, along with an object sl of class slice
which describes the sequence of elements to select from the
valarray<T> object.
You construct a slice_array<T> object only by writing an expression
of the form x[sl]. The member functions of class slice_array then
behave like the corresponding function signatures defined for
valarray<T>, except that only the sequence of selected elements is
affected.
The sequence consists of sl.size() elements, where element i
becomes the index sl.start() + i * sl.stride() within x. For
example:
// x[slice(2, 5, 3)] selects elements with indices
// 2, 5, 8, 11, 14
sqrt
template<class T>
valarray<T> sqrt(const valarray<T>& x);
file:///D|/97/c++_1/LIBREF.TXT (354 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 349 of 619
The template function returns an object of class valarray<T>, each
of whose elements I is the square root of x[I].
See the related sample program.
tan
template<class T>
valarray<T> tan(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the tangent of x[I].
See the related sample program.
tanh
template<class T>
valarray<T> tanh(const valarray<T>& x);
The template function returns an object of class valarray<T>, each
of whose elements I is the hyperbolic tangent of x[I].
See the related sample program.
valarray
apply . cshift . fill . free . max< /b> . min . operator T * .
operator! . operator%= .
operator&= . operator>>= . operator<<= .
operato r*= . operator+ . operator+= . operator- . operator-= .
operator/= . operator= . operator[] . operator^= . operator|= .
operator~ . resize . shift . size . sum . valarray . value_type
template<class T>
class valarray {
public:
typedef T value_type;
valarray();
explicit valarray(size_t n);
valarray(const T& val, size_t n));
valarray(const T *p, size_t n);
valarray(const slice_array<T>& sa);
valarray(const gslice_array<T>& ga);
valarray(const mask_array<T>& ma);
valarray(const indirect_array<T>& ia);
valarray<T>& operator=(const valarray<T>& va);
valarray<T>& operator=(const T& x);
valarray<T>& operator=(const slice_array<T>& sa);
valarray<T>& operator=(const gslice_array<T>& ga);
valarray<T>& operator=(const mask_array<T>& ma);
valarray<T>& operator=(const indirect_array<T>& ia);
T operator[](size_t n) const;
T& operator[](size_t n);
valarray<T> operator[](slice sa) const;
slice_array<T> operator[](slice sa);
valarray<T> operator[](const gslice& ga) const;
file:///D|/97/c++_1/LIBREF.TXT (355 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 350 of 619
gslice_array<T> operator[](const gslice& ga);
valarray<T> operator[](const valarray<bool>& ba) const;
mask_array<T> operator[](const valarray<bool>& ba);
valarray<T> operator[](const valarray<size_t>& xa) const;
indirect_array<T> operator[](const valarray<size_t>& xa);
valarray<T> operator+();
valarray<T> operator-();
valarray<T> operator~();
valarray<bool> operator!();
valarray<T>& operator*=(const valarray<T>& x);
valarray<T>& operator*=(const T& x);
valarray<T>& operator/=(const valarray<T>& x);
valarray<T>& operator/=(const T& x);
valarray<T>& operator%=(const valarray<T>& x);
valarray<T>& operator%=(const T& x);
valarray<T>& operator+=(const valarray<T>& x);
valarray<T>& operator+=(const T& x);
valarray<T>& operator-=(const valarray<T>& x);
valarray<T>& operator-=(const T& x);
valarray<T>& operator^=(const valarray<T>& x);
valarray<T>& operator^=(const T& x);
valarray<T>& operator&=(const valarray<T>& x);
valarray<T>& operator&=(const T& x);
valarray<T>& operator|=(const valarray<T>& x);
valarray<T>& operator|=(const T& x);
valarray<T>& operator<<=(const valarray<T>& x);
valarray<T>& operator<<=(const T& x);
valarray<T>& operator>>=(const valarray<T>& x);
valarray<T>& operator>>=(const T& x);
size_t size() const;
T sum() const;
T max() const;
T min() const;
valarray<T> shift(int n) const;
valarray<T> cshift(int n) const;
valarray<T> apply(T fn(T)) const;
valarray<T> apply(T fn(const T&)) const;
void fill(const T& val);
void free();
void resize(size_t n, const T& c = T());
};
The template class describes an object that controls a varying-
length sequence of elements of type T. The sequence is stored as an
array of T. It differs from template class vector in two important
ways:
lIt defines numerous arithmetic operations between corresponding
elements of valarray<T> objects of the same type and length,
such as x = cos(y) + sin(z).
lIt defines a variety of interesting ways to subscript a
valarray<T> object, by overloading operator[].
valarray::apply
valarray<T> apply(T fn(T)) const;
valarray<T> apply(T fn(const T&)) const;
file:///D|/97/c++_1/LIBREF.TXT (356 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 351 of 619
The member function returns an object of class valarray<T>, of
length size(), each of whose elements I is fn((*this)[I]).
valarray::cshift
valarray<T> cshift(int n) const;
The member function returns an object of class valarray<T>, of
length size(), each of whose elements I is (*this)[(I + n) % size
()]. Thus, if element zero is taken as the leftmost element, a
positive value of n shifts the elements circularly left n places.
valarray::fill
void fill(const T& val);
The member function stores val in every element of *this.
valarray::free
void free();
The member function destroys all elements of *this, leaving an
array of zero length.
valarray::max
T max() const;
The member function returns the value of the largest element of
*this, which must have nonzero length. If the length is greater
than one, it compares values by applying operator< between pairs of
corresponding elements of class T.
valarray::min
T min() const;
The member function returns the value of the smallest element of
*this, which must have nonzero length. If the length is greater
than one, it compares values by applying operator< between pairs of
elements of class T.
valarray::operator!
valarray<bool> operator!();
The member operator returns an object of class valarray<bool>, of
length size(), each of whose elements I is !(*this).
valarray::operator%=
valarray<T>& operator%=(const valarray<T>& x);
valarray<T>& operator%=(const T& x);
The member operator replaces each element I of *this with (*this)
file:///D|/97/c++_1/LIBREF.TXT (357 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 352 of 619
[I] % x[I]. It returns *this.
valarray::operator&=
valarray<T>& operator&=(const valarray<T>& x);
valarray<T>& operator&=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] & x[I]. It returns *this.
valarray::operator>>=
valarray<T>& operator>>=(const valarray<T>& x);
valarray<T>& operator>>=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] >> x[I]. It returns *this.
valarray::operator<<=
valarray<T>& operator<<=(const valarray<T>& x);
valarray<T>& operator<<=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] << x[I]. It returns *this.
valarray::operator*=
valarray<T>& operator*=(const valarray<T>& x);
valarray<T>& operator*=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] * x[I]. It returns *this.
valarray::operator+
valarray<T> operator+();
The member operator returns an object of class valarray<T>, of
length size(), each of whose elements I is (*this)[I].
valarray::operator+=
valarray<T>& operator+=(const valarray<T>& x);
valarray<T>& operator+=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] + x[I]. It returns *this.
valarray::operator-
valarray<T> operator-();
The member operator returns an object of class valarray<T>, of
length size(), each of whose elements I is -(*this)[I].
valarray::operator-=
file:///D|/97/c++_1/LIBREF.TXT (358 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 353 of 619
valarray<T>& operator-=(const valarray<T>& x);
valarray<T>& operator-=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] - x[I]. It returns *this.
valarray::operator/=
valarray<T>& operator/=(const valarray<T>& x);
valarray<T>& operator/=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] / x[I]. It returns *this.
valarray::operator=
valarray<T>& operator=(const valarray<T>& va);
valarray<T>& operator=(const T& x);
valarray<T>& operator=(const slice_array<T>& sa);
valarray<T>& operator=(const gslice_array<T>& ga);
valarray<T>& operator=(const mask_array<T>& ma);
valarray<T>& operator=(const indirect_array<T>& ia);
The first member operator replaces the controlled sequence with a
copy of the sequence controlled by va. The second member operator
replaces each element of the controlled sequence with a copy of x.
The remaining member operators replace those elements of the
controlled sequence selected by their arguments, which are
generated only by operator[]. If the value of a member in the
replacement controlled sequence depends on a member in the initial
controlled sequence, the result is undefined.
If the length of the controlled sequence changes, the result is
generally undefined. In this implementation, however, the effect is
merely to invalidate any pointers or references to elements in the
controlled sequence.
valarray::operator[]
T& operator[](size_t n);
slice_array<T> operator[](slice sa);
gslice_array<T> operator[](const gslice& ga);
mask_array<T> operator[](const valarray<bool>& ba);
indirect_array<T> operator[](const valarray<size_t>& xa);
T operator[](size_t n) const;
valarray<T> operator[](slice sa) const;
valarray<T> operator[](const gslice& ga) const;
valarray<T> operator[](const valarray<bool>& ba) const;
valarray<T> operator[](const valarray<size_t>& xa) const;
The member operator is overloaded to provide several ways to select
sequences of elements from among those controlled by *this. The
first group of five member operators works in conjunction with
various overloads of operator= (and other assigning operators) to
allow selective replacement (slicing) of the controlled sequence.
file:///D|/97/c++_1/LIBREF.TXT (359 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 354 of 619
The selected elements must exist.
The first member operator selects element n. For example:
valarray<char> v0("abcdefghijklmnop", 16);
v0[3] = 'A';
// v0 == valarray<char>("abcAefghijklmnop", 16)
The second member operator selects those elements of the controlled
sequence designated by sa. For example:
valarray<char> v0("abcdefghijklmnop", 16);
valarray<char> v1("ABCDE", 5);
v0[slice(2, 5, 3)] = v1;
// v0 == valarray<char>("abAdeBghCjkDmnEp", 16)
The third member operator selects those elements of the controlled
sequence designated by ga. For example:
valarray<char> v0("abcdefghijklmnop", 16);
valarray<char> v1("ABCDEF", 6);
const size_t lv[] = {2, 3};
const size_t dv[] = {7, 2};
const valarray<size_t> len(lv, 2), str(dv, 2);
v0[gslice(3, len, str)] = v1;
// v0 == valarray<char>("abcAeBgCijDlEnFp", 16)
The fourth member operator selects those elements of the controlled
sequence designated by ma. For example:
valarray<char> v0("abcdefghijklmnop", 16);
valarray<char> v1("ABC", 3);
const bool vb[] = {false, false, true, true, false, true};
v0[valarray<bool>(vb, 6)] = v1;
// v0 == valarray<char>("abABeCghijklmnop", 16)
The fifth member operator selects those elements of the controlled
sequence designated by ia. For example:
valarray<char> v0("abcdefghijklmnop", 16);
valarray<char> v1("ABCDE", 5);
const size_t vi[] = {7, 5, 2, 3, 8};
v0[valarray<size_t>(vi, 5)] = v1;
// v0 == valarray<char>("abCDeBgAEjklmnop", 16)
In the second group, each of the five member operators constructs
an object that represents the value(s) selected. The selected
elements must exist.
The sixth member operator returns the value of element n. For
example:
valarray<char> v0("abcdefghijklmnop", 16);
// v0[3] returns 'd'
The seventh member operator returns an object of class valarray<T>
containing those elements of the controlled sequence designated by
file:///D|/97/c++_1/LIBREF.TXT (360 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 355 of 619
sa. For example:
valarray<char> v0("abcdefghijklmnop", 16);
// v0[slice(2, 5, 3)] returns valarray<char>("cfilo", 5)
The eighth member operator selects those elements of the controlled
sequence designated by ga. For example:
valarray<char> v0("abcdefghijklmnop", 16);
const size_t lv[] = {2, 3};
const size_t dv[] = {7, 2};
const valarray<size_t> len(lv, 2), str(dv, 2);
// v0[gslice(3, len, str)] returns valarray<char>("dfhkmo", 6)
The ninth member operator selects those elements of the controlled
sequence designated by ma. For example:
valarray<char> v0("abcdefghijklmnop", 16);
const bool vb[] = {false, false, true, true, false, true};
// v0[valarray<bool>(vb, 6)] returns valarray<char>("cdf", 3)
The last member operator selects those elements of the controlled
sequence designated by ia. For example:
valarray<char> v0("abcdefghijklmnop", 16);
const size_t vi[] = {7, 5, 2, 3, 8};
// v0[valarray<size_t>(vi, 5)] returns valarray<char>("hfcdi", 3)
valarray::operator^=
valarray<T>& operator^=(const valarray<T>& x);
valarray<T>& operator^=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] ^ x[I]. It returns *this.
valarray::operator|=
valarray<T>& operator|=(const valarray<T>& x);
valarray<T>& operator|=(const T& x);
The member operator replaces each element I of *this with (*this)
[I] | x[I]. It returns *this.
valarray::operator~
valarray<T> operator~();
The member operator returns an object of class valarray<T>, of
length size(), each of whose elements I is ~(*this)[I].
valarray::resize
void resize(size_t n, const T& c = T());
The member function ensures that size() henceforth returns n. If it
must lengthen the controlled sequence, it appends elements with
file:///D|/97/c++_1/LIBREF.TXT (361 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 356 of 619
value c. Any pointers or references to elements in the controlled
sequence are invalidated.
valarray::shift
valarray<T> shift(int n) const;
The member function returns an object of class valarray<T>, of
length size(), each of whose elements I is either (*this)[I + n],
if I + n is a valid subscript, or T(). Thus, if element zero is
taken as the leftmost element, a positive value of n shifts the
elements left n places, with zero fill.
valarray::size
size_t size() const;
The member function returns the number of elements in the array.
valarray::sum
T sum() const;
The member function returns the sum of all elements of *this, which
must have nonzero length. If the length is greater than one, it
adds values to the sum by applying operator+= between pairs of
elements of class T.
valarray::valarray
valarray();
explicit valarray(size_t n);
valarray(const T& val, size_t n));
valarray(const T *p, size_t n);
valarray(const slice_array<T>& sa);
valarray(const gslice_array<T>& ga);
valarray(const mask_array<T>& ma);
valarray(const indirect_array<T>& ia);
The first (default) constructor initializes the object to an empty
array. Each of the next three constructors initializes the object
to an array of n elements as follows:
lFor explicit valarray(size_t n), each element is initialized
with the default constructor.
lFor valarray(const T& val, size_t n)), each element is
initialized with val.
lFor valarray(const T *p, size_t n), the element at position I
is initialized with p[I].
Each of the remaining constructors initializes the object to a
valarray<T> object determined by the argument.
valarray::value_type
typedef T value_type;
file:///D|/97/c++_1/LIBREF.TXT (362 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 357 of 619
The type is a synonym for the template parameter T.
valarray<bool>
class valarray<bool>
The type is a specialization of template class valarray, for
elements of type bool.
<vector>
namespace std {
template<class T, class A>
class vector;
template<class A>
class vector<bool, A>;
// TEMPLATE FUNCTIONS
template<class T, class A>
bool operator==(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
bool operator!=(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
bool operator<(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
bool operator>(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
bool operator<=(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
bool operator>=(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
template<class T, class A>
void swap(
const vector<T, A>& lhs,
const vector<T, A>& rhs);
};
Include the STL standard header <vector> to define the container
template class vector and three supporting templates.
operator!=
template<class T, class A>
bool operator!=(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
file:///D|/97/c++_1/LIBREF.TXT (363 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 358 of 619
The template function returns !(lhs == rhs).
operator==
template<class T, class A>
bool operator==(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function overloads operator== to compare two objects
of template class vector. The function returns lhs.size() ==
rhs.size() && equal(lhs. begin(), lhs. end(), rhs.begin()).
See the related sample program.
operator<
template<class T, class A>
bool operator<(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function overloads operator< to compare two objects of
template class vector. The function returns lexicographical_compare
(lhs. begin(), lhs. end(), rhs.begin(), rhs.end()).
See the related sample program.
operator<=
template<class T, class A>
bool operator<=(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function returns !(rhs < lhs).
operator>
template<class T, class A>
bool operator>(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function returns rhs < lhs.
operator>=
template<class T, class A>
bool operator>=(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function returns !(lhs < rhs).
swap
file:///D|/97/c++_1/LIBREF.TXT (364 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 359 of 619
template<class T, class A>
void swap(
const vector <T, A>& lhs,
const vector <T, A>& rhs);
The template function executes lhs.swap(rhs).
vector
allocator_type . assign . at . back . begin . capacity . clear .
const_iterator . const_reference . const_reverse_iterator .
difference_type .
empty . end . erase . front . get_allocator .
insert . iterator . max_size . operator[] . pop_back . push_back .
rbegin . reference . rend . reserve . resize . reverse_iterator .
size .
size_type . swap . value_type . vector
template<class T, class A = allocator<T> >
class vector {
public:
typedef A allocator_type;
typedef A::size_type size_type;
typedef A::difference_type difference_type;
typedef A::reference reference;
typedef A::const_reference const_reference;
typedef A::value_type value_type;
typedef T0 iterator;
typedef T1 const_iterator;
typedef reverse_iterator<iterator, value_type,
reference, A::pointer, difference_type>
reverse_iterator;
typedef reverse_iterator<const_iterator, value_type,
const_reference, A::const_pointer, difference_type>
const_reverse_iterator;
explicit vector(const A& al = A());
explicit vector(size_type n, const T& v = T(), const A& al = A()
vector(const vector& x);
vector(const_iterator first, const_iterator last,
const A& al = A());
void reserve(size_type n);
size_type capacity() const;
iterator begin();
const_iterator begin() const;
iterator end();
iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
void resize(size_type n, T x = T());
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
reference at(size_type pos);
const_reference at(size_type pos) const;
reference operator[](size_type pos);
file:///D|/97/c++_1/LIBREF.TXT (365 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 360 of 619
const_reference operator[](size_type pos);
reference front();
const_reference front() const;
reference back();
const_reference back() const;
void push_back(const T& x);
void pop_back();
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it,
const_iterator first, const_iterator last);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
void swap(vector x);
protected:
A allocator;
};
The template class describes an object that controls a varying-
length sequence of elements of type T. The sequence is stored as an
array of T.
The object allocates and frees storage for the sequence it controls
through a protected object named allocator, of class A. Such an
allocator object must have the same external interface as an object
of template class allocator. Note that allocator is not copied when
the object is assigned.
Vector reallocation occurs when a member function must grow the
controlled sequence beyond its current storage capacity. Other
insertions and erasures may alter various storage addresses within
the sequence. In all such cases, iterators or references that point
at altered portions of the controlled sequence become invalid.
vector::allocator_type
typedef A allocator_type;
The type is a synonym for the template parameter A.
vector::assign
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
The first member function replaces the sequence controlled by *this
with the sequence [first, last). The second member function
replaces the sequence controlled by *this with a repetition of n
elements of value x.
In this implementation, if a translator does not support member
template functions, the templates:
template<class InIt>
file:///D|/97/c++_1/LIBREF.TXT (366 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 361 of 619
void assign(InIt first, InIt last);
template<class Size, class T2>
void assign(Size n, const T2& x = T2());
are replaced by:
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
vector::at
const_reference at(size_type pos) const;
reference at(size_type pos);
The member function returns a reference to the element of the
controlled sequence at position pos. If that position is invalid,
the function throws an object of class out_of_range.
vector::back
reference back();
const_reference back() const;
The member function returns a reference to the last element of the
controlled sequence, which must be non-empty.
See the related sample program.
vector::begin
const_iterator begin() const;
iterator begin();
The member function returns a random-access iterator that points at
the first element of the sequence (or just beyond the end of an
empty sequence).
vector::capacity
size_type capacity() const;
The member function returns the storage currently allocated to hold
the controlled sequence, a value at least as large as size().
See the related sample program.
vector::clear
void clear() const;
The member function calls erase( begin(), end()).
vector::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant random-
file:///D|/97/c++_1/LIBREF.TXT (367 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 362 of 619
access iterator for the controlled sequence. It is described here
as a synonym for the unspecified type T1.
vector::const_reference
typedef A::const_reference const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence.
vector::const_reverse_iterator
typedef reverse_iterator<const_iterator, value_type,
const_reference, A::const_pointer, difference_type>
const_reverse_iterator;
The type describes an object that can serve as a constant reverse
iterator for the controlled sequence.
vector::difference_type
typedef A::difference_type difference_type;
The signed integer type describes an object that can represent the
difference between the addresses of any two elements in the
controlled sequence.
vector::empty
bool empty() const;
The member function returns true for an empty controlled sequence.
See the related sample program.
vector::end
const_iterator end() const;
iterator end();
The member function returns a random-access iterator that points
just beyond the end of the sequence.
vector::erase
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
The first member function removes the element of the controlled
sequence pointed to by it. The second member function removes the
elements of the controlled sequence in the range [first, last).
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
Erasing N elements causes N destructor calls and an assignment for
each of the elements between the insertion point and the end of the
sequence. No reallocation occurs, so iterators and references
file:///D|/97/c++_1/LIBREF.TXT (368 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 363 of 619
become invalid only from the first element erased through the end
of the sequence.
See the related sample program.
vector::front
reference front();
const_reference front() const;
The member function returns a reference to the first element of the
controlled sequence, which must be non-empty.
See the related sample program.
vector::get_allocator
A get_allocator() const;
The member function returns allocator.
vector::insert
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it,
const_iterator first, const_iterator last);
Each of the member functions inserts, before the element pointed to
by it in the controlled sequence, a sequence specified by the
remaining operands. The first member function inserts a single
element with value x and returns an iterator that points to the
newly inserted element. The second member function inserts a
repetition of n elements of value x. The last member function
inserts the sequence [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
void insert(iterator it, InIt first, InIt last);
is replaced by:
void insert(iterator it,
const_iterator first, const_iterator last);
When inserting a single element, the number of element copies is
linear in the number of elements between the insertion point and
the end of the sequence. When inserting a single element at the end
of the sequence, the amortized number of element copies is
constant. When inserting N elements, the number of element copies
is linear in N plus the number of elements between the insertion
point and the end of the sequence -- except when the template
member is specialized for InIt, an input iterator which behaves
like N single insertions.
file:///D|/97/c++_1/LIBREF.TXT (369 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 364 of 619
If reallocation occurs, the size of the controlled sequence at
least doubles, and all iterators and references become invalid. If
no reallocation occurs, iterators become invalid only from the
point of insertion through the end of the sequence.
vector::iterator
typedef T0 iterator;
The type describes an object that can serve as a random-access
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
vector::max_size
size_type max_size() const;
The member function returns the length of the longest sequence that
the object can control.
See the related sample program.
vector::operator[]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
The member function returns a reference to the element of the
controlled sequence at position pos. If that position is invalid,
the behavior is undefined.
vector::pop_back
void pop_back();
The member function removes the last element of the controlled
sequence, which must be non-empty.
See the related sample program.
vector::push_back
void push_back(const T& x);
The member function inserts an element with value x at the end of
the controlled sequence.
See the related sample program.
vector::rbegin
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
The member function returns a reverse iterator that points just
beyond the end of the controlled sequence. Hence, it designates the
file:///D|/97/c++_1/LIBREF.TXT (370 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 365 of 619
beginning of the reverse sequence.
vector::reference
typedef A::reference reference;
The type describes an object that can serve as a reference to an
element of the controlled sequence.
vector::rend
const_reverse_iterator rend() const;
reverse_iterator rend();
The member function returns a reverse iterator that points at the
first element of the sequence (or just beyond the end of an empty
sequence). Hence, it designates the end of the reverse sequence.
vector::reserve
void reserve(size_type n);
The member function ensures that capacity() henceforth returns at
least n.
See the related sample program.
vector::resize
void resize(size_type n, T x = T());
The member function ensures that size() henceforth returns n. If it
must lengthen the controlled sequence, it appends elements with
value x.
See the related sample program.
vector::reverse_iterator
typedef reverse_iterator<iterator, value_type,
reference, A::pointer, difference_type>
reverse_iterator;
The type describes an object that can serve as a reverse iterator
for the controlled sequence.
vector::size
size_type size() const;
The member function returns the length of the controlled sequence.
See the related sample program.
vector::size_type
typedef A::size_type size_type;
file:///D|/97/c++_1/LIBREF.TXT (371 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 366 of 619
The unsigned integer type describes an object that can represent
the length of any controlled sequence.
vector::swap
void swap(vector& str);
The member function swaps the controlled sequences between *this
and str. If allocator == str.allocator, it does so in constant
time. Otherwise, it performs a number of element assignments and
constructor calls proportional to the number of elements in the two
controlled sequences.
vector::value_type
typedef A::value_type value_type;
The type is a synonym for the template parameter T.
vector::vector
explicit vector(const A& al = A());
explicit vector(size_type n, const T& v = T(), const A& al = A());
vector(const vector& x);
vector(const_iterator first, const_iterator last,
const A& al = A());
All constructors store the allocator object al (or, for the copy
constructor, x.get_allocator()) in allocator and initialize the
controlled sequence. The first constructor specifies an empty
initial controlled sequence. The second constructor specifies a
repetition of n elements of value x. The third constructor
specifies a copy of the sequence controlled by x. The last
constructor specifies the sequence [first, last).
In this implementation, if a translator does not support member
template functions, the template:
template<class InIt>
vector(InIt first, InIt last, const A& al = A());
is replaced by:
vector(const_iterator first, const_iterator last,
const A& al = A());
All constructors copy N elements and perform no interim
reallocation.
vector<bool, A>
class vector<bool, allocator<bool> > { typedef allocator<bool> A; pu
const_reference; typedef T0 iterator; typedef T1 const_iterator; voi
reference y); // rest same as template class vector };
The class is a specialization of template class vector for elements
file:///D|/97/c++_1/LIBREF.TXT (372 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 367 of 619
of type bool. It alters the definition of four member types (to
optimize the packing and unpacking of elements) and adds two member
functions. Its behavior is otherwise the same as for template class
vector.
In this implementation, if partial specializations are not
supported or if bool is not a distinct type, the class should be
referred to by the synonym _Bvector.
vector<bool, A>::const_iterator
typedef T1 const_iterator;
The type describes an object that can serve as a constant random-
access iterator for the controlled sequence. It is described here
as a synonym for the unspecified type T1.
vector<bool, A>::const_reference
typedef bool const_reference;
The type describes an object that can serve as a constant reference
to an element of the controlled sequence, in this case bool.
vector<bool, A>::flip
void flip();
The member function inverts the values of all the members of the
controlled sequence.
vector<bool, A>::iterator
typedef T0 iterator;
The type describes an object that can serve as a random-access
iterator for the controlled sequence. It is described here as a
synonym for the unspecified type T0.
vector<bool, A>::reference
class reference {
public:
reference& operator=(const reference& x);
reference& operator=(bool x);
void flip();
bool operator~() const;
operator bool() const;
};
The type describes an object that can serve as a reference to an
element of the controlled sequence. Specifically, for two objects x
and y of class reference:
lbool(x) yields the value of the element designated by x
l~x yields the inverted value of the element designated by x
lx.flip() inverts the value stored in x
file:///D|/97/c++_1/LIBREF.TXT (373 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 368 of 619
ly = bool(x) and y = x both assign the value of the element
designated by x to the element designated by y
It is unspecified how member functions of class vector<bool, A>
construct objects of class reference that designate elements of a
controlled sequence. The default constructor for class reference
generates an object that refers to no such element.
vector<bool, A>::swap
void swap(reference x, reference y);
The static member function swaps the members of the controlled
sequences designated by x and y.
<iso646.h> [Added with Amendment 1]
#define and && [keyword in C++]
#define and_eq &= [keyword in C++]
#define bitand & [keyword in C++]
#define bitor | [keyword in C++]
#define compl ~ [keyword in C++]
#define not ! [keyword in C++]
#define not_eq != [keyword in C++]
#define or || [keyword in C++]
#define or_eq |= [keyword in C++]
#define xor ^ [keyword in C++]
#define xor_eq ^= [keyword in C++]
Include the standard header <iso646.h> to provide readable
alternatives to certain operators or punctuators. The standard
header <iso646.h> is available even in a freestanding
implementation.
and
#define and && [keyword in C++]
The macro yields the operator &&.
and_eq
#define and_eq &= [keyword in C++]
The macro yields the operator &=.
bitand
#define bitand & [keyword in C++]
The macro yields the operator &.
bitor
#define bitor | [keyword in C++]
The macro yields the operator |.
file:///D|/97/c++_1/LIBREF.TXT (374 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 369 of 619
compl
#define compl ~ [keyword in C++]
The macro yields the operator ~.
not
#define not ! [keyword in C++]
The macro yields the operator !.
not_eq
#define not_eq != [keyword in C++]
The macro yields the operator !=.
or
#define or || [keyword in C++]
The macro yields the operator ||.
or_eq
#define or_eq |= [keyword in C++]
The macro yields the operator |=.
xor
#define xor ^ [keyword in C++]
The macro yields the operator ^.
xor_eq
#define xor_eq ^= [keyword in C++]
The macro yields the operator ^=.
<wchar.h> [Added with Amendment 1]
Most of the functions, types, and constants listed below are
documented in the Run-Time Library Reference, a section of the
Those that are not documented there are relatively new to wchar.h
and are documented in the topics following this one.
#define NULL <either 0, 0L, or (void *)
#define WCHAR_MAX <#if
#define WCHAR_MIN <#if
#define WEOF <wint_t constant
wint_t btowc(int c);
file:///D|/97/c++_1/LIBREF.TXT (375 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 370 of 619
wint_t fgetwc(FILE *stream);
wchar_t *fgetws(wchar_t *s, int n, FILE *stream);
wint_t fputwc(wchar_t c, FILE *stream);
int fputws(const wchar_t *s, FILE *stream);
int fwide(FILE *stream, int mode);
int fwprintf(FILE *stream, const wchar_t *format, ...);
int fwscanf(FILE *stream, const wchar_t *format, ...);
wint_t getwc(FILE *stream);
wint_t getwchar(void);
size_t mbrlen(const char *s, size_t n, mbstate_t *ps);
size_t mbrtowc(wchar_t *pwc, const char *s, size_t n, mbstate_t
*ps);
int mbsinit(const mbstate_t *ps);
size_t mbsrtowcs(wchar_t *dst, const char **src, size_t len,
mbstate_t *ps);
typedef o-type
wint_t putwc(wchar_t c, FILE *stream);
wint_t putwchar(wchar_t c);
typedef ui-type
int swprintf(wchar_t *s, size_t n, const wchar_t *format, ...);
int swscanf(const wchar_t *s, const wchar_t *format, ...);
struct tm;
wint_t ungetwc(wint_t c, FILE *stream);
int vfwprintf(FILE *stream, const wchar_t *format, va_list arg);
int vswprintf(wchar_t *s, size_t n, const wchar_t *format, va_list
arg);
int vwprintf(const wchar_t *format, va_list arg);
typedef i-type wchar_t; [keyword in
size_t wcrtomb(char *s, wchar_t wc, mbstate_t *ps);
wchar_t *wcscat(wchar_t *s1, const wchar_t *s2);
wchar_t *wcschr(const wchar_t *s, wchar_t c);
int wcscmp(const wchar_t *s1, const wchar_t *s2);
int wcscoll(const wchar_t *s1, const wchar_t *s2);
wchar_t *wcscpy(wchar_t *s1, const wchar_t *s2);
size_t wcscspn(const wchar_t *s1, const wchar_t *s2);
size_t wcsftime(wchar_t *s, size_t maxsize, const wchar_t *format,
const struct tm *timeptr);
size_t wcslen(const wchar_t *s);
wchar_t *wcsncat(wchar_t *s1, const wchar_t *s2, size_t n);
int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n);
wchar_t *wcsncpy(wchar_t *s1, const wchar_t *s2, size_t n);
wchar_t *wcspbrk(const wchar_t *s1, const wchar_t *s2);
wchar_t *wcsrchr(const wchar_t *s, wchar_t c);
size_t wcsrtombs(char *dst, const wchar_t **src, size_t len,
mbstate_t *ps);
size_t wcsspn(const wchar_t *s1, const wchar_t *s2);
wchar_t *wcsstr(const wchar_t *s1, const wchar_t *s2);
double wcstod(const wchar_t *nptr, wchar_t **endptr);
wchar_t *wcstok(wchar_t *s1, const wchar_t *s2, wchar_t **ptr);
long wcstol(const wchar_t *nptr, wchar_t **endptr, int base);
unsigned long wcstoul(const wchar_t *nptr, wchar_t **endptr, int
base);
size_t wcsxfrm(wchar_t *s1, const wchar_t *s2, size_t n);
int wctob(wint_t c);
typedef i_type
wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n); [not in
C++]
file:///D|/97/c++_1/LIBREF.TXT (376 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 371 of 619
const wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n); [C++
only]
wchar_t *wmemchr(wchar_t *s, wchar_t c, size_t n); [C++ only]
int wmemcmp(const wchar_t *s1, const wchar_t *s2, size_t n);
wchar_t *wmemcpy(wchar_t *s1, const wchar_t *s2, size_t n);
wchar_t *wmemmove(wchar_t *s1, const wchar_t *s2, size_t n);
wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);
int wprintf(const wchar_t *format, ...);
int wscanf(const wchar_t *format, ...);
Include the standard header <wchar.h> so that you can perform input
and output operations on wide streams or manipulate wide strings.
WCHAR_MAX
#define WCHAR_MAX <#if
The macro yields the maximum value for type wchar_t.
WCHAR_MIN
#define WCHAR_MIN <#if
The macro yields the minimum value for type wchar_t.
btowc
wint_t btowc(int c);
The function returns WEOF if c equals EOF. Otherwise, it converts
(unsigned char)c as a one-byte multibyte character beginning in the
initial conversion state, as if by calling mbrtowc. If the
conversion succeeds, the function returns the wide-character
conversion. Otherwise, it returns WEOF.
fwide
int fwide(FILE *stream, int mode);
The function determines the orientation of the stream stream. If
mode is greater than zero, it first attempts to make the stream
wide oriented. If mode is less than zero, it first attempts to make
the stream byte oriented. In any event, the function returns:
lA value greater than zero if the stream is left wide-oriented.
lZero if the stream is left unbound.
lA value less than zero if the stream is left byte-oriented.
In no event will the function alter the orientation of a stream
after it has been oriented.
mbrlen
size_t mbrlen(const char *s, size_t n, mbstate_t *ps);
The function is equivalent to the call:
file:///D|/97/c++_1/LIBREF.TXT (377 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 372 of 619
mbrtowc(0, s, n, ps != 0 ? ps : &internal)
where internal is an object of type mbstate_t internal to the
mbrlen function. At program startup, internal is initialized to the
initial conversion state. No other library function alters the
value stored in internal.
The function returns:
l(size_t)-2 if, after converting all n characters, the resulting
conversion state indicates an incomplete multibyte character.
l(size_t)-1 if the function detects an encoding error before
completing the next multibyte character, in which case the
function stores the value EILSEQ in errno and leaves the
resulting conversion state undefined.
lZero, if the next completed character is a null character, in
which case the resulting conversion state is the initial
conversion state.
lx, the number of bytes needed to complete the next muitibyte
character, in which case the resulting conversion state
indicates that x bytes have been converted.
Thus, mbrlen effectively returns the number of bytes that would be
consumed in successfully converting a multibyte character to a wide
character (without storing the converted wide character), or an
error code if the conversion cannot succeed.
mbrtowc
size_t mbrtowc(wchar_t *pwc, const char *s, size_t n, mbstate_t
*ps);
The function determines the number of bytes in a multibyte string
that completes the next multibyte character, if possible.
If ps is not a null pointer, the conversion state for the multibyte
string is assumed to be *ps. Otherwise, it is assumed to be
&internal, where internal is an object of type mbstate_t internal
to the mbrtowc function. At program startup, internal is
initialized to the initial conversion state. No other library
function alters the value stored in internal.
If s is not a null pointer, the function determines x, the number
of bytes in the multibyte string s that complete or contribute to
the next multibyte character. (x cannot be greater than n.)
Otherwise, the function effectively returns mbrtowc(0, "", 1, ps),
ignoring pwc and n. (The function thus returns zero only if the
conversion state indicates that no incomplete multibyte character
is pending from a previous call to mbrlen, mbrtowc, or mbsrtowcs
for the same string and conversion state.)
If pwc is not a null pointer, the function converts a completed
multibyte character to its corresponding wide-character value and
stores that value in *pwc.
The function returns:
file:///D|/97/c++_1/LIBREF.TXT (378 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 373 of 619
l(size_t)-2 if, after converting all n characters, the resulting
conversion state indicates an incomplete multibyte character.
l(size_t)-1 if the function detects an encoding error before
completing the next multibyte character, in which case the
function stores the value EILSEQ in errno and leaves the
resulting conversion state undefined.
lZero, if the next completed character is a null character, in
which case the resulting conversion state is the initial
conversion state.
lx, the number of bytes needed to complete the next muitibyte
character, in which case the resulting conversion state
indicates that x bytes have been converted.
mbsinit
int mbsinit(const mbstate_t *ps);
The function returns a nonzero value if ps is a null pointer or if
*ps designates an initial conversion state. Otherwise, it returns
zero.
mbsrtowcs
size_t mbsrtowcs(wchar_t *dst, const char **src, size_t len,
mbstate_t *ps);
The function converts the multibyte string beginning at *src to a
sequence of wide characters as if by repeated calls of the form:
x = mbrtowc(dst, *src, n, ps != 0 ? ps : &internal)
where n is some value > 0 and internal is an object of type
mbstate_t internal to the mbsrtowcs function. At program startup,
internal is initialized to the initial conversion state. No other
library function alters the value stored in internal.
If dst is not a null pointer, the mbsrtowcs function stores len
wide characters , at most, by calls to mbrtowc. The function
effectively increments dst by one and *src by x after each call to
mbrtowc that stores a converted wide character. After a call that
returns zero, mbsrtowcs stores a null wide character at dst and
stores a null pointer at *src.
If dst is a null pointer, len is effectively assigned a large
value.
The function returns:
l(size_t)-1, if a call to mbrtowc returns (size_t)-1, indicating
that it has detected an encoding error before completing the
next multibyte character.
lThe number of multibyte characters successfully converted, not
including the terminating null character.
mbstate_t
file:///D|/97/c++_1/LIBREF.TXT (379 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 374 of 619
typedef o-type
The type is an object type o-type that can represent a
state for any of the functions mbrlen, mbrtowc, mbsrtowcs, wcrtomb,
or wcsrtombs. A definition of the form:
mbstate_t mbst = {0};
ensures that mbst represents the initial conversion state. Note,
however, that other values stored in an object of type mbstate_t
can also represent this state. To test safely for this state, use
the function mbsinit.
wcrtomb
size_t wcrtomb(char *s, wchar_t wc, mbstate_t *ps);
The function determines the number of bytes needed to represent the
wide character wc as a multibyte character, if possible. (Not all
values representable as type wchar_t are necessarily valid wide-
character codes.)
If ps is not a null pointer, the conversion state for the multibyte
string is assumed to be *ps. Otherwise, it is assumed to be
&internal, where internal is an object of type mbstate_t internal
to the wcrtomb function. At program startup, internal is
initialized to the initial conversion state. No other library
function alters the value stored in internal.
If s is not a null pointer and wc is a valid wide-character code,
the function determines x, the number of bytes needed to represent
wc as a multibyte character, and stores the converted bytes in the
array of char beginning at s. (x cannot be greater than
If wc is a null wide character, the function stores any shift
sequence needed to restore the initial shift state, followed by a
null byte. The resulting conversion state is the initial conversion
state.
If s is a null pointer, the function effectively returns wcrtomb
(buf, L'\0', ps), where buf is a buffer internal to the function.
(The function thus returns the number of bytes needed to restore
the initial conversion state and to terminate the multibyte string
pending from a previous call to wcrtomb or wcsrtombs for the same
string and conversion state.)
The function returns:
l(size_t)-1 if wc is an invalid wide-character code, in which
case the function stores the value EILSEQ in errno and leaves
the resulting conversion state undefined.
lx, the number of bytes needed to complete the next muitibyte
character, in which case the resulting conversion state
indicates that x bytes have been generated.
wcsrtombs
file:///D|/97/c++_1/LIBREF.TXT (380 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 375 of 619
size_t wcsrtombs(char *dst, const wchar_t **src, size_t len,
mbstate_t *ps);
The function converts the wide-character string beginning at *src
to a sequence of multibyte characters as if by repeated calls of
the form:
x = wcrtomb(dst ? dst : buf, *src, ps != 0 ? ps : &internal)
where buf is an array of type char and internal is an object of
mbstate_t, both internal to the wcsrtombs function. At program
startup, internal is initialized to the initial conversion state.
No other library function alters the value stored in internal.
If dst is not a null pointer, the wcsrtombs function stores len
bytes, at most, by calls to wcrtomb. The function effectively
increments dst by x and *src by one after each call to wcrtomb that
stores a complete converted multibyte character in the remaining
available. After a call that stores a complete null multibyte
character at dst (including any shift sequence needed to restore
the initial shift state), the function stores a null pointer at
*src.
If dst is a null pointer, len is effectively assigned a large
value.
The function returns:
l(size_t)-1, if a call to wcrtomb returns (size_t)-1, indicating
that it has detected an invalid wide-character code.
lThe number of bytes successfully converted, not including the
terminating null byte.
wctob
int wctob(wint_t c);
The function determines whether c can be represented as a one-byte
multibyte character x, beginning in the initial shift state. (It
effectively calls wcrtomb to make the conversion.) If so, the
function returns x. Otherwise, it returns WEOF.
wmemchr
wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n); [not in
C++]
const wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n); [C++
only]
wchar_t *wmemchr(wchar_t *s, wchar_t c, size_t n); [C++ only]
The function searches for the first element of an array beginning
at the address s with size n, that equals c. If successful, it
returns the address of the matching element; otherwise, it returns
a null pointer.
wmemcmp
file:///D|/97/c++_1/LIBREF.TXT (381 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 376 of 619
int wmemcmp(const wchar_t *s1, const wchar_t *s2, size_t n);
The function compares successive elements from two arrays beginning
at the addresses s1 and s2 (both of size n), until it finds
elements that are not equal.
lIf all elements are equal, the function returns zero.
lIf the differing element from s1 is greater than the element
from s2, the function returns a positive number.
lOtherwise, the function returns a negative number.
wmemcpy
wchar_t *wmemcpy(wchar_t *s1, const wchar_t *s2, size_t n);
The function copies the array beginning at the address s2 to the
array beginning at the address s1 (both of size n). It returns s1.
The elements of the arrays can be accessed and stored in any order.
wmemmove
wchar_t *wmemmove(wchar_t *s1, const wchar_t *s2, size_t n);
The function copies the array beginning at s2 to the array
beginning at s1 (both of size n). It returns s1. If the arrays
overlap, the function accesses each of the element values from s2
before it stores a new value in that element, so the copy is not
corrupted.
wmemset
wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);
The function stores c in each of the elements of the array
beginning at s, with size n. It returns s.
STL Sample Programs
Following is an alphabetic list of 118 STL sample programs.
labs
laccumulate, copy, vector::push_back
ladjacent_difference, vector::push_back
ladvance
lBasic Math Functions
lbasic_string::append
lbasic_string size and resize
lbinary_function Structure
lcount
lcount_if
ldeque::assign and deque::swap
ldeque::begin and deque::end
ldeque::erase and deque::clear
ldeque::front and deque::back
file:///D|/97/c++_1/LIBREF.TXT (382 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 377 of 619
ldeque::insert
ldeque::operator[] and deque::at
ldeque::push_back and deque::pop_back
ldeque::push_front, deque::pop_front
ldeque::rbegin and deque::rend
ldeque::size and deque::resize
ldistance
lexp, log, and log10
lfind
lfind_if
lfor_each
lgenerate
lgenerate_n
lheap
lheap (predicate version)
lincludes
lincludes (predicate version)
linner_product
linplace_merge
linplace_merge (predicate version)
liter_swap
llist::assign
llist::back, list::front
ldeque::insert
llist::list
llower_bound
llower_bound (predicate version)
lmake_pair
lmap::insert, map::find, and map::end
lmax_element
lmax_element (predicate version)
lmap::max_size, clear, erase, size
lmerge
lmerge (predicate version)
lmin_element
lmin_element (predicate version)
lnew operator
lnext_permutation
lnext_permutation (predicate version)
lnth_element
lnth_element (predicate version)
lMembers of the numeric_limits Class
loperator == and operator < deque
lPair Logical Operator
lpartial_sort
lpartial_sort_copy
lpartial_sort_copy (predicate version)
lpartial_sort (predicate version)
lpartial_sum
lpartition
lprev_permutation
lpriority_queue functions
lqueue functions
lrandom_shuffle
lrandom_shuffle
lremove
lremove_copy
file:///D|/97/c++_1/LIBREF.TXT (383 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 378 of 619
lremove_copy_if
lremove_if
lreplace
lreplace_copy
lreplace_copy_if
lreplace_if
lreverse
lreverse_copy
lrotate
lrotate_copy
lset::(lower_, upper_)bound, equal_range
lset::(key_, value_)comp
lset::count
lset::empty and set::clear
lset::find
lset::max_size
lset::rbegin and set::rend
lset::size
lset::swap, begin, end
lsqrt and pow
lstack::operator==
lstack::operator<
lstack::size
lstack::top and stack::empty
lstring::getline
lstring::operator==
lstring::operator>
lstring::operator>=
lstring::operator>>
lstring::operator<
lstring::operator<=
lstring::operator<<
lstring::operator+
lstring::operator!=
lTrigonometry Functions
lunary_function<> Structure
lupper_bound
lupper_bound (predicate version)
lVector Class, operator==
lvector::empty, erase, and push_back
lvector::front and vector::back
lVector Class, operator<
lvector::push_back and vector::pop_back
lvector::size and vector::capacity
abs (STL Sample)
The sample code below illustrates how to use the abs STL function
in Visual C++.
Required Header:
<valarray>
Prototype:
template<class T>
file:///D|/97/c++_1/LIBREF.TXT (384 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 379 of 619
valarray<T> abs(const valarray<T>& x);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares a valarray of integers and uses the abs()STL
function to get the absolute value for each array element.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: None
//
// <filename> : main.cpp
//
// Functions:
//
// abs
//
////////////////////////////////////////////////////////////////////
#include <iostream> // for i/o functions
#include <valarray> // for valarray
using namespace std;
#define ARRAY_SIZE 10 // array size
typedef valarray<int> INTVALARRAY; // type for valarray of ints
void main()
{
// Initialize val_array to 0, -1, -2, etc.
INTVALARRAY val_array(ARRAY_SIZE);
for (int i = 0; i < ARRAY_SIZE; i++)
val_array[i] = -i;
// Display the size of val_array.
cout << "Size of val_array = " << val_array.size() << "\n\n";
// Display the values of val_array before calling abs().
cout << "The values of val_array before calling abs():\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << val_array[i] << " ";
cout << "\n\n";
// Display the result of val_array after calling abs().
INTVALARRAY abs_array = abs(val_array);
cout << "The result of val_array after calling abs():\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << abs_array[i] << " ";
cout << "\n\n";
}
file:///D|/97/c++_1/LIBREF.TXT (385 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 380 of 619
Program Output is:
Size of val_array = 10
The values of val_array before calling abs():
0 -1 -2 -3 -4 -5 -6 -7 -8 -9
The result of val_array after calling abs():
0 1 2 3 4 5 6 7 8 9
accumulate, copy, vector::push_back(STL Sample)
The sample code below illustrates how to use the accumulate, copy,
and vector::push_back STL functions in Visual C++.
Required Header:
<numeric>
Prototype:
template<class InputIterator, class _TYPE> inline
_TYPE accumulate(InputIterator first, InputIterator last, _TYP
template<class InputIterator, class _TYPE, class BinaryOperator> inl
_TYPE accumulate(InputIterator first, InputIterator last, _TYPE
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The accumulate function initializes an accumulator acc with an
initial value init and then modifies it with acc = acc + *i or acc
= binary_op(acc,*i) for every iterator i in the range [first, last)
in order. Normally, the accumulate function is used to sum the
numeric elements of a vector. However, it can also be used to do
other useful work such as concatenating a vector of strings.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// accumulate.cpp : Demonstrates the use of accumulate()
//
// Description of accumulate(first,last,init)
// accumulate(first,last,init,binary_op):
//
// Initializes the accumulator acc with the initial value init
// acc = init
// and then modifies it with
// acc = acc + *i
// or
file:///D|/97/c++_1/LIBREF.TXT (386 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 381 of 619
// acc = binary_op(acc, *i)
// for every iterator i in the range [first, last) in order.
////////////////////////////////////////////////////////////////////
// turn off warning about symbols too long for debugger
#pragma warning (disable : 4786)
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
typedef vector < float > FloatArray;
typedef vector < string > StringArray;
typedef ostream_iterator <float, char, char_traits <char> > FloatOst
void main ()
{
// a vector of floats
FloatArray rgFA;
// an ostream iterator that outputs a float to cout terminated
// by a space
FloatOstreamIt OstreamIt(cout," ");
// Initialize the array to 1,1/2,1/3,...
for (int i=0; i<10; i++) rgFA.push_back(1.0f/(i+1));
// Print the array
copy(rgFA.begin(),rgFA.end(),OstreamIt);
cout << endl;
// Sum the array
cout << "The sum of 1 + 1/2 + 1/3 + ... + 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),0.0f)
<< endl;
// Compute the product of the array
cout << "The product of 1 * 1/2 * 1/3 * ... * 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),1.0f,multiplies<float
<< endl;
// Initialize array of strings
StringArray rgs;
rgs.push_back("This ");
rgs.push_back("is ");
rgs.push_back("one ");
rgs.push_back("sentence. ");
// Concatenate the strings in the array and print the sentence
cout << "The concatenated vector of strings: "
<< accumulate(rgs.begin(),rgs.end(),string(""))
file:///D|/97/c++_1/LIBREF.TXT (387 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 382 of 619
<< endl;
}
Program Output is:
1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 0.111111 0.1
The sum of 1 + 1/2 + 1/3 + ... + 1/10 is 2.92897
The product of 1 * 1/2 * 1/3 * ... * 1/10 is 2.75573e-007
The concatenated vector of strings: This is one sentence.
adjacent_difference, vector::push_back (STL Sample)
The sample code below illustrates how to use the
adjacent_difference and vector::push_back STL functions in Visual
C++.
Required Header:
<numeric>
Prototype:
template<class InputIterator, class OutputIterator> inline
OutputIterator adjacent_difference(InputIterator first, InputIt
template<class InputIterator, class OutputIterator, class BinaryOper
OutputIterator adjacent_difference(InputIterator first, InputIt
BinaryOperator binary_op)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
Assigns to every element referred to by iterator i in the range
[result + 1, result + (last - first)) a value correspondingly equal
to *(first + (i - result)) - *(first + (i - result) - 1) or
binary_op (*(first + (i - result)), *(first + (i - result) - 1)).
Result gets the value of *first.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// adj_diff.cpp : Demonstrates the use of adjacent_difference()
//
// Description of adjacent_difference(first,last,result)
// adjacent_difference(first,last,result,binary_op):
//
// Assigns to every element referred to by iterator i in the rang
// [result + 1, result + (last - first))
// a value correspondingly equal to
// *(first + (i - result)) - *(first + (i - result) - 1)
file:///D|/97/c++_1/LIBREF.TXT (388 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 383 of 619
// or
// binary_op(*(first + (i - result)), *(first + (i - result) - 1)
// Result gets the value of *first.
////////////////////////////////////////////////////////////////////
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
using namespace std;
typedef vector < int > IntegerArray;
typedef ostream_iterator < int, char, char_traits<char> > IntOstream
void main ()
{
// an ostream iterator that outputs an int to cout terminated
// by a space
IntOstreamIt itOstream(cout," ");
// Initialize the array
// Suppose that you are taking a trip and can measure
// the miles traveled from your city of origin
// to the city you are traveling through
IntegerArray rgIA;
rgIA.push_back(5661); // San Francisco to Berlin
rgIA.push_back(7456); // to Cairo
rgIA.push_back(10995); // to Calcutta
rgIA.push_back(17019); // to Cape Town
rgIA.push_back(24394); // to Hong Kong
rgIA.push_back(30376); // to London
rgIA.push_back(35758); // to Los Angeles
// Print the array
copy(rgIA.begin(),rgIA.end(),itOstream);
cout << endl;
// Suppose that you now want the distance between each
// of the cities that you traveled to. You can easily
// find it with adjacent_difference()
IntegerArray rgDifferences(7);
IntegerArray::iterator itDifferences = rgDifferences.begin();
adjacent_difference(rgIA.begin(),rgIA.end(),itDifferences);
// Print the differences
// Remember that the first item in the differences array is
// not a difference, but is unused space
cout << "The adjacent differences are: ";
copy(rgDifferences.begin()+1,rgDifferences.end(),itOstream);
cout << endl;
// Suppose that you now want to know which adjacent differences
// are greater. If you have [a,b,c], you would like [1,0] if a>b
// and b<=c.
file:///D|/97/c++_1/LIBREF.TXT (389 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 384 of 619
// You are using less() rather than greater() because
// adjacent_difference() reverses the parameters. For example,
// if a and b are adjacent, adjacent_difference() calls
// less(b,a). See the explanation at the top of this file
// for a more exact description.
IntegerArray rgGT(6);
IntegerArray::iterator itGT = rgGT.begin();
adjacent_difference(rgDifferences.begin()+1,
rgDifferences.end(),
itGT,
less<int>());
// Print the greater thans
// Remember that the first item in the differences array is
// not a difference, but is unused space
cout << "Which adjacent distances are greater:" << endl
<< "(If you have [a,b,c], then you have [1,0] if a>b and b<
<< endl;
copy(rgGT.begin()+1,rgGT.end(),itOstream);
cout << endl;
}
Program Output is:
5661 7456 10995 17019 24394 30376 35758
The adjacent differences are: 1795 3539 6024 7375 5982 5382
Which adjacent distances are greater:
(If you have [a,b,c], then you have [1,0] if a>b and b<=c)
0 0 0 1 1
Non-Predicate Version of adjacent_find (STL Sample)
The sample code below illustrates how to use the non-predicate
version of the adjacent_find STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator> inline
ForwardIterator adjacent_find(ForwardIterator first, ForwardIte
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The adjacent_find algorithm finds consecutive pairs of matching
elements in a sequence. The adjacent_find algorithm returns an
iterator referencing the first consecutive matching element in the
range (first, last), or last if there are no such elements.
Comparison is done using operator== in this non-predicate version
of the algorithm.
file:///D|/97/c++_1/LIBREF.TXT (390 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 385 of 619
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// adfind.cpp : Illustrates how to use the non-predicate version of
// adjacent_find function.
//
// Functions:
//
// adjacent_find - Locate a matching consecutive sequence in a ran
////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iostream>
using namespace std;
void main()
{
const int ARRAY_SIZE = 8 ;
int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
int *location ; // stores the position for the first pair
// of matching consecutive elements.
int i ;
// print content of IntArray
cout << "IntArray { " ;
for(i = 0; i < ARRAY_SIZE; i++)
cout << IntArray[i] << ", " ;
cout << " }" << endl ;
// Find the first pair of matching consecutive elements
// in the range [first, last + 1)
// This version performs matching using operator==
location = adjacent_find(IntArray, IntArray + ARRAY_SIZE) ;
//print the matching consecutive elements if any were found
if (location != IntArray + ARRAY_SIZE) // matching consecutive
// elements found
cout << "Found adjacent pair of matching elements: ("
<< *location << ", " << *(location + 1) << "), " <<
"at location " << location - IntArray << endl;
else // no matching consecutive elements were found
cout << "No adjacent pair of matching elements were found"
<< endl ;
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (391 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 386 of 619
IntArray { 1, 2, 3, 4, 4, 5, 6, 7, }
Found adjacent pair of matching elements: (4, 4), at location 3
Predicate Version of adjacent_find (STL Sample)
The sample code below illustrates how to use the predicate version
of the adjacent_find STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class BinaryPredicate> inline
ForwardIterator adjacent_find(ForwardIterator first, ForwardIt
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The adjacent_find algorithm finds consecutive pairs of matching
elements in a sequence. adjacent_find returns an iterator
referencing the first consecutive matching element in the range
[first, last), or last if there are no such elements. Comparison is
done using the binary_pred function in this version of the
algorithm. The binary_pred function can be any user-defined
function. You could also use one of the binary function objects
provided by STL.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// adfind.cpp : Illustrates how to use the predicate version of
// adjacent_find function.
//
// Functions:
//
// adjacent_find - Locate a consecutive sequence in a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
using namespace std;
file:///D|/97/c++_1/LIBREF.TXT (392 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 387 of 619
void main()
{
const int VECTOR_SIZE = 5 ;
// Define a template class vector of strings
typedef vector<string > StringVector ;
//Define an iterator for template class vector of strings
typedef StringVector::iterator StringVectorIt ;
StringVector NamesVect(VECTOR_SIZE) ; //vector containing name
StringVectorIt location ; // stores the position for the
// first pair of matching
// consecutive elements.
StringVectorIt start, end, it ;
// Initialize vector NamesVect
NamesVect[0] = "Aladdin" ;
NamesVect[1] = "Jasmine" ;
NamesVect[2] = "Mickey" ;
NamesVect[3] = "Minnie" ;
NamesVect[4] = "Goofy" ;
start = NamesVect.begin() ; // location of first
// element of NamesVect
end = NamesVect.end() ; // one past the location
// last element of NamesVect
// print content of NamesVect
cout << "NamesVect { " ;
for(it = start; it != end; it++)
cout << *it << ", " ;
cout << " }\n" << endl ;
// Find the first name that is lexicographically greater
// than the following name in the range [first, last + 1).
// This version performs matching using binary predicate
// function greater<string>
location = adjacent_find(start, end, greater<string>()) ;
// print the first pair of strings such that the first name is
// lexicographically greater than the second.
if (location != end)
cout << "(" << *location << ", " << *(location + 1) << ")"
<< " the first pair of strings in NamesVect such that\n"
<< "the first name is lexicographically greater than"
<< "the second\n" << endl ;
else
cout << "No consecutive pair of strings found such that\n"
<< "the first name is lexicographically greater than "
<< "the second\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (393 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 388 of 619
Program Output is:
NamesVect { Aladdin, Jasmine, Mickey, Minnie, Goofy, }
(Minnie, Goofy) the first pair of strings in NamesVect such that
the first name is lexicographically greater than the second
advance (STL Sample)
The sample code below illustrates how to use the advance STL
function in Visual C++.
Required Header:
<iterator>
Prototype:
template<class InIt, class Dist>
void advance(InIt& it, Dist n);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The advance function accepts two parameters:
- InIt: The iterator to advance.
- Dist: The number of elements to increment the iterator by.
The advance function advances the iterator n times. If the iterator
is a random-access iterator type, the function evaluates the
expression as iterator += n. Otherwise, it performs each increment
by evaluating: ++iterator. If the iterator is an input or forward
iterator type, n must not be negative. NOTE: The class/parameter
names in the prototype may not match the version in the header
file. Some have been modified to improve readability.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : Advance.cpp
//
// Functions:
//
// advance()
////////////////////////////////////////////////////////////////////
/* Compile options needed: /GX
*/
#include <iostream>
file:///D|/97/c++_1/LIBREF.TXT (394 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 389 of 619
#include <string>
#include <list>
#pragma warning (disable:4786)
using namespace std ;
typedef list<string> STRLIST;
void main() {
STRLIST List;
STRLIST::iterator iList;
STRLIST::difference_type dTheDiff;
List.push_back("A1");
List.push_back("B2");
List.push_back("C3");
List.push_back("D4");
List.push_back("E5");
List.push_back("F6");
List.push_back("G7");
// Print out the list
iList=List.begin();
cout << "The list is: ";
for (int i = 0; i < 7 ; i++, iList++)
cout << *iList << " ";
// Initialize to the first element"
iList=List.begin();
cout << "\n\nAdvance to the 3rd element." << endl;
advance(iList,2);
cout << "The element is " << *iList << endl;
dTheDiff = distance( List.begin(), iList);
}
Program Output is:
The list is: A1 B2 C3 D4 E5 F6 G7
Advance to the 3rd element.
The element is C3
Basic Math (STL Sample)
The sample code below illustrates how to use some basic math
functions in Visual C++.
Required Header:
< functional >
Prototype:
template<class _TYPE>
file:///D|/97/c++_1/LIBREF.TXT (395 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 390 of 619
struct plus : binary_function<_TYPE, _TYPE, _TYPE>
{
_TYPE operator()(const _TYPE& _X, const _TYPE& _Y) const
{return (_X + _Y); }
};
template<class _TYPE>
struct minus : binary_function<_TYPE, _TYPE, _TYPE>
{
_TYPE operator()(const _TYPE& _X, const _TYPE& _Y) const
{return (_X - _Y); }
};
template<class _TYPE>
struct times : binary_function<_TYPE, _TYPE, _TYPE>
{
_TYPE operator()(const _TYPE& _X, const _TYPE& _Y) const
{return (_X * _Y); }
};
template<class _TYPE>
struct divides : binary_function<_TYPE, _TYPE, _TYPE>
{
_TYPE operator()(const _TYPE& _X, const _TYPE& _Y) const
{return (_X / _Y); }
};
template<class _TYPE>
struct modulus : binary_function<_TYPE, _TYPE, _TYPE>
{
_TYPE operator()(const _TYPE& _X, const _TYPE& _Y) const
{return (_X % _Y); }
};
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
This sample uses a class derived from all five basic math
structures: plus, minus, times, divides, and modulus, using an
integer as the templated operand.
Sample Code:
////////////////////////////////////////////////////////////////
//
// Compile options needed: none
//
// mathfunc.cpp - Illustrating the basic STL math
// functions.
//
// Structures: plus<A> - Adds data type A object to
// a class object derived from plus.
// minus<A> - Subtracts data type A.
// multiplies<A> - Multiplies object by data type A.
// divides<A> - Divides object by data type A.
// modulus<A> - Returns object modulo A.
/////////////////////////////////////////////////////////////////
#include <functional>
file:///D|/97/c++_1/LIBREF.TXT (396 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 391 of 619
#include <iostream>
using namespace std ;
class MathOps : public plus<int>, public minus<int>,
public multiplies<int>, public divides<int>,
public modulus<int>
{
public:
int value;
MathOps(){value=0;}
MathOps(int x){value=x;}
result_type operator+(second_argument_type add2)
{return value + add2;}
result_type operator-(second_argument_type sub2)
{return value - sub2;}
result_type operator*(second_argument_type mult2)
{return value * mult2;}
result_type operator/(second_argument_type div2)
{return value / div2;}
result_type operator%(second_argument_type mod2)
{return value % mod2;}
friend ostream& operator<<(ostream& os, const MathOps& obj ) ;
};
ostream& operator<<(ostream& os, const MathOps& obj )
{
os << obj.value ;
return os ;
}
void main(void)
{
MathOps one,two,three,four,five,six;
cout << "Using MathOps class..." << endl ;
one = 18;
cout << "one = " << one << endl ;
two = one + 1;
cout << "two = one + 1 = " << two << endl ;
three = two - 2;
cout << "three = two - 2 = " << three << endl ;
four = three * 3;
cout << "four = three * 3 = " << four << endl ;
five = four / 4;
cout << "five = four / 4 = " << five << endl ;
six = five % 5;
cout << "six = five % 5 = " << six << endl ;
}
file:///D|/97/c++_1/LIBREF.TXT (397 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 392 of 619
Program Output is:
Using MathOps class...
one = 18
two = one + 1 = 19
three = two - 2 = 17
four = three * 3 = 51
five = four / 4 = 12
six = five % 5 = 2
basic_string::append (STL Sample)
The sample code below illustrates how to use the
basic_string::append STL function in Visual C++.
Required Header:
<string>
Prototype:
string& append(const basic_string& _X);
string& append(const basic_string& _X, size_type pos, size_type
string& append(const element_type *_S, size_type count);
string& append(const element_type *_S);
string& append(size_type count, element_type _C);
string& append(Iterator first, Iterator last);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The append member functions of the basic_string append elements to
the end of the string. The different forms of the function provide
alternate ways to specify the source of the elements that will be
appended. The append functions return a reference to the string to
which the elements were appended.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// bsappend.cpp : Illustrates how to use the string append member
// function.
//
// Functions:
//
// string::append - appends a sequence of elements to the
file:///D|/97/c++_1/LIBREF.TXT (398 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 393 of 619
// current string.
////////////////////////////////////////////////////////////////////
#include <string>
#include <iostream>
using namespace std ;
void main()
{
string str1("012");
string str2("345");
cout << "str1 = " << str1.c_str() << endl;
// append str2 to str1
str1.append(str2);
cout << "str1 = " << str1.c_str() << endl;
// append the last 2 items in str2 to str1
str2 = "567";
str1.append(str2, 1, 2); // begin at pos 1, append 2 elements
cout << "str1 = " << str1.c_str() << endl;
// append the first 2 items from an array of the element type
char achTest[] = {'8', '9', 'A'};
str1.append(achTest, 2);
cout << "str1 = " << str1.c_str() << endl;
// append all of a string literal to str1
char szTest[] = "ABC";
str1.append(szTest);
cout << "str1 = " << str1.c_str() << endl;
// append one item of the element type
str1.append(1, 'D');
cout << "str1 = " << str1.c_str() << endl;
// append str2 to str1 using iterators
str2 = "EF";
str1.append (str2.begin(), str2.end());
cout << "str1 = " << str1.c_str() << endl;
}
Program Output is:
str1 = 012
str1 = 012345
str1 = 01234567
file:///D|/97/c++_1/LIBREF.TXT (399 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 394 of 619
str1 = 0123456789
str1 = 0123456789ABC
str1 = 0123456789ABCD
str1 = 0123456789ABCDEF
basic_string::find_first_of (STL Sample)
The sample code below illustrates how to use the
basic_string::find_first_of STL function in Visual C++.
Required Header:
<string>
Prototype:
size_type find_first_of(const basic_string& _X, size_type iPos
size_type find_first_of(const element_type *_S, size_type iPos,
size_type find_first_of(const element_type *_S, size_type iPos
size_type find_first_of(element_type _C, size_type iPos = 0);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The member functions each find the first (lowest position) element
of the controlled sequence at or after position iPos that matches
any of the elements in the operand sequence specified by the
remaining operands. If it succeeds, it returns the position.
Otherwise, the function returns npos. The position returned is 0
(zero) based. The npos return value is a special value indicating
that none of the elements were found.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// main.cpp : Demonstrates the use of the string::find_first_of().
//
// Functions:
//
// string::find_first_of() - find the first instance in the
// controlled string of any of the elements specified by the
// parameters. The search begins at an optionally-supplied
// position in the controlled string.
////////////////////////////////////////////////////////////////////
#include <string>
#include <iostream>
using namespace std ;
void main()
{
file:///D|/97/c++_1/LIBREF.TXT (400 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 395 of 619
string str1("Heartbeat");
string str2("abcde");
int iPos = 0;
cout << "The string to search is '" << str1.c_str() << "'"
<< endl;
// find the first instance in str1 of any characters in str2
iPos = str1.find_first_of (str2, 0); // 0 is default position
cout << "Element in '" << str2.c_str() << "' found at position "
<< iPos << endl;
// start looking in the third position...
iPos = str1.find_first_of (str2, 2);
cout << "Element in '" << str2.c_str() << "' found at position "
<< iPos << endl;
// use an array of the element type as the set of elements to
// search for; look for anything after the fourth position
char achVowels[] = {'a', 'e', 'i', 'o', 'u'};
iPos = str1.find_first_of (achVowels, 4, sizeof(achVowels));
cout << "Element in '";
for (int i = 0; i < sizeof (achVowels); i++)
cout << achVowels[i];
cout << "' found at position " << iPos << endl;
// use a string literal to specify the set of elements
char szVowels[] = "aeiou";
iPos = str1.find_first_of (szVowels, 0); // 0 is default positi
cout << "Element in '" << szVowels << "' found at position "
<< iPos << endl;
// look for a specific character beginning in the third position
iPos = str1.find_first_of ('e', 2);
cout << "'e' found at position " << iPos << endl;
}
Program Output is:
The string to search is 'Heartbeat'
Element in 'abcde' found at position 1
Element in 'abcde' found at position 2
Element in 'aeiou' found at position 6
Element in 'aeiou' found at position 1
'e' found at position 6
basic_string size and resize (STL Sample)
The sample code below illustrates how to use the basic_string size
and resize STL functions in Visual C++.
file:///D|/97/c++_1/LIBREF.TXT (401 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 396 of 619
Required Header:
<string>
Prototype:
size_type size() const;
void resize(size_type n, E c = E());
resize is defined in header xstring which is included indirectly.
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The size function returns the length of the sequence. The resize
function changes the size to the length specified by the first
parameter. If the sequence is made longer, the function appends
elements with the value of the second parameter. This value
defaults to a null. The output of the sample code shows spaces for
the null characters. operator<< reads the size of string and
outputs each character in the string one at a time.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : size.cpp
//
// Functions:
//
// size()
// resize() ; Defined in header xstring which is included indirec
////////////////////////////////////////////////////////////////////
/* Compile options needed: /GX
*/
#include <iostream>
#include <string>
using namespace std;
void main()
{
string TestString = "1111122222333334444455555";
cout << TestString << "\n size: " << TestString.size() << endl;
TestString.resize(5);
cout << TestString << "\n size: " << TestString.size() << endl;
TestString.resize(10);
cout << TestString << "\n size: " << TestString.size() << endl;
TestString.resize(15,'6');
file:///D|/97/c++_1/LIBREF.TXT (402 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 397 of 619
cout << TestString << "\n size: " << TestString.size() << endl;
}
Program Output is:
1111122222333334444455555
size: 25
11111
size: 5
11111
size: 10
11111 66666
size: 15
binary_function Structure (STL Sample)
The sample code below illustrates how to use the binary_function
structure in Visual C++.
Required Header:
< functional >
Prototype:
template<class _A1, class _A2, class _R>
struct binary_function
{
typedef _A1 first_argument_type;
typedef _A2 second_argument_type;
typedef _R result_type;
};
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The binary_function<A,B,C> class is used as a base class to allow
the user to easily define binary operator functions that take data
types A and B as arguments and return data type C objects.
Sample Code:
////////////////////////////////////////////
//
// Compile options needed: /GX
//
// binfunc.cpp : Illustrating the binary_function
// structure.
//
// Structure used: binary_function<A,B,C> - base
// class used to create operator
// functions taking data types A
// and B and returning data type C.
////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (403 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 398 of 619
#include <functional>
#include <iostream>
using namespace std ;
class binary_test : public binary_function<binary_test &,int,float>
{
public:
float value;
binary_test(){value=10.0;}
binary_test(float x){value=x;}
result_type operator<<(second_argument_type arg2);
};
binary_test::result_type
binary_test::operator<<(binary_test::second_argument_type arg2)
{
value = ((int)value) << arg2;
cout << "New value after shift is" << value << endl;
return value;
}
void main(void)
{
binary_test item;
cout << "Begin" << endl;
item = item << 2;
}
Program Output is:
Begin
New value after shift is 40.0
count (STL Sample)
The sample code below illustrates how to use the count STL function
in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class T> inline
size_t count(InputIterator first, InputIterator last, const T&
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
file:///D|/97/c++_1/LIBREF.TXT (404 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 399 of 619
The count algorithm counts the number of elements in the range
[first, last +1) that match value and returns the number of
matching elements.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// count.cpp : Illustrates how to use the count function.
//
// Functions:
//
// count - Count items in a range that match a value.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string > StringVector ;
//Define an iterator for template class vector of strings
typedef StringVector::iterator StringVectorIt ;
StringVector NamesVect(VECTOR_SIZE) ; //vector containing name
string value("Sea") ; // stores the value used
// to count matching elements
StringVectorIt start, end, it ;
int result = 0 ; // stores count of elements
// that match value.
// Initialize vector NamesVect
NamesVect[0] = "She" ;
NamesVect[1] = "Sells" ;
NamesVect[2] = "Sea" ;
NamesVect[3] = "Shells" ;
NamesVect[4] = "by" ;
NamesVect[5] = "the" ;
file:///D|/97/c++_1/LIBREF.TXT (405 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 400 of 619
NamesVect[6] = "Sea" ;
NamesVect[7] = "Shore" ;
start = NamesVect.begin() ; // location of first
// element of NamesVect
end = NamesVect.end() ; // one past the location
// last element of NamesVect
// print content of NamesVect
cout << "NamesVect { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// Count the number of elements in the range [first, last +1)
// that match value.
result = count(start, end, value) ;
// print the count of elements that match value
cout << "Number of elements that match \"Sea\" = "
<< result << endl ;
}
Program Output is:
NamesVect { She Sells Sea Shells by the Sea Shore }
Number of elements that match "Sea" = 2
count_if (STL Sample)
The sample code below illustrates how to use the count_if STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class Predicate> inline
size_t count_if(InputIterator first, InputIterator last, Predic
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The count_if algorithm counts the number of elements in the range
[first, last) that cause the predicate to return true, and returns
the number of elements for which the predicate was true.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (406 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 401 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// count.cpp : Illustrates how to use the count_if function.
//
// Functions:
//
// count_if - Count items in a range that satisfy a predicate.
//
// begin - Returns an iterator that points to the first elemen
// a sequence.
//
// end - Returns an iterator that points one past the end of
// sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
using namespace std;
// Return true if string str starts with letter 'S'
int MatchFirstChar( const string& str)
{
string s("S") ;
return s == str.substr(0,1) ;
}
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string > StringVector ;
//Define an iterator for template class vector of strings
typedef StringVector::iterator StringVectorIt ;
StringVector NamesVect(VECTOR_SIZE) ; //vector containing name
StringVectorIt start, end, it ;
int result = 0 ; // stores count of elements
// that match value.
// Initialize vector NamesVect
NamesVect[0] = "She" ;
file:///D|/97/c++_1/LIBREF.TXT (407 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 402 of 619
NamesVect[1] = "Sells" ;
NamesVect[2] = "Sea" ;
NamesVect[3] = "Shells" ;
NamesVect[4] = "by" ;
NamesVect[5] = "the" ;
NamesVect[6] = "Sea" ;
NamesVect[7] = "Shore" ;
start = NamesVect.begin() ; // location of first
// element of NamesVect
end = NamesVect.end() ; // one past the location
// last element of NamesVect
// print content of NamesVect
cout << "NamesVect { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// Count the number of elements in the range [first, last +1)
// that start with letter 'S'
result = count_if(start, end, MatchFirstChar) ;
// print the count of elements that start with letter 'S'
cout << "Number of elements that start with letter \"S\" = "
<< result << endl ;
}
Program Output is:
NamesVect { She Sells Sea Shells by the Sea Shore }
Number of elements that start with letter "S" = 6
deque::assign and deque::swap (STL Sample)
The sample code below illustrates how to use the deque::assign and
deque::swap STL functions in Visual C++.
Required Header:
< deque>
Prototype:
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
void swap(deque& dq);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
file:///D|/97/c++_1/LIBREF.TXT (408 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 403 of 619
The first assign member function replaces the sequence controlled
by *this with the sequence [first, last). The second assign member
function replaces the sequence controlled by *this with a
repetition of n elements of value x. The swap member function swaps
the contents between *this and dq.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// assign
// swap
// begin
// end
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
void main()
{
//create a with 3 A's
CHARDEQUE a(3,'A');
//create b with 4 B's.
CHARDEQUE b(4,'B');
//print out the contents
print_contents (a,"a");
print_contents (b,"b");
//swap a and b
a.swap(b);
print_contents (a,"a");
print_contents (b,"b");
// let us swap it back
a.swap(b);
print_contents (a,"a");
print_contents (b,"b");
//assign the contents of b to a
a.assign(b.begin(),b.end());
file:///D|/97/c++_1/LIBREF.TXT (409 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 404 of 619
print_contents (a,"a");
//assign the first two items of b to a
a.assign(b.begin(),b.begin()+2);
print_contents (a,"a");
//assign 3 'Z's to a
a.assign(3,'Z');
print_contents (a,"a");
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" : ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The contents of a : A A A
The contents of b : B B B B
The contents of a : B B B B
The contents of b : A A A
The contents of a : A A A
The contents of b : B B B B
The contents of a : B B B B
The contents of a : B B
The contents of a : Z Z Z
deque::begin and deque::end (STL Sample)
The sample code below illustrates how to use the deque::begin and
deque::end STL functions in Visual C++.
Required Header:
< deque>
Prototype:
const_iterator begin() const;
iterator begin();
const_iterator end() const;
file:///D|/97/c++_1/LIBREF.TXT (410 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 405 of 619
iterator end();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The begin member function returns a random-access iterator that
points at the first element of the sequence, or just beyond the end
of an empty sequence. The end member function returns a random-
access iterator that points just beyond the end of the sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// begin()
// end()
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<int > INTDEQUE;
void main()
{
// Create A and fill it with elements 1,2,3,4 and 5
// using push_back function
INTDEQUE A;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
A.push_back(5);
// Print the contents of A using iterator
// and functions begin() and end()
INTDEQUE::iterator pi;
for(pi= A.begin(); pi !=A.end(); pi++)
{
cout << *pi <<" " ;
file:///D|/97/c++_1/LIBREF.TXT (411 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 406 of 619
}
cout<<endl;
}
Program Output is:
1 2 3 4 5
deque::erase and deque::clear (STL sample)
The sample code below illustrates how to use the deque::erase and
deque::clear STL functions in Visual C++.
Required Header:
< deque>
Prototype:
iterator erase(iterator iter);
iterator erase(iterator first, iterator last);
void clear() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The first erase member function removes the element of the
container pointed to by iter. The second erase member function
removes the elements of the container in the range [first, last).
Both return an iterator that designates the first element remaining
beyond any elements removed, or end() if no such element exists.
Removing N elements causes N destructor calls and an assignment for
each of the elements between the insertion point and the nearer end
of the sequence. Removing an element at either end invalidates only
iterators and references that designate the erased elements.
Otherwise, erasing an element invalidates all iterators and
references. The clear member function calls erase( begin(), end()).
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// erase
// clear
// begin
// end
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (412 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 407 of 619
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<int > INTDEQUE;
void print_contents (INTDEQUE deque);
void main()
{
// create a and with elements 1,2,3,4 and 5
INTDEQUE a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
//print the contents
print_contents (a);
// erase the second element
a.erase(a.begin()+1);
print_contents (a);
//erase the last two elements
a.erase(a.end()-2,a.end());
print_contents (a);
//clear a
a.clear();
print_contents (a);
}
void print_contents (INTDEQUE deque) {
INTDEQUE::iterator pdeque;
cout <<"The output is: ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The output is: 1 2 3 4 5
file:///D|/97/c++_1/LIBREF.TXT (413 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 408 of 619
The output is: 1 3 4 5
The output is: 1 3
The output is:
deque::front and deque::back (STL Sample)
The sample code below illustrates how to use the deque::front and
deque::back STL functions in Visual C++.
Required Header:
< deque>
Prototype:
reference front();
const_reference front() const;
reference back();
const_reference back() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The member function front returns a reference to the first element
of the controlled sequence, which must be non-empty. The member
function back returns a reference to the last element of the
controlled sequence, which must be non-empty.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// front()
//
// back()
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
file:///D|/97/c++_1/LIBREF.TXT (414 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 409 of 619
void main()
{
//create a with A, B, C and D
CHARDEQUE a;
a.push_back('A');
a.push_back('B');
a.push_back('C');
a.push_back('D');
//print out the contents
print_contents (a,"a");
cout <<"The first element of a is " <<a.front() <<endl;
cout <<"The last element of a is " <<a.back() <<endl;
//now let us modify the first and last elements
//using reference ,front() and back()
CHARDEQUE::reference reffront=a.front();
CHARDEQUE::reference refback=a.back();
reffront='X';
refback='Y';
//print out the contents
print_contents (a,"a");
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" : ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The contents of a : A B C D
The first element of a is A
The last element of a is D
The contents of a : X B C Y
file:///D|/97/c++_1/LIBREF.TXT (415 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 410 of 619
deque::insert (STL Sample)
The sample code below illustrates how to use the deque::insert STL
function in Visual C++.
Required Header:
<deque>
Prototype:
iterator insert(iterator iter, const T& x = T());
void insert(iterator iter, size_type n, const T& x);
void insert(iterator iter, const_iterator first,const_iterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
Each of these functions inserts a sequence specified by the
remaining operands after the element pointed to by iter in the
container. The first member function inserts a single element with
value x and returns an iterator that points to the newly inserted
element. The second member function inserts a repetition of n
elements of value x. The third member function inserts the sequence
[first, last).
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// insert
// begin
// end
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque);
void main()
{
file:///D|/97/c++_1/LIBREF.TXT (416 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 411 of 619
//create a with 3 A's
CHARDEQUE a(3,'A');
//create b with 2 B's.
CHARDEQUE b(2,'B');
//print out the contents
print_contents (a);
print_contents (b);
//insert 'X' to the beginning of a
a.insert(a.begin(),'X');
print_contents (a);
//insert 'Y' to the end of a
a.insert(a.end(),'Y');
print_contents (a);
//inset 3 'Z's to one item before the end of a
a.insert(a.end()-1,3,'Z');
print_contents (a);
//insert to the end of a from b
a.insert(a.end(),b.begin(),b.end());
print_contents (a);
//function to print the contents of deque
void print_contents (CHARDEQUE deque)
{
CHARDEQUE::iterator pdeque;
cout <<"The output is: ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The output is: A A A
The output is: B B
The output is: X A A A
The output is: X A A A Y
The output is: X A A A Z Z Z Y
The output is: X A A A Z Z Z Y B B
deque::operator[] and deque::at (STL Sample)
file:///D|/97/c++_1/LIBREF.TXT (417 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 412 of 619
The sample code below illustrates how to use the deque::operator[]
and deque::at STL function in Visual C++.
Required Header:
< deque>
Prototype:
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
const_reference operator[](difference_type _N) const;
reference operator[](difference_type _N) const;
const_reference at(size_type pos) const;
reference at(size_type pos);
bool empty() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The member function operator[] returns a reference to the element
of the controlled sequence at position pos. If that position is
invalid, the behavior is undefined. The member function at returns
a reference to the element of the controlled sequence at position
pos. If that position is invalid, the function throws an object of
class out_of_range. The member function empty returns true for an
empty controlled sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// operator[]
// at
// empty
// push_back
// begin
// end
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
file:///D|/97/c++_1/LIBREF.TXT (418 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 413 of 619
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
void main()
{
//create an empty deque a
CHARDEQUE a;
//check whether it is empty
if(a.empty())
cout<<"a is empty"<<endl;
else
cout<<"a is not empty"<<endl;
//inset A, B, C and D to a
a.push_back('A');
a.push_back('B');
a.push_back('C');
a.push_back('D');
//check again whether a is empty
if(a.empty())
cout<<"a is empty"<<endl;
else
cout<<"a is not empty"<<endl;
//print out the contents
print_contents (a,"a");
cout <<"The first element of a is " <<a[0] <<endl;
cout <<"The first element of a is " <<a.at(0) <<endl;
cout <<"The last element of a is " <<a[a.size()-1] <<endl;
cout <<"The last element of a is " <<a.at(a.size()-1) <<endl;
}
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" : ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
file:///D|/97/c++_1/LIBREF.TXT (419 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 414 of 619
Program Output is:
a is empty
a is not empty
The contents of a : A B C D
The first element of a is A
The first element of a is A
The last element of a is D
The last element of a is D
deque::push_back and deque::pop_back (STL Sample)
The sample code below illustrates how to use the deque::push_back
and deque::pop_back STL functions in Visual C++.
Required Header:
<deque>
Prototype:
void push_back(const T& x);
void pop_back();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The push_back function inserts an element with value x at the end
of the container deque. The pop_back function removes the last
element of the container deque, which must be non-empty.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// deque::push_back
//
// deque::pop_back
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
file:///D|/97/c++_1/LIBREF.TXT (420 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 415 of 619
typedef deque<int > INTDEQUE;
void printcontents (INTDEQUE deque);
void main()
{
INTDEQUE dequetest;
dequetest.push_back(1);
dequetest.push_back(2);
dequetest.push_back(3);
printcontents (dequetest);
dequetest.pop_back();
printcontents (dequetest);
dequetest.pop_back();
printcontents (dequetest);
}
//function to print the contents of deque
void printcontents (INTDEQUE deque)
{
INTDEQUE::iterator pdeque;
cout <<"The output is:"<<endl;
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<endl ;
}
}
Program Output is:
The output is:
1
2
3
The output is:
1
2
The output is:
1
deque::push_front, deque::pop_front (STL Sample)
The sample code below illustrates how to use the deque::push_front
and deque::pop_front STL functions in Visual C++.
Required Header:
<deque>
Prototype:
file:///D|/97/c++_1/LIBREF.TXT (421 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 416 of 619
void push_front(const T& x);
void pop_front();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The push_front function inserts an element with value x at the
beginning of the deque container. The pop_front function removes
the first element of the deque container, which must be non-empty.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// deque::push_front
// deque::pop_front
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<int > INTDEQUE;
void printcontents (INTDEQUE deque);
void main()
{
INTDEQUE dequetest;
dequetest.push_front(1);
dequetest.push_front(2);
dequetest.push_front(3);
printcontents (dequetest);
dequetest.pop_front();
printcontents (dequetest);
dequetest.pop_front();
printcontents (dequetest);
}
//function to print the contents of deque
void printcontents (INTDEQUE deque)
file:///D|/97/c++_1/LIBREF.TXT (422 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 417 of 619
{
INTDEQUE::iterator pdeque;
cout <<"The output is:"<<endl;
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<endl ;
}
}
Program Output is:
The output is:
3
2
1
The output is:
2
1
The output is:
1
deque::rbegin and deque::rend (STL Sample)
The sample code below illustrates how to use the deque::rbegin and
deque::rend STL functions in Visual C++.
Required Header:
< deque>
Prototype:
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
const_reverse_iterator rend() const;
reverse_iterator rend();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The rbegin member function returns a reverse iterator that points
just beyond the end of the controlled sequence. Therefore, it
designates the beginning of the reverse sequence. The rend member
function returns a reverse iterator that points at the first
element of the sequence, or just beyond the end of an empty
sequence. Therefore, it designates the end of the reverse sequence.
file:///D|/97/c++_1/LIBREF.TXT (423 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 418 of 619
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// rbegin
// rend
// push_back
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<int > INTDEQUE;
void main()
{
// Create A and fill it with elements 1,2,3,4 and 5
// using push_back function
INTDEQUE A;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
A.push_back(5);
// Now print the contents in reverse order using reverse_iterato
// and functions rbegin() and rend()
INTDEQUE::reverse_iterator rpi;
for(rpi= A.rbegin(); rpi !=A.rend(); rpi++)
{
cout << *rpi <<" " ;
}
cout<<endl;
}
Program Output is:
5 4 3 2 1
file:///D|/97/c++_1/LIBREF.TXT (424 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 419 of 619
deque::size and deque::resize (STL Sample)
The sample code below illustrates how to use the deque::size and
deque::resize STL functions in Visual C++.
Required Header:
<deque>
Prototype:
size_type size() const;
void resize(size_type n, T x = T());
size_type max_size() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The member function size returns the length of the controlled
sequence. The member function resize ensures that size() henceforth
returns n. If it must make the controlled sequence longer, it
appends elements with value x. If no value is supplied, the default
value depends upon the type. For example, if it is a deque of
chars, the default is a blank. If it is a deque of ints, the
default is zero. The member function max_size returns the length of
the longest sequence that the object can control.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// size
// resize
// max_size
// begin
// end
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
file:///D|/97/c++_1/LIBREF.TXT (425 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 420 of 619
void main()
{
//create a with A, B, C and D
CHARDEQUE a;
a.push_back('A');
a.push_back('B');
a.push_back('C');
a.push_back('D');
//print out the contents
print_contents (a,"a");
cout <<"max_size of a is " <<a.max_size() <<endl;
cout <<"size of a is " <<a.size() <<endl;
//let us increase the size to 10
// and set the new elements to be 'X'
a.resize(10,'X');
print_contents (a,"a");
cout <<"size of a is " <<a.size() <<endl;
//let us resize it to 5
a.resize(5);
print_contents (a,"a");
cout <<"size of a is " <<a.size() <<endl;
cout <<"max_size of a is still " <<a.max_size() <<endl;
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" : ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The contents of a : A B C D
max_size of a is 4294967295
size of a is 4
The contents of a : A B C D X X X X X X
size of a is 10
The contents of a : A B C D X
size of a is 5
file:///D|/97/c++_1/LIBREF.TXT (426 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 421 of 619
max_size of a is still 4294967295
distance (STL Sample)
The sample code below illustrates how to use the distance STL
function in Visual C++.
Required Header:
<iterator>
Prototype:
template<class Init, class Dist>
Dist distance(InIt first, InIt last, Dist& n);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
This function returns the distance between two iterators by
determining how many times the first iterator would need to be
incremented until it was equal to the last iterator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : distance.cpp
//
// Functions:
//
// distance()
////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
#pragma warning (disable:4786)
typedef vector<string > VTRLIST;
void main() {
VTRLIST Vector;
VTRLIST::iterator iVector;
VTRLIST::difference_type dTheDiff;
Vector.push_back("A1");
Vector.push_back("B2");
Vector.push_back("C3");
file:///D|/97/c++_1/LIBREF.TXT (427 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 422 of 619
Vector.push_back("D4");
Vector.push_back("E5");
Vector.push_back("F6");
Vector.push_back("G7");
// Print out the list
iVector=Vector.begin();
cout << "The list is: ";
for (int i = 0; i < 7 ; i++, iVector++)
cout << *iVector << " ";
// Initialize the iterator the first element"
iVector=Vector.begin();
cout << "\n\nAdvance to the 3rd element." << endl;
advance( iVector, 2);
cout << "The element is " << *iVector << endl;
dTheDiff = distance( Vector.begin(), iVector);
cout << "The distance from the beginning is " << dTheDiff << end
cout << "Calculate it in reverse order " << endl;
dTheDiff = distance( iVector, Vector.begin());
cout << "The distance is " << dTheDiff << endl;
cout << "\nUse distance() to count from the 3rd element to the e
<< endl;
dTheDiff = distance( iVector, Vector.end());
// Note that end() returns one past the end of the sequence
cout << "The distance is " << dTheDiff << endl;
cout <<"\nUse distance() to count the total length." << endl;
dTheDiff = distance( Vector.begin(), Vector.end() );
cout << "The total distance is " << dTheDiff << endl;
}
Program Output is:
The list is: A1 B2 C3 D4 E5 F6 G7
Advance to the 3rd element.
The element is C3
The distance from the beginning is 2
Calculate it in reverse order
The distance is -2
Use distance() to count from the 3rd element to the end.
The distance is 5
Use distance() to count the total length.
The total distance is 7
exp, log, and log10 (Sample)
The sample code below illustrates how to use the exp, log, and
log10 STL functions in Visual C++.
file:///D|/97/c++_1/LIBREF.TXT (428 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 423 of 619
Required Header:
<valarray>
Prototype:
// exp
template<class T>
valarray<T> exp(const valarray<T>& x);
// log
template<class T>
valarray<T> log(const valarray<T>& x);
// log10
template<class T>
valarray<T> log10(const valarray<T>& x);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
This article illustrates the use of the STL exp(), log(), and log10
() functions through sample code.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: None
//
// <filename> : main.cpp
//
// Functions:
//
// exp, log, log10
////////////////////////////////////////////////////////////////////
#include <iostream> // for i/o functions
#include <valarray> // for valarray
#include <math.h> // for exp(), log(), and log10()
using namespace std;
#define ARRAY_SIZE 3 // array size
typedef valarray<double> DB_VARRAY;
void main()
{
// Set val_array to contain values 1, 10, 100 for the following
DB_VARRAY val_array(ARRAY_SIZE);
for (int i = 0; i < ARRAY_SIZE; i++)
val_array[i] = pow(10, i);
file:///D|/97/c++_1/LIBREF.TXT (429 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 424 of 619
// Display the size of val_array.
cout << "Size of val_array = " << val_array.size() << "\r\n";
// Display the content of val_array before calling exp, log, and
// log10 functions.
cout << "The values in val_array:\r\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << val_array[i] << " ";
cout << "\r\n\r\n";
// rvalue_array to hold the return value from calling the sqrt()
// pow() functions.
DB_VARRAY rvalue_array;
// -------------------------------------------------------------
// exp() - display the content of rvalue_array
// -------------------------------------------------------------
rvalue_array = exp(val_array);
cout << "The result after calling exp():\r\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << "\r\n\r\n";
// -------------------------------------------------------------
// log() - display the content of rvalue_array
// -------------------------------------------------------------
rvalue_array = log(val_array);
cout << "The result after calling log():\r\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << "\r\n\r\n";
// -------------------------------------------------------------
// log10() - display the content of rvalue_array
// -------------------------------------------------------------
rvalue_array = log10(val_array);
cout << "The result after calling log10():\r\n";
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << "\r\n\r\n";
}
Program Output is:
Size of val_array = 3
The values in val_array:
1 10 100
The result after calling exp():
2.71828 22026.5 2.68812e+043
file:///D|/97/c++_1/LIBREF.TXT (430 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 425 of 619
The result after calling log():
0 2.30259 4.60517
The result after calling log10():
0 1 2
find (STL Sample)
The sample code below illustrates how to use the find STL function
in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class T> inline
InputIterator find(InputIterator first, InputIterator last, con
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The find algorithm locates the first element in the range [first,
last) that matches value and returns the iterator positioned at the
first matching element, or last + 1 if no such element exists.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// find.cpp : Illustrates how to use the find function.
//
// Functions:
//
// find - Find the first element in a sequence that matches value
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <algorithm>
#include <iostream>
using namespace std;
void main()
{
const int ARRAY_SIZE = 8 ;
file:///D|/97/c++_1/LIBREF.TXT (431 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 426 of 619
int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
int *location ; // stores the position of the first
// matching element.
int i ;
int value = 4 ;
// print content of IntArray
cout << "IntArray { " ;
for(i = 0; i < ARRAY_SIZE; i++)
cout << IntArray[i] << ", " ;
cout << " }" << endl ;
// Find the first element in the range [first, last + 1)
// that matches value.
location = find(IntArray, IntArray + ARRAY_SIZE, value) ;
//print the matching element if any was found
if (location != IntArray + ARRAY_SIZE) // matching element foun
cout << "First element that matches " << value
<< " is at location " << location - IntArray << endl;
else // no matching element w
// found
cout << "The sequence does not contain any elements"
<< " with value " << value << endl ;
}
Program Output is:
IntArray { 1, 2, 3, 4, 4, 5, 6, 7, }
First element that matches 4 is at location 3
find_if (STL Sample)
The sample code below illustrates how to use the find_if STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class T, class Predicate> inline
InputIterator find_if(InputIterator first, InputIterator last,
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The find_if algorithm locates the first element in the range
file:///D|/97/c++_1/LIBREF.TXT (432 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 427 of 619
[first, last) that causes the predicate to return true and returns
the iterator positioned at that element, or last if no such element
was found.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// findif.cpp : Illustrates how to use the find_if function.
//
// Functions:
//
// find_if - locate the first element in a range that satisfies
// a predicate.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <algorithm>
#include <iostream>
using namespace std;
// returns true if n is an odd number
int IsOdd( int n)
{
return n % 2 ;
}
void main()
{
const int ARRAY_SIZE = 8 ;
int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
int *location ; // stores the position of the first
// element that is an odd number
int i ;
// print content of IntArray
cout << "IntArray { " ;
for(i = 0; i < ARRAY_SIZE; i++)
cout << IntArray[i] << ", " ;
cout << " }" << endl ;
// Find the first element in the range [first, last -1 ]
// that is an odd number
location = find_if(IntArray, IntArray + ARRAY_SIZE, IsOdd) ;
//print the location of the first element
// that is an odd number
if (location != IntArray + ARRAY_SIZE) // first odd element fou
cout << "First odd element " << *location
<< " is at location " << location - IntArray << endl;
file:///D|/97/c++_1/LIBREF.TXT (433 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 428 of 619
else // no odd numbers in the range
cout << "The sequence does not contain any odd numbers"
<< endl ;
}
Program Output is:
IntArray { 1, 2, 3, 4, 4, 5, 6, 7, }
First odd element 1 is at location 0
for_each (STL Sample)
The sample code below illustrates how to use the for_each STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class Function> inline
Function for_each(InputIterator first, InputIterator last, Func
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The for_each algorithm calls Function F for each element in the
range [first, last) and returns the input parameter F. This
function does not modify any elements in the sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// count.cpp : Illustrates how to use the for_each function.
//
// Functions:
//
// for_each - Calls function F for every element in a range.
//
// begin - Returns an iterator that points to the first elemen
// in a sequence.
//
// end - Returns an iterator that points one past the end of
// a sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
file:///D|/97/c++_1/LIBREF.TXT (434 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 429 of 619
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// prints the cube of integer n
void PrintCube(int n)
{
cout << n * n * n << " " ;
}
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
int i ;
// Initialize vector Numbers
for (i = 0; i < VECTOR_SIZE; i++)
Numbers[i] = i + 1 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// for each element in the range [first, last)
// print the cube of the element
for_each(start, end, PrintCube) ;
cout << "\n\n" ;
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (435 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 430 of 619
Numbers { 1 2 3 4 5 6 7 8 }
1 8 27 64 125 216 343 512
Generate (STL Sample)
The sample code below illustrates how to use the Generate STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class Function> inline
Function for_each(InputIterator first, InputIterator last, Func
template<class ForwardIterator, class Generator> inline
void generate(ForwardIterator first, ForwardIterator last, Gene
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The Generate algorithm traverses the range [first, last + 1),
assigning to each element the value returned by gen. Generate
modifies the elements in the specified range.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// generate.cpp : Illustrates how to use the generate function.
//
// Functions:
//
// generate - Fill a sequence using a generator function
// Fibonacci - return the next Fibonacci number in the
// Fibonacci series.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
file:///D|/97/c++_1/LIBREF.TXT (436 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 431 of 619
// return the next Fibonacci number in the
// Fibonacci series.
int Fibonacci(void)
{
static int r;
static int f1 = 0;
static int f2 = 1;
r = f1 + f2 ;
f1 = f2 ;
f2 = r ;
return f1 ;
}
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// fill the range [first, last +1) with a series of
// Fibonnaci numbers using the Fibonacci function
generate(start, end, Fibonacci) ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Numbers { 1 1 2 3 5 8 13 21 }
generate_n (STL Sample)
The sample code below illustrates how to use the generate_n STL
function in Visual C++.
Required Header:
file:///D|/97/c++_1/LIBREF.TXT (437 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 432 of 619
<algorithm>
Prototype:
template<class OutputIterator, class Size, class Generator> inline
void generate_n(OutputIterator first, Size n, Generator gen)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The generate_n algorithm traverses the range [first, first + n),
assigning to each element the value returned by gen. Note that
generate modifies the elements in the specified range.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// generate_n.cpp : Illustrates how to use the generate_n function.
//
// Functions:
//
// generate_n - Fill a specified number of elements of a sequence
// using a generator function.
//
// begin - Returns an iterator that points to the first elem
// in a sequence.
//
// end - Returns an iterator that points one past the end
// a sequence.
//
// size - Returns the length of a sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// return the next Fibonacci number in the
// Fibonacci series.
int Fibonacci(void)
{
static int r;
static int f1 = 0;
static int f2 = 1;
file:///D|/97/c++_1/LIBREF.TXT (438 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 433 of 619
r = f1 + f2 ;
f1 = f2 ;
f2 = r ;
return f1 ;
}
void main()
{
const int VECTOR_SIZE = 15 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
int i ;
//Initialize vector Numbers
for(i = 0; i < VECTOR_SIZE; i++)
Numbers[i] = i * i ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling generate_n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// fill the specified range with a series of
// Fibonacci numbers using the Fibonacci function
generate_n(start + 5, Numbers.size() - 5, Fibonacci) ;
cout << "After calling generate_n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (439 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 434 of 619
Before calling generate_n
Numbers { 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 }
After calling generate_n
Numbers { 0 1 4 9 16 1 1 2 3 5 8 13 21 34 55 }
heap (STL Sample)
The sample code below illustrates how to use the heap STL function
in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator> inline
void make_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator> inline
void sort_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator> inline
void push_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator> inline
void pop_heap(RandomAccessIterator first, RandomAccessIterator
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
A heap is a sequence of elements organized like a binary tree. Each
heap element corresponds to a tree node. The first value in the
sequence [first..last) is the root, and is the largest value in the
heap. Every element in the heap satisfies the following: Every
element is less than or equal to its parent. The largest element is
stored in the root, and all children hold progressively smaller
values. The make_heap function converts the range [first..last)
into a heap. The sort_heap function sorts a "heapified" sequence
that was created using the make_heap function. The push_heap
function inserts a new value into the heap. The pop_heap function
swaps the first and last elements in the heap specified by [first,
last), then reduces the length of the sequence by one before
restoring the heap property. The non-predicate versions of the heap
functions use the operator< for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// heap_functions.cpp : Illustrates how to use the
file:///D|/97/c++_1/LIBREF.TXT (440 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 435 of 619
// make_heap, sort_heap, push_heap
// and pop_heap functions.
//
// Functions:
//
// make_heap : convert a sequence to a heap
// sort_heap : sort a heap
// push_heap : insert an element in a heap
// pop_heap : remove the top element from a heap
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// convert Numbers into a heap
make_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling make_heap\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (441 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 436 of 619
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the heapified sequence Numbers
sort_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling sort_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//insert an element in the heap
Numbers.push_back(7) ;
push_heap(Numbers.begin(), Numbers.end()) ;
// you need to call make_heap to re-assert the
// heap property
make_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling push_heap and make_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove the root element from the heap Numbers
pop_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling pop_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Numbers { 4 10 70 10 30 69 96 100 }
After calling make_heap
Numbers { 100 30 96 10 4 69 70 10 }
After calling sort_heap
file:///D|/97/c++_1/LIBREF.TXT (442 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 437 of 619
Numbers { 4 10 10 30 69 70 96 100 }
After calling push_heap and make_heap
Numbers { 100 69 96 30 4 70 10 10 7 }
After calling pop_heap
Numbers { 96 69 70 30 4 7 10 10 100 }
The Predicate Versions of heap (STL Sample)
The sample code below illustrates how to use the predicate versions
of the heap STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator, class Compare> inline
void make_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator, class Compare> inline
void sort_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator, class Compare> inline
void push_heap(RandomAccessIterator first, RandomAccessIterator
template<class RandomAccessIterator, class Compare> inline
void pop_heap(RandomAccessIterator first, RandomAccessIterator
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
A heap is a sequence of elements organized like a binary tree. Each
heap element corresponds to a tree node. The first value in the
sequence [first..last) is the root, and is ordered by the
predicate. For example, if the predicate is greater, every element
in the heap satisfies the following: Every element is greater than
or equal to its parent. The smallest element is stored in the root,
and all children hold progressively larger values. The make_heap
function converts the range [first..last) into a heap. The
sort_heap function sorts a "heapified" sequence that was created
using the make_heap function. The push_heap function inserts a new
value into the heap. The pop_heap function swaps the first and last
elements in the heap specified by [first, last), then reduces the
length of the sequence by one before restoring the heap property.
The predicate versions of the heap functions use the compare
function for comparisons.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (443 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 438 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// heap_functions.cpp : Illustrates how to use the predicate version
// of the make_heap, sort_heap, push_heap
// and pop_heap functions.
//
// Functions:
//
// make_heap : Convert a sequence to a heap.
// sort_heap : Sort a heap.
// push_heap : Insert an element in a heap.
// pop_heap : Remove the top element from a heap.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (444 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 439 of 619
// convert Numbers into a heap
make_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling make_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the heapified sequence Numbers
sort_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling sort_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
make_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
//insert an element in the heap
Numbers.push_back(7) ;
push_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling push_heap()\n" << endl;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//remove the root element from the heap Numbers
pop_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling pop_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Numbers { 4 10 70 10 30 69 96 100 }
After calling make_heap
Numbers { 4 10 69 10 30 70 96 100 }
After calling sort_heap
Numbers { 100 96 70 69 30 10 10 4 }
After calling push_heap()
file:///D|/97/c++_1/LIBREF.TXT (445 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 440 of 619
Numbers { 4 7 10 30 100 10 70 96 69 }
After calling pop_heap
Numbers { 7 30 10 69 100 10 70 96 4 }
includes (STL Sample)
The sample code below illustrates how to use the includes STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator1, class InputIterator2>
inline bool includes(InputIterator1 first1, InputIterator1 last
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The includes algorithm searches for one sequence of values in
another sequence of values. includes returns true if every element
in the range [first2..last2) is in the sequence [first1..last1).
This version of includes assumes that both sequences are sorted
using operator<.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// includesP.cpp : Illustrates how to use the includes function.
//
// Functions:
//
// includes - Search for one sequence in another.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include <deque>
using namespace std;
file:///D|/97/c++_1/LIBREF.TXT (446 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 441 of 619
void main()
{
const int VECTOR_SIZE = 5 ;
// Define a template class vector of strings
typedef vector<string > StringVector ;
//Define an iterator for template class vector of strings
typedef StringVector::iterator StringVectorIt ;
// Define a template class deque of strings
typedef deque<string > StringDeque ;
//Define an iterator for template class deque of strings
typedef StringDeque::iterator StringDequeIt ;
StringVector CartoonVector(VECTOR_SIZE) ;
StringDeque CartoonDeque ;
StringVectorIt start1, end1, it1 ;
StringDequeIt start2, end2, it2 ;
// Initialize vector Vector1
CartoonVector[0] = "Aladdin" ;
CartoonVector[1] = "Jasmine" ;
CartoonVector[2] = "Mickey" ;
CartoonVector[3] = "Minnie" ;
CartoonVector[4] = "Goofy" ;
start1 = CartoonVector.begin() ; // location of first
// element of CartoonVector
end1 = CartoonVector.end() ; // one past the location last
// element of CartoonVector
//Initialize list CartoonDeque
CartoonDeque.push_back("Jasmine") ;
CartoonDeque.push_back("Aladdin") ;
CartoonDeque.push_back("Goofy") ;
start2 = CartoonDeque.begin() ; // location of first
// element of CartoonDeque
end2 = CartoonDeque.end() ; // one past the location last
// element of CartoonDeque
//sort CartoonVector and CartoonDeque alphabetically
//includes requires the sequences
//to be sorted.
sort(start1, end1) ;
sort(start2, end2) ;
// print contents of CartoonVector and CartoonDeque
cout << "CartoonVector { " ;
for(it1 = start1; it1 != end1; it1++)
cout << *it1 << ", " ;
cout << " }\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (447 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 442 of 619
cout << "CartoonDeque { " ;
for(it2 = start2; it2 != end2; it2++)
cout << *it2 << ", " ;
cout << " }\n" << endl ;
//Is CartoonDeque a subset of CartoonVector?
if(includes(start1, end1, start2, end2) )
cout << "CartoonVector includes CartoonDeque"
<< endl ;
else
cout << "CartoonVector does not include CartoonDeque"
<< endl ;
Program Output is:
CartoonVector { Aladdin, Goofy, Jasmine, Mickey, Minnie, }
CartoonDeque { Aladdin, Goofy, Jasmine, }
CartoonVector includes CartoonDeque
Predicate Version of includes (STL Sample)
The sample code below illustrates how to use the predicate version
of the includes STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator1, class InputIterator2, class Compare>
inline bool includes(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The includes algorithm searches for one sequence of values in
another sequence of values. includes returns true if every element
in the range [first2..last2) is in the sequence [first1..last1).
This version of includes assumes that both sequences are sorted
using the compare function.
Sample Code:
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (448 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 443 of 619
//
// Compile options needed: /GX
//
// includesP.cpp : Illustrates how to use the predicate version of
// includes function.
//
// Functions:
//
// includes - Search for one sequence in another.
// string_compare - Compare strings, return true if
// s1 < s2.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include <deque>
using namespace std ;
bool string_compare(const string& s1, const string& s2)
{
return s1 < s2 ? 1 : 0;
}
void main()
{
const int VECTOR_SIZE = 5 ;
// Define a template class vector of strings
typedef vector<string> StringVector ;
//Define an iterator for template class vector of strings
typedef StringVector::iterator StringVectorIt ;
// Define a template class deque of strings
typedef deque<string> StringDeque ;
//Define an iterator for template class deque of strings
typedef StringDeque::iterator StringDequeIt ;
StringVector CartoonVector(VECTOR_SIZE) ;
StringDeque CartoonDeque ;
StringVectorIt start1, end1, it1 ;
StringDequeIt start2, end2, it2 ;
// Initialize vector Vector1
CartoonVector[0] = "Aladdin" ;
CartoonVector[1] = "Jasmine" ;
CartoonVector[2] = "Mickey" ;
CartoonVector[3] = "Minnie" ;
file:///D|/97/c++_1/LIBREF.TXT (449 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 444 of 619
CartoonVector[4] = "Goofy" ;
start1 = CartoonVector.begin() ; // location of first
// element of CartoonVector
end1 = CartoonVector.end() ; // one past the location last
// element of CartoonVector
//Initialize list CartoonDeque
CartoonDeque.push_back("Jasmine") ;
CartoonDeque.push_back("Aladdin") ;
CartoonDeque.push_back("Goofy") ;
start2 = CartoonDeque.begin() ; // location of first
// element of CartoonDeque
end2 = CartoonDeque.end() ; // one past the location last
// element of CartoonDeque
//sort CartoonVector and CartoonDeque alphabetically
//includes requires the sequences
//to be sorted.
sort(start1, end1, string_compare) ;
sort(start2, end2, string_compare) ;
// print contents of CartoonVector and CartoonDeque
cout << "CartoonVector { " ;
for(it1 = start1; it1 != end1; it1++)
cout << *it1 << ", " ;
cout << " }\n" << endl ;
cout << "CartoonDeque { " ;
for(it2 = start2; it2 != end2; it2++)
cout << *it2 << ", " ;
cout << " }\n" << endl ;
//Is CartoonDeque a subset of CartoonVector?
if(includes(start1, end1, start2, end2, string_compare) )
cout << "CartoonVector includes CartoonDeque"
<< endl ;
else
cout << "CartoonVector does not include CartoonDeque"
<< endl ;
Program Output is:
CartoonVector { Aladdin, Goofy, Jasmine, Mickey, Minnie, }
CartoonDeque { Aladdin, Goofy, Jasmine, }
CartoonVector includes CartoonDeque
inner_product (STL Sample)
file:///D|/97/c++_1/LIBREF.TXT (450 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 445 of 619
The sample code below illustrates how to use the inner_product STL
function in Visual C++.
Required Header:
<numeric>
Prototype:
template<class InputIterator1, class InputIterator2, class T>
inline T inner_product(InputIterator first, InputIterator last,
template<class InputIterator1, class InputIterator2, class T, class
inline T inner_product(InputIterator1 first, InputIterator1 las
T init, BinOp1 binary_op1, BinOp2 binary_op2)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
inner_product computes its result by initializing the accumulator
acc with init and then modifying it with: acc = acc + (*i1) * (*i2)
- or - acc = binary_op1(acc, binary_op2(*i1, *i2)) for every
iterator i1 in the range [first, last) and iterator i2 in the range
[first2, first2 + (last - first)) in order.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// inner_product.cpp : Demonstrates the use of inner_product().
//
// Description of
// inner_product(first,last,first2,init)
// inner_product(first,last,first2,init,binary_op1,binary_op
//
// Computes its result by initializing the accumulator acc with i
// acc = init
// and then modifying it with
// acc = acc + (*i1) * (*i2)
// or
// acc = binary_op1(acc, binary_op2(*i1, *i2))
// for every iterator i1 in the range [first, last) and
// iterator i2 in the range [first2, first2 + (last - first))
// in order.
////////////////////////////////////////////////////////////////////
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
file:///D|/97/c++_1/LIBREF.TXT (451 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 446 of 619
using namespace std;
typedef vector < float > FloatArray;
typedef ostream_iterator < float, char, char_traits<char> >
FloatOstreamIt;
void main ()
{
FloatOstreamIt itOstream(cout," ");
// Initialize the arrays
FloatArray rgF1, rgF2;
for (int i=1; i<=5; i++) {
rgF1.push_back(i);
rgF2.push_back(i*i);
};
// Print the arrays
cout << "Array 1: ";
copy(rgF1.begin(),rgF1.end(),itOstream);
cout << endl;
cout << "Array 2: ";
copy(rgF2.begin(),rgF2.end(),itOstream);
cout << endl;
// Compute the inner_product of the arrays. This is the
// sum of the products (S.O.P) of the corresponding elements
float ip1 = inner_product(rgF1.begin(),rgF1.end(),rgF2.begin(),0
cout << "The inner product (S.O.P) of Array1 and Array2 is "
<< ip1
<< endl;
// Compute the inner_product of the arrays. This is the
// product of the sums (P.O.S.) of the corresponding elements
float ip2 = inner_product(rgF1.begin(),rgF1.end(),rgF2.begin(),1
multiplies<float>(),plus<float>());
cout << "The inner product (P.O.S.) of Array1 and Array2 is "
<< ip2
<< endl;
}
Program Output is:
Array 1: 1 2 3 4 5
Array 2: 1 4 9 16 25
The inner product (S.O.P) of Array1 and Array2 is 225
The inner product (P.O.S.) of Array1 and Array2 is 86400
inplace_merge (STL Sample)
The sample code below illustrates how to use the inplace_merge STL
function in Visual C++.
Required Header:
file:///D|/97/c++_1/LIBREF.TXT (452 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 447 of 619
<algorithm>
Prototype:
template<class BidirectionalIterator>
inline void inplace_merge(BidirectionalIterator first, Bidirect
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The inplace_merge algorithm merges two sorted sub-sequences:
[first..middle) and [middle..last) in place into a single sorted
sequence [first..last). This version assumes that the ranges
[first..middle) and [middle..last) are sorted using operator<. If
both ranges contain equal values, the value from the first range
will be stored first.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// inplace_merge.cpp : Illustrates how to use the inplace_merge
// function.
//
// Functions:
//
// inplace_merge : Merge two sorted sub-sequences in place into a
// single sorted list.
//
// begin - Returns an iterator that points to the first element in
// sequence.
//
// end - Returns an iterator that points one past the end of a seq
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
file:///D|/97/c++_1/LIBREF.TXT (453 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 448 of 619
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//merge the elements of Numbers in place
inplace_merge(start, start + 3, end) ;
cout << "After calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling inplace_merge
Numbers { 4 10 70 10 30 69 96 100 }
After calling inplace_merge
Numbers { 4 10 10 30 69 70 96 100 }
file:///D|/97/c++_1/LIBREF.TXT (454 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 449 of 619
Predicate Version of inplace_merge (STL Sample)
The sample code below illustrates how to use the predicate version
of the inplace_merge STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator, class Compare> inline
void inplace_merge(BidirectionalIterator first, BidirectionalIt
BidirectionalIterator last, Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The inplace_merge algorithm merges two sorted sub-sequences:
[first..middle) and [middle..last) in place into a single sorted
sequence [first..last). This version assumes that the ranges
[first..middle) and [middle..last) are sorted using the compare
function. If both ranges contain equal values, the value from the
first range will be stored first.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// inplace_mergeP.cpp : Illustrates how to use the predicate version
// the inplace_merge function.
//
// Functions:
//
// inplace_merge - Merge two sorted sub-sequences in place into a
// single sorted list using the compare function.
//
// begin - Returns an iterator that points to the first element i
// sequence.
// end - Returns an iterator that points one past the end of a se
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
file:///D|/97/c++_1/LIBREF.TXT (455 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 450 of 619
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//merge the elements of Numbers in place
inplace_merge(start, start + 3, end, less<int>()) ;
cout << "After calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (456 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 451 of 619
Before calling inplace_merge
Numbers { 4 10 70 10 30 69 96 100 }
After calling inplace_merge
Numbers { 4 10 10 30 69 70 96 100 }
iter_swap (STL Sample)
The sample code below illustrates how to use the iter_swap STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator1, class ForwardIterator2> inline
void iter_swap(ForwardIterator1 first, ForwardIterator2 second)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The iter_swap algorithm swaps two elements represented by two
iterators.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// iter_swap.cpp : Illustrates how to use the iter_swap function.
//
// Functions:
//
// iter_swap - Swap two elements in a sequence represented by
// two iterators.
//
// begin - Returns an iterator that points to the first eleme
// in a sequence.
//
// end - Returns an iterator that points one past the end o
// a sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
file:///D|/97/c++_1/LIBREF.TXT (457 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 452 of 619
#include <algorithm>
using namespace std;
// return the next Fibonacci number in the
// Fibonacci series.
int Fibonacci(void)
{
static int r;
static int f1 = 0;
static int f2 = 1;
r = f1 + f2 ;
f1 = f2 ;
f2 = r ;
return f1 ;
}
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// fill the range [first, last +1) with a series of
// Fibonacci numbers using the Fibonacci function
generate(start, end, Fibonacci) ;
cout << "Before calling iter_swap" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// swap the first and last elements of the
// sequence using iter_swap
iter_swap(start, end - 1) ;
cout << "After calling iter_swap" << endl ;
// print content of Numbers
file:///D|/97/c++_1/LIBREF.TXT (458 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 453 of 619
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Before calling iter_swap
Numbers { 1 1 2 3 5 8 13 21 }
After calling iter_swap
Numbers { 21 1 2 3 5 8 13 1 }
list::assign (STL Sample)
The sample code below illustrates how to use the list::assign STL
function in Visual C++.
Required Header:
<list>
Prototype:
void assign(const_iterator first, const_iterator last);
void assign(size_type n, const T& x = T());
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
bool empty() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The first member function replaces the sequence controlled by *this
with the sequence [first, last). The second member function
replaces the sequence controlled by *this with a repetition of n
elements of value x. The third member function removes the element
of the controlled sequence pointed to by it. The fourth member
function removes the elements of the controlled sequence in the
range [first, last). Both return an iterator that designates the
first element remaining beyond any elements removed, or end() if no
such element exists. The last member function returns true for an
empty controlled sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// assign.cpp : Shows the various ways to assign and erase elements
file:///D|/97/c++_1/LIBREF.TXT (459 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 454 of 619
// from a list<T>.
//
// Functions:
//
// list::assign
// list::empty
// list::erase
////////////////////////////////////////////////////////////////////
#include <list>
#include <iostream>
using namespace std ;
typedef list<int> LISTINT;
void main()
{
LISTINT listOne;
LISTINT listAnother;
LISTINT::iterator i;
// Add some data
listOne.push_front (2);
listOne.push_front (1);
listOne.push_back (3);
listAnother.push_front(4);
listAnother.assign(listOne.begin(), listOne.end());
// 1 2 3
for (i = listAnother.begin(); i != listAnother.end(); ++i)
cout << *i << " ";
cout << endl;
listAnother.assign(4, 1);
// 1 1 1 1
for (i = listAnother.begin(); i != listAnother.end(); ++i)
cout << *i << " ";
cout << endl;
listAnother.erase(listAnother.begin());
// 1 1 1
for (i = listAnother.begin(); i != listAnother.end(); ++i)
cout << *i << " ";
cout << endl;
listAnother.erase(listAnother.begin(), listAnother.end());
if (listAnother.empty())
cout << "All gone\n";
}
file:///D|/97/c++_1/LIBREF.TXT (460 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 455 of 619
Program Output is:
1 2 3
1 1 1 1
1 1 1
All gone
list::back, list::front (STL Sample)
The sample code below illustrates how to use the list::back and
list::front STL functions in Visual C++.
Required Header:
<list>
Prototype:
reference back();
const_reference back() const;
reference front();
const_reference front() const;
void pop_back();
void pop_front();
void push_back(const T& x);
void push_front(const T& x);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The member function back returns a reference to the last element of
the controlled sequence. The member function front returns a
reference to the first element of the controlled sequence. The
member function pop_back removes the last element of the controlled
sequence. The member function pop_front removes the first element
of the controlled sequence. All the above functions require that
the controlled sequence be non-empty. The member function push_back
inserts an element with value x at the end of the controlled
sequence. The member function push_front inserts an element with
value x at the beginning of the controlled sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// liststck.cpp : This example shows how to use the various stack
// like functions of list.
//
// Functions:
//
// list::back
// list::front
file:///D|/97/c++_1/LIBREF.TXT (461 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 456 of 619
// list::pop_back
// list::pop_front
// list::push_back
// list::push_front
////////////////////////////////////////////////////////////////////
#include <list>
#include <string>
#include <iostream>
using namespace std ;
typedef list<string> LISTSTR;
void main()
{
LISTSTR test;
test.push_back("back");
test.push_front("middle");
test.push_front("front");
// front
cout << test.front() << endl;
// back
cout << test.back() << endl;
test.pop_front();
test.pop_back();
// middle
cout << test.front() << endl;
}
Program Output is:
front
back
middle
list::insert (STL Sample)
The sample code below illustrates how to use the list::insert STL
function in Visual C++.
Required Header:
<list>
Prototype:
iterator insert(iterator it, const T& x = T());
void insert(iterator it, size_type n, const T& x);
void insert(iterator it, const_iterator first, const_iterator l
file:///D|/97/c++_1/LIBREF.TXT (462 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 457 of 619
void insert(iterator it, const T *first, const T *last);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
Each of the member functions inserts, after the element pointed to
by it in the controlled sequence, a sequence specified by the
remaining operands. The first member function inserts a single
element with value x and returns an iterator that points to the
newly inserted element. The second member function inserts a
repetition of n elements of value x. The last two member functions
insert the sequence [first, last).
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// insert.cpp : Shows the various ways to insert elements into a
// list<T>.
//
// Functions:
//
// list::insert
////////////////////////////////////////////////////////////////////
#include <list>
#include <iostream>
using namespace std ;
typedef list<int> LISTINT;
void main()
{
int rgTest1[] = {5,6,7};
int rgTest2[] = {10,11,12};
LISTINT listInt;
LISTINT listAnother;
LISTINT::iterator i;
// Insert one at a time
listInt.insert (listInt.begin(), 2);
listInt.insert (listInt.begin(), 1);
listInt.insert (listInt.end(), 3);
// 1 2 3
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << *i << " ";
cout << endl;
// Insert 3 fours
listInt.insert (listInt.end(), 3, 4);
file:///D|/97/c++_1/LIBREF.TXT (463 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 458 of 619
// 1 2 3 4 4 4
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << *i << " ";
cout << endl;
// Insert an array in there
listInt.insert (listInt.end(), rgTest1, rgTest1 + 3);
// 1 2 3 4 4 4 5 6 7
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << *i << " ";
cout << endl;
// Insert another LISTINT
listAnother.insert (listAnother.begin(), rgTest2, rgTest2+3);
listInt.insert (listInt.end(), listAnother.begin(), listAnother.
// 1 2 3 4 4 4 5 6 7 10 11 12
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << *i << " ";
cout << endl;
}
Program Output is:
1 2 3
1 2 3 4 4 4
1 2 3 4 4 4 5 6 7
1 2 3 4 4 4 5 6 7 10 11 12
list::list (STL Sample)
The sample code below illustrates how to use the list::list STL
function in Visual C++.
Required Header:
<list>
Prototype:
explicit list(const A& al = A());
explicit list(size_type n, const T& v = T(), const A& al = A())
list(const list& x);
list(const_iterator first, const_iterator last, const A& al = A
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The first constructor specifies an empty initial controlled
sequence. The second constructor specifies a repetition of n
elements of value x. The third constructor specifies a copy of the
file:///D|/97/c++_1/LIBREF.TXT (464 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 459 of 619
sequence controlled by x. The last constructor specifies the
sequence [first, last). All constructors store the allocator object
'al', or for the copy constructor, the return value of
'x.get_allocator()', in the data member 'allocator' and initialize
the controlled sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// list.cpp : demonstrates the different constructors for list<T>
//
// Functions:
//
// list::list
////////////////////////////////////////////////////////////////////
#include <list>
#include <string>
#include <iostream>
using namespace std ;
typedef list<string> LISTSTR;
// Try each of the four constructors
void main()
{
LISTSTR::iterator i;
LISTSTR test; // default constructor
test.insert(test.end(), "one");
test.insert(test.end(), "two");
LISTSTR test2(test); // construct from another list
LISTSTR test3(3, "three"); // add several <T>'s
LISTSTR test4(++test3.begin(), // add part of another list
test3.end());
// Print them all out
// one two
for (i = test.begin(); i != test.end(); ++i)
cout << *i << " ";
cout << endl;
// one two
for (i = test2.begin(); i != test2.end(); ++i)
cout << *i << " ";
cout << endl;
// three three three
for (i = test3.begin(); i != test3.end(); ++i)
cout << *i << " ";
cout << endl;
file:///D|/97/c++_1/LIBREF.TXT (465 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 460 of 619
// three three
for (i = test4.begin(); i != test4.end(); ++i)
cout << *i << " ";
cout << endl;
}
Program Output is:
one two
one two
three three three
three three
lower_bound (STL Sample)
The sample code below illustrates how to use the lower_bound STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class T>
inline ForwardIterator lower_bound(ForwardIterator first, Forwa
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The lower_bound algorithm returns the first location in the
sequence that value can be inserted such that the order of the
sequence is maintained. lower_bound returns an iterator positioned
at the location that value can be inserted in the range
[first..last), or returns last if no such position exists.
lower_bound assumes the range [first..last) is sorted using
operator<.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// lower_bound.cpp : Illustrates how to use the lower_bound
// function.
//
// Functions:
//
// lower_bound : Return the lower bound within a range.
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (466 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 461 of 619
// disable warning C4786: symbol greater than 255 character,
// okay to ignore this warning
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// return the first location at which 10 can be inserted
// in Numbers
location = lower_bound(start, end, 10) ;
cout << "First location element 10 can be inserted in Numbers is
<< location - start << endl ;
}
file:///D|/97/c++_1/LIBREF.TXT (467 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 462 of 619
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
First location element 10 can be inserted in Numbers is: 1
Predicate Version of lower_bound (STL Sample)
The sample code below illustrates how to use the the predicate
version of the lower_bound STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class T, class Compare>
inline ForwardIterator lower_bound(ForwardIterator first, Forwa
const T& value, Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The lower_bound algorithm returns the first location in the
sequence that value can be inserted such that the order of the
sequence is maintained. lower_bound returns an iterator positioned
at the location that value can be inserted in the range
[first..last), or returns last if no such position exists. This
version assumes the range [first..last) is sorted sequentially
using the compare function.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// lower_bound.cpp : Illustrates how to use the lower_bound
// function.
//
// Functions:
//
// lower_bound : Return the lower bound within a range.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore this warning
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
file:///D|/97/c++_1/LIBREF.TXT (468 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 463 of 619
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//sort Numbers using the function object less<int>()
//lower_bound assumes that Numbers is sorted
//using the "compare" (less<int>() in this case)
//function
sort(start, end, less<int>()) ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// return the first location at which 10 can be inserted
// in Numbers
location = lower_bound(start, end, 10, less<int>()) ;
cout << "First location element 10 can be inserted in Numbers is
<< location - start << endl ;
}
file:///D|/97/c++_1/LIBREF.TXT (469 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 464 of 619
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
First location element 10 can be inserted in Numbers is: 1
make_pair (STL Sample)
The sample code below illustrates how to use the make_pair STL
function in Visual C++.
Required Header:
<utility>
Prototype:
template<class first, class second> inline
pair<first, second> make_pair(const first& _X, const second& _Y
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The make_pair function creates a pair structure that contains two
data elements of any type.
Sample Code:
////////////////////////////////////////////////////////////////////
// Compile options needed: none
//
// mkpair.cpp: Illustrates how to use the make_pair function.
//
// Functions: make_pair - creates an object pair containing two data
// elements of any type.
////////////////////////////////////////////////////////////////////
/* Compiler options needed: none
*/
#include <utility>
#include <iostream>
using namespace std;
/* STL pair data type containing int and float
*/
typedef struct pair<int,float> PAIR_IF;
void main(void)
{
PAIR_IF pair1=make_pair(18,3.14f);
file:///D|/97/c++_1/LIBREF.TXT (470 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 465 of 619
cout << pair1.first << " " << pair1.second << endl;
pair1.first=10;
pair1.second=1.0f;
cout << pair1.first << " " << pair1.second << endl;
}
Program Output is:
18 3.14
10 1
map::insert, map::find, and map::end (STL Sample)
The sample code below illustrates how to use the map::insert,
map::find, and map::end STL functions in Visual C++.
Required Header:
<map>
Prototype:
iterator map::end();
// Key is the data type of template argument #1 for map
iterator map::find(const Key& key);
pair<iterator, bool> map::insert(const value_type& x);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The end() function returns an iterator that points one past the end
of a sequence. Find returns an iterator that designates the first
element whose sort key equals key. If no such element exists, the
iterator equals end(). If the key does not already exist, insert
will add it to the sequence and return pair<iterator, true>. If the
key already exists, insert does not add it to the sequence and
returns pair <iterator, false>. The following sample creates a map
of ints to strings. In this case, the mapping is from digits to
their string equivalents (1 -> "One", 2 -> "Two", etc.). The
program reads a number from the user, finds the word equivalent for
each digit (using the map), and prints the number back as a series
of words. For example, if the user enters 25463, the program
responds with: Two Five Four Six Three.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: None
//
file:///D|/97/c++_1/LIBREF.TXT (471 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 466 of 619
// <filename> : main.cpp
//
// Functions:
//
// end
// find
// insert
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef map<int, string, less<int> > INT2STRING;
void main()
{
// 1. Create a map of ints to strings
INT2STRING theMap;
INT2STRING::iterator theIterator;
string theString = "";
int index;
// Fill it with the digits 0 - 9, each mapped to its string counterp
// Note: value_type is a pair for maps...
theMap.insert(INT2STRING::value_type(0,"Zero"));
theMap.insert(INT2STRING::value_type(1,"One"));
theMap.insert(INT2STRING::value_type(2,"Two"));
theMap.insert(INT2STRING::value_type(3,"Three"));
theMap.insert(INT2STRING::value_type(4,"Four"));
theMap.insert(INT2STRING::value_type(5,"Five"));
theMap.insert(INT2STRING::value_type(6,"Six"));
theMap.insert(INT2STRING::value_type(7,"Seven"));
theMap.insert(INT2STRING::value_type(8,"Eight"));
theMap.insert(INT2STRING::value_type(9,"Nine"));
// Read a Number from the user and print it back as words
for( ; ; )
{
cout << "Enter \"q\" to quit, or enter a Number: ";
cin >> theString;
if(theString == "q")
break;
// extract each digit from the string, find its correspondin
// entry in the map (the word equivalent) and print it
for(index = 0; index < theString.length(); index++){
theIterator = theMap.find(theString[index] - '0');
if(theIterator != theMap.end() ) // is 0 - 9
cout << (*theIterator).second << " ";
else // some character other than 0 - 9
cout << "[err] ";
}
file:///D|/97/c++_1/LIBREF.TXT (472 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 467 of 619
cout << endl;
}
}
Program Output is:
Enter "q" to quit, or enter a Number: 22
Two Two
Enter "q" to quit, or enter a Number: 33
Three Three
Enter "q" to quit, or enter a Number: 456
Four Five Six
Enter "q" to quit, or enter a Number: q
Non-Predicate Version of max_element (STL Sample)
The sample code below illustrates how to use the non-predicate
version of the max_element STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator>
inline InputIterator max_element(InputIterator first, InputIter
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The max_element algorithm returns the location of the maximum
element in the sequence [first, last). The non-predicate version of
max_element uses operator< for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// max_element.cpp : Illustrates how to use the max_element
// function.
//
// Functions:
//
// max_element : Return the maximum element within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
file:///D|/97/c++_1/LIBREF.TXT (473 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 468 of 619
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// return the maximum element in the Numbers
location = max_element(start, end) ;
cout << "The maximum element in Numbers is: "
<< *location << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
file:///D|/97/c++_1/LIBREF.TXT (474 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 469 of 619
The maximum element in Numbers is: 100
Predicate Version of max_element (STL Sample)
The sample code below illustrates how to use the predicate version
of the max_element STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class Compare> inline
InputIterator max_element(InputIterator first, InputIterator la
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The max_element algorithm returns the location of the maximum
element in the sequence [first, last). The predicate version of
max_element uses the compare function for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// max_element.cpp : Illustrates how to use the predicates version
// of the max_element function.
//
// Functions:
//
// max_element : Return the maximum element within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
file:///D|/97/c++_1/LIBREF.TXT (475 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 470 of 619
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// return the maximum element in the Numbers
location = max_element(start, end, less<int>()) ;
cout << "The maximum element in Numbers is: "
<< *location << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
The maximum element in Numbers is: 100
map::max_size, clear, erase, size (STL Sample)
The sample code below illustrates how to use the map::max_size,
clear, erase, and size STL functions in Visual C++.
Required Header:
<map>
Prototype:
size_type max_size() const;
file:///D|/97/c++_1/LIBREF.TXT (476 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 471 of 619
void clear() const;
bool empty() const;
iterator erase(iterator first, iterator last);
size_type size() const;
A::reference operator[](const Key& key); // A is the allocat
iterator map::begin();
iterator map::end();
iterator map::find(const Key& key);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The following sample creates a map of strings to ints and fills it
first with a map of month names to month numbers, then empties and
refills it with a map of weekday names to corresponding ints.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: None
//
// <filename> : main.cpp
//
// Functions: iterator map::max_size();
// void clear() const;
// bool empty() const;
// iterator erase(iterator first, iterator last);
// size_type size() const;
// A::reference operator[](const Key& key);
// iterator map::begin();
// iterator map::end();
// iterator map::find(const Key& key);
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
using namespace std ;
typedef map<string, int> STRING2INT;
void main()
{
STRING2INT MyMap;
STRING2INT::iterator MyIterator;
string MyBuffer;
// print the maximum number of <key,data> pairs that MyMap can h
cout << "MyMap is capable of holding " << MyMap.max_size()
<< " <string,int> pairs" << endl;
file:///D|/97/c++_1/LIBREF.TXT (477 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 472 of 619
if(!MyMap.empty())
cout << "MyMap has " << MyMap.size() << " entries" << endl;
else
cout << "MyMap is empty" << endl;
cout << "Entering new entries in MyMap" << endl;
// Fill in MyMap with the months of the year, mapped to their nu
// January - 1, February - 2, etc. using operator[].
MyMap["January"] = 1;
MyMap["February"] = 2;
MyMap["March"] = 3;
MyMap["April"] = 4;
MyMap["May"] = 5;
MyMap["June"] = 6;
MyMap["July"] = 7;
MyMap["August"] = 8;
MyMap["September"] = 9;
MyMap["October"] = 10;
MyMap["November"] = 11;
MyMap["December"] = 12;
if(!MyMap.empty())
cout << "MyMap has " << MyMap.size() << " entries" << endl;
else
cout << "MyMap is empty" << endl;
// Ask the user for a month of the year and print the number
// that corresponds to the month entered
//MyIterator = MyMap.end();
while(MyIterator == MyMap.end()){
cout << "Enter a Month :";
cin >> MyBuffer;
if((MyIterator = MyMap.find(MyBuffer)) != MyMap.end())
cout << (*MyIterator).first << " is Month Number "
<< (*MyIterator).second << endl;
else
cout << "Enter a Valid Month (example: March)" << endl;
}
// empty MyMap - note that clear simply calls erase(begin(),end(
MyMap.clear();
if(!MyMap.empty())
cout << "MyMap has " << MyMap.size() << " entries" << endl;
else
cout << "MyMap is empty" << endl;
cout << "Entering new entries in MyMap" << endl;
// Fill MyMap with the days of the week, each mapped to an int
MyMap["Monday"] = 1;
MyMap["Tuesday"] = 2;
MyMap["Wednesday"] = 3;
MyMap["Thursday"] = 4;
MyMap["Friday"] = 5;
MyMap["Saturday"] = 6;
MyMap["Sunday"] = 7;
if(!MyMap.empty())
cout << "MyMap has " << MyMap.size() << " entries" << endl;
file:///D|/97/c++_1/LIBREF.TXT (478 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 473 of 619
else
cout << "MyMap is empty" << endl;
// Ask the user for a day of the week and print the number
// that corresponds to the day entered
MyIterator = MyMap.end();
while(MyIterator == MyMap.end()){
cout << "Enter a Day of the Week:";
cin >> MyBuffer;
if((MyIterator = MyMap.find(MyBuffer)) != MyMap.end())
cout << (*MyIterator).first << " is Day Number "
<< (*MyIterator).second << endl;
else
cout <<"Enter a Valid Day of the Week(example: Monday)"<
}
// Now clear MyMap again - this time using erase instead of clear
MyMap.erase(MyMap.begin(), MyMap.end());
if(!MyMap.empty())
cout << "MyMap has " << MyMap.size() << " entries" << endl;
else
cout << "MyMap is empty" << endl;
Program Output is:
MyMap is capable of holding 1073741823 <string,int> pairs
MyMap is empty
Entering new entries in MyMap
MyMap has 12 entries
Enter a Month :[April]
April is Month Number 4
MyMap is empty
Entering new entries in MyMap
MyMap has 7 entries
Enter a Day of the Week:[Friday]
Enter a Valid Day of the Week(example: Monday)
Enter a Day of the Week:[Friday]
Friday is Day Number 5
MyMap is empty
merge (STL Sample)
The sample code below illustrates how to use the merge STL function
in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator1,
class InputIterator2,
file:///D|/97/c++_1/LIBREF.TXT (479 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 474 of 619
class OutputIterator> inline
OutputIterator merge( InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2
OutputIterator result )
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The merge algorithm merges two sorted sequences: [first1..last1)
and [first2..last2) into a single sorted sequence starting at
result. This version assumes that the ranges [first1..last1) and
[first2..last2) are sorted using operator<. If both ranges contain
equal values, the value from the first range will be stored first.
The result of merging overlapping ranges is undefined.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// merge.cpp : Illustrates how to use the merge
// function.
//
// Functions:
//
// merge : Merge two sorted sequences
// into a single sorted list.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>
using namespace std ;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of ints
typedef IntVector::iterator IntVectorIt ;
IntVector NumbersVector(MAX_ELEMENTS) ;
file:///D|/97/c++_1/LIBREF.TXT (480 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 475 of 619
IntVectorIt startv, endv, itv ;
// Define a template class list of int
typedef list<int> IntList ;
//Define an iterator for template class list of ints
typedef IntList::iterator IntListIt ;
IntList NumbersList ;
IntListIt first, last, itl ;
// Define a template class deque of int
typedef deque<int> IntDeque ;
//Define an iterator for template class deque of ints
typedef IntDeque::iterator IntDequeIt ;
IntDeque NumbersDeque(2 * MAX_ELEMENTS) ;
IntDequeIt itd ;
// Initialize vector NumbersVector
NumbersVector[0] = 4 ;
NumbersVector[1] = 10;
NumbersVector[2] = 70 ;
NumbersVector[3] = 10 ;
NumbersVector[4] = 30 ;
NumbersVector[5] = 69 ;
NumbersVector[6] = 96 ;
NumbersVector[7] = 100;
startv = NumbersVector.begin() ; // location of first
// element of NumbersVector
endv = NumbersVector.end() ; // one past the location
// last element of NumbersVector
// sort NumbersVector, merge requires the sequences
// to be sorted
sort(startv, endv) ;
// print content of NumbersVector
cout << "NumbersVector { " ;
for(itv = startv; itv != endv; itv++)
cout << *itv << " " ;
cout << " }\n" << endl ;
// Initialize vector NumbersList
for(int i = 0; i < MAX_ELEMENTS; i++)
NumbersList.push_back(i) ;
first = NumbersList.begin() ; // location of first
// element of NumbersList
last = NumbersList.end() ; // one past the location
file:///D|/97/c++_1/LIBREF.TXT (481 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 476 of 619
// last element of NumbersList
// print content of NumbersList
cout << "NumbersList { " ;
for(itl = first; itl != last; itl++)
cout << *itl << " " ;
cout << " }\n" << endl ;
// merge the elements of NumbersVector
// and NumbersList and place the
// results in NumbersDeque
merge(startv, endv, first, last, NumbersDeque.begin()) ;
cout << "After calling merge\n" << endl ;
// print content of NumbersDeque
cout << "NumbersDeque { " ;
for(itd = NumbersDeque.begin();
itd != NumbersDeque.end(); itd++)
cout << *itd << " " ;
cout << " }\n" << endl ;
}
Program Output is:
NumbersVector { 4 10 10 30 69 70 96 100 }
NumbersList { 0 1 2 3 4 5 6 7 }
After calling merge
NumbersDeque { 0 1 2 3 4 4 5 6 7 10 10 30 69 70 96 100 }
Predicate Version of merge (STL Sample)
The sample code below illustrates how to use the predicate version
of the merge STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator1,
class InputIterator2,
class OutputIterator
class Compare> inline
OutputIterator merge( InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2
OutputIterator result,
Compare compare )
file:///D|/97/c++_1/LIBREF.TXT (482 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 477 of 619
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The merge algorithm merges two sorted sequences: [first1..last1)
and [first2..last2) into a single sorted sequence starting at
result. This version assumes that the ranges [first1..last1) and
[first2..last2) are sorted using the compare function. If both
ranges contain equal values, the value from the first range will be
stored first. The result of merging overlapping ranges is
undefined.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// merge.cpp : Illustrates how to use predicate version of the merge
// function.
//
// Functions:
//
// merge : Merge two sorted sequences
// into a single sorted list.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>
using namespace std ;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of ints
typedef IntVector::iterator IntVectorIt ;
IntVector NumbersVector(MAX_ELEMENTS) ;
IntVectorIt startv, endv, itv ;
// Define a template class list of int
typedef list<int> IntList ;
file:///D|/97/c++_1/LIBREF.TXT (483 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 478 of 619
//Define an iterator for template class list of ints
typedef IntList::iterator IntListIt ;
IntList NumbersList ;
IntListIt first, last, itl ;
// Define a template class deque of int
typedef deque<int> IntDeque ;
//Define an iterator for template class deque of ints
typedef IntDeque::iterator IntDequeIt ;
IntDeque NumbersDeque(2 * MAX_ELEMENTS) ;
IntDequeIt itd ;
// Initialize vector NumbersVector
NumbersVector[0] = 4 ;
NumbersVector[1] = 10;
NumbersVector[2] = 70 ;
NumbersVector[3] = 10 ;
NumbersVector[4] = 30 ;
NumbersVector[5] = 69 ;
NumbersVector[6] = 96 ;
NumbersVector[7] = 100;
startv = NumbersVector.begin() ; // location of first
// element of NumbersVector
endv = NumbersVector.end() ; // one past the location
// last element of NumbersVector
// sort NumbersVector, merge requires the sequences
// to be sorted
sort(startv, endv, less<int>()) ;
// print content of NumbersVector
cout << "NumbersVector { " ;
for(itv = startv; itv != endv; itv++)
cout << *itv << " " ;
cout << " }\n" << endl ;
// Initialize vector NumbersList
for(int i = 0; i < MAX_ELEMENTS; i++)
NumbersList.push_back(i) ;
first = NumbersList.begin() ; // location of first
// element of NumbersList
last = NumbersList.end() ; // one past the location
// last element of NumbersList
// print content of NumbersList
cout << "NumbersList { " ;
for(itl = first; itl != last; itl++)
file:///D|/97/c++_1/LIBREF.TXT (484 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 479 of 619
cout << *itl << " " ;
cout << " }\n" << endl ;
// merge the elements of NumbersVector
// and NumbersList and place the
// results in NumbersDeque
merge(startv, endv, first, last, NumbersDeque.begin(), less<int>
cout << "After calling merge\n" << endl ;
// print content of NumbersDeque
cout << "NumbersDeque { " ;
for(itd = NumbersDeque.begin();
itd != NumbersDeque.end(); itd++)
cout << *itd << " " ;
cout << " }\n" << endl ;
}
Program Output is:
NumbersVector { 4 10 10 30 69 70 96 100 }
NumbersList { 0 1 2 3 4 5 6 7 }
After calling merge
NumbersDeque { 0 1 2 3 4 4 5 6 7 10 10 30 69 70 96 100 }
min_element (STL Sample)
The sample code below illustrates how to use the min_element STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator> inline
InputIterator min_element(InputIterator first, InputIterator la
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The min_element algorithm returns the location of the minimum
element in the sequence [first, last). The non-predicate version of
min_element uses operator< for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (485 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 480 of 619
//
// Compile options needed: /GX
//
// min_element.cpp : Illustrates how to use the min_element
// function.
//
// Functions:
//
// min_element - Return the minimum element within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10 ;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
file:///D|/97/c++_1/LIBREF.TXT (486 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 481 of 619
cout << " }\n" << endl ;
// return the minimum element in the Numbers
location = min_element(start, end) ;
cout << "The minimum element in Numbers is: "
<< *location << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
The minimum element in Numbers is: 4
Predicate Version of min_element (STL Sample)
The sample code below illustrates how to use the predicate version
of the min_element STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, class Compare> inline
InputIterator min_element(InputIterator first, InputIterator la
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The min_element algorithm returns the location of the minimum
element in the sequence [first, last). The predicate version of
min_element uses the compare function for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// min_element.cpp : Illustrates how to use the predicates version
// of the min_element function.
//
// Functions:
//
// min_element : Return the minimum element within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
file:///D|/97/c++_1/LIBREF.TXT (487 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 482 of 619
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// return the minimum element in the Numbers
location = min_element(start, end, less<int>()) ;
cout << "The minimum element in Numbers is: "
<< *location << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
file:///D|/97/c++_1/LIBREF.TXT (488 of 626) [28/10/2007 12:33:47 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 483 of 619
The minimum element in Numbers is: 4
new operator (STL Sample)
The sample code below illustrates how to use the new operator.
Required Header:
<new>
Prototype:
void *operator new(size_t n)
void *operator new(size_t n, const nothrow&)
void *operator new[](size_t n);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The first operator new will attempt to allocate memory and if it
fails, will throw an exception. The second operator new accepts a
second parameter of type nothrow. This parameter indicates that if
the allocation fails, it should return NULL and not throw an
exception. The third operator new will allocate memory for an array
of that type and if it fails, will throw an exception.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : newop.cpp
//
// Functions:
//
// void *operator new(size_t n)
//
// void *operator new(size_t n, const nothrow&)
//
// void *operator new[](size_t n);
////////////////////////////////////////////////////////////////////
/* Compile options needed: /GX
*/
#include <new>
#include <iostream>
using namespace std;
class BigClass {
public:
file:///D|/97/c++_1/LIBREF.TXT (489 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 484 of 619
BigClass() {};
~BigClass(){}
double BigArray[99999999];
};
void main()
{
try {
BigClass * p = new BigClass;
}
catch( bad_alloc a) {
const char * temp = a.what();
cout << temp << endl;
cout << "Threw a bad_alloc exception" << endl;
}
BigClass * q = new(nothrow) BigClass;
if ( q == NULL )
cout << "Returned a NULL pointer" << endl;
try {
BigClass * r = new BigClass[3];
}
catch( bad_alloc a) {
const char * temp = a.what();
cout << temp << endl;
cout << "Threw a bad_alloc exception" << endl;
}
}
Program Output is:
bad allocation
Threw a bad_alloc exception
Returned a NULL pointer
bad allocation
Threw a bad_alloc exception
next_permutation (STL Sample)
The sample code below illustrates how to use the next_permutation
STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator> inline
bool next_permutation(BidirectionalIterator first,
BidirectionalIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
file:///D|/97/c++_1/LIBREF.TXT (490 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 485 of 619
Description:
The next_permutation algorithm changes the order of the elements in
the range [first, last) to the next lexicographic permutation and
returns true. If there is no next_permutation, it arranges the
sequence to be the first permutation and returns false. IMPORTANT:
The next_permutation algorithm assumes the sequence is sorted in
ascending order using operator<. The non-predicate version uses the
operator< to order the permutations.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// next_permutation.cpp : Illustrates how to use the
// next_permutation function.
//
// Functions:
//
// next_permutation : Change the order of the sequence to the
// next lexicograhic permutation.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 3 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
//Define an ostream iterator for strings
typedef ostream_iterator<string> StrOstreamIt;
StrVector Pattern(VECTOR_SIZE) ;
StrVectorIt start, end, it ;
StrOstreamIt outIt(cout, " ") ;
start = Pattern.begin() ; // location of first
file:///D|/97/c++_1/LIBREF.TXT (491 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 486 of 619
// element of Pattern
end = Pattern.end() ; // one past the location last
// element of Pattern
//Initialize vector Pattern
Pattern[0] = "A" ;
Pattern[1] = "B" ;
Pattern[2] = "C" ;
// print content of Pattern
cout << "Before calling next_permutation...\n" << "Pattern: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// Generate all possible permutations
cout << "After calling next_permutation...." << endl ;
while ( next_permutation(start, end) )
{
copy(start, end, outIt) ;
cout << endl ;
}
}
Program Output is:
Before calling next_permutation:
Pattern: A B C
After calling next_permutation:
A C B
B A C
B C A
C A B
C B A
Predicate Version of next_permutation (STL Sample)
The sample code below illustrates how to use the predicate version
of the next_permutation STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator, class Compare> inline
bool next_permutation(BidirectionalIterator first,
BidirectionalIterator last,
Compare compare)
Note: The class/parameter names in the prototype do not match the
file:///D|/97/c++_1/LIBREF.TXT (492 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 487 of 619
version in the header file. Some have been modified to improve
readability.
Description:
The next_permutation algorithm changes the order of the elements in
the range [first, last) to the next lexicographic permutation and
returns true. If there is no next_permutation, it arranges the
sequence to be the first permutation and returns false. NOTE: The
next_permutation algorithm assumes that the sequence is sorted in
ascending order using the compare function. The non-predicate
version uses the compare function to order the permutations.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// next_permutation.cpp : Illustrates how to use the predicate versi
// of the next_permutation function.
//
// Functions:
//
// next_permutation : Change the order of the sequence to the
// next lexicograhic permutation.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 3 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
//Define an ostream iterator for strings
typedef ostream_iterator<string> StrOstreamIt;
StrVector Pattern(VECTOR_SIZE) ;
StrVectorIt start, end, it ;
StrOstreamIt outIt(cout, " ") ;
file:///D|/97/c++_1/LIBREF.TXT (493 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 488 of 619
start = Pattern.begin() ; // location of first
// element of Pattern
end = Pattern.end() ; // one past the location last
// element of Pattern
//Initialize vector Pattern
Pattern[0] = "K" ;
Pattern[1] = "A" ;
Pattern[2] = "L" ;
//sort the contents of Pattern, required by next_permutation
sort(start, end, less<string>()) ;
// print content of Pattern
cout << "Before calling next_permutation...\n" << "Pattern: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// Generate all possible permutations
cout << "After calling next_permutation...." << endl ;
while ( next_permutation(start, end, less<string>()) )
{
copy(start, end, outIt) ;
cout << endl ;
}
}
Program Output is:
Before calling next_permutation:
Pattern: A K L
After calling next_permutation:.
A L K
K A L
K L A
L A K
L K A
nth_element (STL Sample)
The sample code below illustrates how to use the nth_element STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator> inline
file:///D|/97/c++_1/LIBREF.TXT (494 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 489 of 619
void nth_element(RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The nth_element algorithm partitions the sequence [first..last) on
the value referenced by nth. All the elements less than or equal to
the value are placed before value and all elements greater than
value are placed after value in the sequence. The non-predicate
version of nth_element uses operator< for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// nth_element.cpp : Illustrates how to use the nth_element
// function.
//
// Functions:
//
// nth_element : Partition the elements in a sequence by its nth
// element.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
file:///D|/97/c++_1/LIBREF.TXT (495 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 490 of 619
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling nth_element\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// partition the elements by the 4th element
nth_element(start, start+4, end) ;
cout << "After calling nth_element\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling nth_element
Numbers { 4 10 70 30 10 69 96 100 }
After calling nth_element
Numbers { 4 10 10 30 69 70 96 100 }
Predicate Version of nth_element (STL Sample)
The sample code below illustrates how to use the predicate version
of the nth_element STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator, class Compare>
file:///D|/97/c++_1/LIBREF.TXT (496 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 491 of 619
inline void nth_element(RandomAccessIterator first, RandomAcces
RandomAccessIterator last, Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The nth_element algorithm partitions the sequence [first..last) on
the value referenced by nth. All the elements less than or equal to
the value are placed before value and all elements greater than
value are placed after value in the sequence. The predicate version
of nth_element uses the compare function for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// nth_element.cpp : Illustrates how to use the predicate version
// of the nth_element function.
//
// Functions:
//
// nth_element : Partition the elements in a sequence by its nth
// element.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
file:///D|/97/c++_1/LIBREF.TXT (497 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 492 of 619
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling nth_element:\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// partition the elements by the 4th element
nth_element(start, start+4, end, less<int>()) ;
cout << "After calling nth_element:\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling nth_element:
Numbers { 4 10 70 30 10 69 96 100 }
After calling nth_element:
Numbers { 4 10 10 30 69 70 96 100 }
Members of the numeric_limits Class (STL Sample)
The sample code below illustrates how to use the members of the
numeric_limits class in Visual C++.
Required Header:
<limits>
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
file:///D|/97/c++_1/LIBREF.TXT (498 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 493 of 619
Description:
To reference one of the members of this class, you need to specify
the type that you want to obtain information about and the member
name. The return will either be a value of 1 for true or 0 for
false. For example, numeric_limits<int>::min() will return the
minimum value for an int. NOTE: Some of the members are valid only
for certain types. Please refer to the Online Help to determine if
a member is valid only for a certain type.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : Numeric.cpp
//
// Variables and Functions:
//
// has_denorm
// has_denorm_loss
// has_infinity
// has_quiet_NaN
// has_signaling_NaN
// is_bounded
// is_exact
// is_iec559
// is_integer
// is_modulo
// is_signed
// is_specialized
// tinyness_before
// traps
// round_style
// digits
// digits10
// max_exponent
// max_exponent10
// min_exponent
// min_exponent10
// radix;
// denorm_min()
// epsilon()
// infinity()
// max()
// min()
// quiet_ NaN()
// round_error()
// signaling_NaN()
////////////////////////////////////////////////////////////////////
/* Compile options needed: /GX
*/
#include <iostream>
#include <limits>
file:///D|/97/c++_1/LIBREF.TXT (499 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 494 of 619
using namespace std;
void main() {
cout << " 1 The minimum value for char is " <<
(int)numeric_limits<char>::min() << endl;
cout << " 2 The minimum value for int is " <<
numeric_limits<int>::min() << endl;
cout << " 3 The maximum value for char is " <<
(int)numeric_limits<char>::max() << endl;
cout << " 4 The maximum value for int is " <<
numeric_limits<int>::max() << endl;
cout << " 5 The number of bits to represent a char is " <<
numeric_limits<char>::digits << endl;
cout << " 6 The number of bits to represent an int is " <<
numeric_limits<int>::digits << endl;
cout <<" 7 The number of digits representable in base 10 for flo
<< numeric_limits<float>::digits10 << endl;
cout << " 8 Is a char signed? " <<
numeric_limits<char>::is_signed << endl;
cout << " 9 Is an unsigned integer signed? " <<
numeric_limits<unsigned int>::is_signed << endl;
cout << "10 Is a integer an integer? " <<
numeric_limits<int>::is_integer << endl;
cout << "11 Is a float an integer? " <<
numeric_limits<float>::is_integer << endl;
cout << "12 Is a integer exact? " <<
numeric_limits<int>::is_exact << endl;
cout << "13 Is a float exact? " <<
numeric_limits<float>::is_exact << endl;
cout << "14 The radix for float is " <<
numeric_limits<float>::radix << endl;
cout << "15 The epsilon for float is " <<
numeric_limits<float>::epsilon() << endl;
cout << "16 The round error for float is " <<
numeric_limits<float>::round_error() << endl;
cout << "17 The minimum exponent for float is " <<
numeric_limits<float>::min_exponent << endl;
cout << "18 The minimum exponent in base 10 " <<
numeric_limits<float>::min_exponent10 << endl;
cout << "19 The maximum exponent is " <<
numeric_limits<float>::max_exponent << endl;
cout << "20 The maximum exponent in base 10 " <<
numeric_limits<float>::max_exponent10 << endl;
cout << "21 Can float represent positive infinity? " <<
numeric_limits<float>::has_infinity << endl;
cout << "22 Can double represent positive infinity? " <<
numeric_limits<double>::has_infinity << endl;
cout << "23 Can int represent positive infinity? " <<
numeric_limits<int>::has_infinity << endl;
cout << "24 Can float represent a NaN? " <<
numeric_limits<float>::has_quiet_NaN << endl;
cout << "25 Can float represent a signaling NaN? " <<
numeric_limits<float>::has_signaling_NaN << endl;
cout << "26 Does float allow denormalized values? " <<
numeric_limits<float>::has_denorm << endl;
file:///D|/97/c++_1/LIBREF.TXT (500 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 495 of 619
cout << "27 Does float detect denormalization loss? " <<
numeric_limits<float>::has_denorm_loss << endl;
cout << "28 Representation of positive infinity for float " <<
numeric_limits<float>::infinity() << endl;
cout << "29 Representation of quiet NaN for float " <<
numeric_limits<float>::quiet_NaN() << endl;
cout << "30 Minimum denormalized number for float " <<
numeric_limits<float>::denorm_min() << endl;
cout << "31 Minimum positive denormalized value for float " <<
numeric_limits<float>::denorm_min() << endl;
cout << "32 Does float adhere to IEC 559 standard? " <<
numeric_limits<float>::is_iec559 << endl;
cout << "33 Is float bounded? " <<
numeric_limits<float>::is_bounded << endl;
cout << "34 Is float modulo? " <<
numeric_limits<float>::is_modulo << endl;
cout << "35 Is int modulo? " <<
numeric_limits<float>::is_modulo << endl;
cout << "36 Is trapping implemented for float? " <<
numeric_limits<float>::traps << endl;
cout << "37 Is tinyness detected before rounding? " <<
numeric_limits<float>::tinyness_before << endl;
cout << "38 What is the rounding style for float? " <<
(int)numeric_limits<float>::round_style << endl;
cout << "39 What is the rounding style for int? " <<
(int)numeric_limits<int>::round_style << endl;
cout << "40 How does a float represent a signaling NaN? " <<
numeric_limits<float>::signaling_NaN() << endl;
cout << "41 Is int specialized? " <<
numeric_limits<float>::is_specialized << endl;
}
Program Output is:
1 The minimum value for char is -128
2 The minimum value for int is -2147483648
3 The maximum value for char is 127
4 The maximum value for int is 2147483647
5 The number of bits to represent a char is 7
6 The number of bits to represent an int is 31
7 The number of digits representable in base 10 for float is 6
8 Is a char signed? 1
9 Is an unsigned integer signed? 0
10 Is an integer an integer? 1
11 Is a float an integer? 0
12 Is an integer exact? 1
13 Is a float exact? 0
14 The radix for float is 2
15 The epsilon for float is 1.19209e-007
16 The round error for float is 0.5
17 The minimum exponent for float is -125
18 The minimum exponent in base 10 -37
19 The maximum exponent is 128
20 The maximum exponent in base 10 38
21 Can float represent positive infinity? 1
file:///D|/97/c++_1/LIBREF.TXT (501 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 496 of 619
22 Can double represent positive infinity? 1
23 Can int represent positive infinity? 0
24 Can float represent a NaN? 1
25 Can float represent a signaling NaN? 1
26 Does float allow denormalized values? 1
27 Does float detect denormalization loss? 1
28 Representation of positive infinity for float 1.#INF
29 Representation of quiet NaN for float -1.#IND
30 Minimum denormalized number for float 1.4013e-045
31 Minimum positive denormalized value for float 1.4013e-045
32 Does float adhere to IEC 559 standard? 1
33 Is float bounded? 1
34 Is float modulo? 0
35 Is int modulo? 0
36 Is trapping implemented for float? 1
37 Is tinyness detected before rounding? 1
38 What is the rounding style for float? 1
39 What is the rounding style for int? 0
40 How does a float represent a signaling NaN? -1.#INF
41 Is int specialized? 1
operator == and operator < deque (STL Sample)
The sample code below illustrates how to use the operator == and
operator < deque STL functions in Visual C++.
Required Header:
< deque>
Prototype:
template<class T, class A>
bool operator==(const deque <T, A>& lhs, const deque <T, A>& rh
template<class T, class A>
bool operator<(const deque <T, A>& lhs, const deque <T, A>& rhs
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The first template function overloads operator== to compare two
objects of template class deque. The function returns: lhs.size()
== rhs.size() && equal(lhs. begin(), lhs. end(), rhs.begin()). For
equality, the number of elements must be equal in both deque
objects. The second template function overloads operator< to
compare two objects of template class deque. The function returns:
lexicographical_compare(lhs. begin(), lhs. end(), rhs.begin(),
rhs.end()). Because lexicographic (as in a dictionary) compare is
used, the number of elements does not matter while using operator<.
In the sample code, adding a line of code while creating the b
object, such as b.push_front('D');, will make b greater than a.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (502 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 497 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
// ==
// <
//
////////////////////////////////////////////////////////////////////
/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
void main()
{
//create a with 3 A's
CHARDEQUE a(3,'A');
a.push_front('C');
//create b with 4 B's.
CHARDEQUE b(6,'B');
//print out the contents
print_contents (a,"a");
print_contents (b,"b");
//compare a and b
if (a==b)
cout <<"a is equal to b"<<endl;
else if(a<b)
cout <<"a is less than b"<<endl;
else
cout <<"a is greater than b" <<endl;
//assign the contents of b to a
a.assign(b.begin(),b.end());
print_contents (a,"a");
print_contents (b,"b");
//compare a and b again
if (a==b)
cout <<"a is equal to b"<<endl;
else if(a<b)
cout <<"a is less than b"<<endl;
else
file:///D|/97/c++_1/LIBREF.TXT (503 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 498 of 619
cout <<"a is greater than b" <<endl;
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" : ";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout << *pdeque <<" " ;
}
cout<<endl;
}
Program Output is:
The contents of a : C A A A
The contents of b : B B B B B B
a is greater than b
The contents of a : B B B B B B
The contents of b : B B B B B B
a is equal to b
Pair Logical Operator (STL Sample)
The sample code below illustrates how to use the pair logical
operator STL function in Visual C++.
Required Header:
< utility >
Prototype:
It is interesting to note that only the < and == operators are
necessary in order to define all of the logical operators.
template<class _T1, class _T2> inline
bool operator==(const pair<_T1, _T2>& _X,
const pair<_T1, _T2>& _Y)
{return (_X.first == _Y.first && _X.second == _Y.second); }
template<class _T1, class _T2> inline
bool operator<(const pair<_T1, _T2>& _X,
const pair<_T1, _T2>& _Y)
{return (_X.first < _Y.first ||
!(_Y.first < _X.first) && _X.second < _Y.second); }
Note: The class/parameter names in the prototype do not match the
file:///D|/97/c++_1/LIBREF.TXT (504 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 499 of 619
version in the header file. Some have been modified to improve
readability.
Description:
The functions are described in the comments section of the sample.
Sample Code:
/////////////////////////////
// Compile options needed: none
//
// paircomp.cpp : Illustrates several comparison
// operators used to compare two
// pair objects.
//
// Functions:
//
// operator== - returns true if two pair objects are identical.
//
// operator!= - returns true if two pair objects are not identica
//
// operator< - returns true for (A < B) if pair object A is less
// than pair object B.
//
// operator<= - returns true for (A <= B) if pair object A is les
// than or equal to pair object B.
//
// operator> - returns true for (A > B) if pair object A is grea
// than pair object B.
//
// operator>= - returns true for (A >= B) if pair object A is gre
// than or equal to pair object B.
/////////////////////////////
#include <iostream>
#include <utility>
using namespace std ;
/* STL pair data type containing int and float */
typedef struct pair<int, float> PAIR_IF;
void main(void)
{
PAIR_IF A(10,3.14);
PAIR_IF B(18,3.14);
PAIR_IF C(10,6.28);
PAIR_IF D(10,3.14);
/* show pair values */
cout << "A = ( " << A.first << " , " << A.second << " )" << endl;
cout << "B = ( " << B.first << " , " << B.second << " )" << endl;
cout << "C = ( " << C.first << " , " << C.second << " )" << endl;
cout << "D = ( " << D.first << " , " << D.second << " )" << endl;
file:///D|/97/c++_1/LIBREF.TXT (505 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 500 of 619
/* operator== */
if (A==D)
cout << "A and D are equal" << endl;
else
cout << "A and D are not equal" << endl;
/* operator!= */
if (B!=C)
cout << "B and C are not equivalent" << endl;
else
cout << "B and C are equivalent" << endl;
/* operator> */
if (A>C)
cout << "A is greater than C" << endl;
else
cout << "A is not greater than C" << endl;
/* operator>= */
if (A>=C)
cout << "A is greater than or equal to C" << endl;
else
cout << "A is not greater than or equal to C" << endl;
/* operator< */
if (C<D)
cout << "C is less than D" << endl;
else
cout << "C is not less than D" << endl;
/* operator<= */
if (C<D)
cout << "C is less than or equal to D" << endl;
else
cout << "C is not less than or equal to D" << endl;
}
Program Output is:
A = ( 10 , 3.14 )
B = ( 18 , 3.14 )
C = ( 10 , 6.28 )
D = ( 10 , 3.14 )
A and D are equal
B and C are not equivalent
A is not greater than C
A is not greater than or equal to C
C is not less than D
C is not less than or equal to D
file:///D|/97/c++_1/LIBREF.TXT (506 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 501 of 619
partial_sort (STL Sample)
The sample code below illustrates how to use the partial_sort STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator> inline
void partial_sort(RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The partial_sort algorithm sorts the smallest N elements, where N =
middle - first of the sequence [first, last). The remaining
elements end up in the range [middle..last) in an undefined order.
The non-predicate version of partial_sort uses operator< for
comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// partial_sort.cpp : Illustrates how to use the partial_sort
// function.
//
// Functions:
//
// partial_sort : Sort the smallest N elements in a sequence.
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
file:///D|/97/c++_1/LIBREF.TXT (507 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 502 of 619
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 7;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling partial_sort\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the smallest 4 elements in the sequence
partial_sort(start, start+4, end) ;
cout << "After calling partial_sort\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling partial_sort
Numbers { 4 10 70 30 10 69 96 7 }
After calling partial_sort
Numbers { 4 7 10 10 70 69 96 30 }
file:///D|/97/c++_1/LIBREF.TXT (508 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 503 of 619
partial_sort_copy (STL Sample)
The sample code below illustrates how to use the partial_sort_copy
STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, RandomAccessIterator> inline
RandomAccessIterator partial_sort(InputIterator first1,
InputIterator last1,
RandomAccessIterator first2,
RandomAccessIterator last2)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The partial_sort_copy algorithm sorts the smallest N elements,
where N = min((last1 - first1), (last2 - first2)), of the sequence
[first1, last1) and copies the results to the sequence [first2,
first2 + N]. The non-predicate version of partial_sort_copy uses
operator< for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// partial_sort_copy.cpp : Illustrates how to use the partial_sort_c
// function.
//
// Functions:
//
// partial_sort_copy : Sort the smallest N elements in a sequence
// and copy the resulting sequence
// to another sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
void main()
file:///D|/97/c++_1/LIBREF.TXT (509 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 504 of 619
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVector Result(4) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 7;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling partial_sort_copy\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the smallest 4 elements in the Numbers
// and copy the results in Result
partial_sort_copy(start, end, Result.begin(), Result.end()) ;
cout << "After calling partial_sort_copy\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
cout << "Result { " ;
for(it = Result.begin(); it != Result.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
file:///D|/97/c++_1/LIBREF.TXT (510 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 505 of 619
Program Output is:
Before calling partial_sort_copy
Numbers { 4 10 70 30 10 69 96 7 }
After calling partial_sort_copy
Numbers { 4 10 70 30 10 69 96 7 }
Result { 4 7 10 10 }
Predicate Version of partial_sort_copy (STL Sample)
The sample code below illustrates how to use the predicate version
of the partial_sort_copy STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class InputIterator, RandomAccessIterator, class Compare> i
RandomAccessIterator partial_sort(InputIterator first1,
InputIterator last1,
RandomAccessIterator first2,
RandomAccessIterator last2,
Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The partial_sort_copy algorithm sorts the smallest N elements,
where N = min((last1 - first1), (last2 - first2)), of the sequence
[first1, last1), and copies the results to the sequence [first2,
first2 + N]. The predicate version of partial_sort_copy uses the
compare function for comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// partial_sort_copyP.cpp : Illustrates how to use the predicate ver
// of the partial_sort_copy function.
//
// Functions:
//
// partial_sort_copy : Sort the smallest N elements in a sequence
// and copy the resulting sequence
// to another sequence.
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (511 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 506 of 619
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVector Result(4) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 7;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling partial_sort_copy\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the smallest 4 elements in the Numbers
// and copy the results in Result
partial_sort_copy(start, end, Result.begin(),Result.end(),less<i
cout << "After calling partial_sort_copy\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (512 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 507 of 619
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
cout << "Result { " ;
for(it = Result.begin(); it != Result.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling partial_sort_copy
Numbers { 4 10 70 30 10 69 96 7 }
After calling partial_sort_copy
Numbers { 4 10 70 30 10 69 96 7 }
Result { 4 7 10 10 }
Predicate Version of partial_sort (STL Sample)
The sample code below illustrates how to use the predicate version
of the partial_sort STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator, class Compare> inline
void partial_sort(RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last,
Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The partial_sort algorithm sorts the smallest N elements, where N =
middle - first of the sequence [first, last). The remaining
elements end up in the range [middle..last) in an undefined order.
The predicate version of partial_sort uses the compare function for
comparisons.
Sample Code:
////////////////////////////////////////////////////////////////////
//
file:///D|/97/c++_1/LIBREF.TXT (513 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 508 of 619
// Compile options needed: /GX
//
// partial_sort.cpp : Illustrates how to use the predicate version
// of the partial_sort function.
//
// Functions:
//
// partial_sort : Sort the smallest N elements in a sequence.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 7;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling partial_sort\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
file:///D|/97/c++_1/LIBREF.TXT (514 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 509 of 619
cout << " }\n" << endl ;
// sort the smallest 4 elements in the sequence
partial_sort(start, start+4, end, less<int>()) ;
cout << "After calling partial_sort\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling partial_sort
Numbers { 4 10 70 30 10 69 96 7 }
After calling partial_sort
Numbers { 4 7 10 10 70 69 96 30 }
partial_sum (STL Sample)
The sample code below illustrates how to use the partial_sum STL
function in Visual C++.
Required Header:
<numeric>
Prototype:
template<class InputIterator, class OutputIterator> inline
OutputIterator partial_sum(InputIterator first, InputIterator l
template<class InputIterator, class OutputIterator, class BinaryOper
OutputIterator partial_sum(InputIterator first, InputIterator l
BinaryOperator binary_op)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
Assigns to every iterator i in the range [result,result + (last -
first)) a value correspondingly equal to ((...(*first + *(first +
1)) + ...) + *(first + (i - result))) - or - binary_op(binary_op
(..., binary_op(*first, *(first + 1)),...), *(first + (i -
result))). In other words, *(result+i) = init + *(first+0) + *
(first+1) + ... + *(first+i).
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (515 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 510 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// partial_sum.cpp : Demonstrates the use of partial_sum().
//
// Description of partial_sum(first,last,first2,init)
// partial_sum(first,last,first2,init,binary_op):
//
// Assigns to every iterator i in the range
// [result,result + (last - first)) a value correspondingly equal
// ((...(*first + *(first + 1)) + ...) + *(first + (i - result)))
//
// - or -
//
// binary_op(binary_op(..., binary_op(*first, *(first + 1)),...
// *(first + (i - result)))
//
// In other words,
// *(result+i) = init + *(first+0) + *(first+1) + ... + *(first+i
////////////////////////////////////////////////////////////////////
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
using namespace std;
typedef vector < int > IntArray;
typedef ostream_iterator < int, char, char_traits<char> > IntOstream
void main ()
{
IntOstreamIt itOstream(cout," ");
// Initialize the array
IntArray rgI;
for (int i=1; i<=10; i++) rgI.push_back(i);
// Print the arrays
cout << "Array: ";
copy(rgI.begin(),rgI.end(),itOstream);
cout << endl;
// The result array must be at least the same size as the data a
IntArray rgIresult(rgI.size());
// Compute the partial sum of the array
partial_sum(rgI.begin(),rgI.end(),rgIresult.begin());
// Print the array of partial sums
cout << "Array of partial sums: ";
copy(rgIresult.begin(),rgIresult.end(),itOstream);
file:///D|/97/c++_1/LIBREF.TXT (516 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 511 of 619
cout << endl;
// Compute the partial product of the array
partial_sum(rgI.begin(),rgI.end(),rgIresult.begin(),multiplies<i
// Print the array of partial products
cout << "Array of partial products: ";
partial_sum(rgIresult.begin(),rgIresult.end(),itOstream);
cout << endl;
}
Program Output is:
Array: 1 2 3 4 5 6 7 8 9 10
Array of partial sums: 1 3 6 10 15 21 28 36 45 55
Array of partial products: 1 3 9 33 153 873 5913 46233 409113 403791
partition (STL Sample)
The sample code below illustrates how to use the partition STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator, class Predicate> inline
BidirectionalIterator partition(BidirectionalIterator first, Bi
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The partition algorithm arranges elements in the range [first,
last) such that the elements for which predicate returns true are
before the elements for which predicate returns false. The
algorithm returns an iterator positioned at the first element for
which predicate returns false.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// partition.cpp : Illustrates how to use the partition function.
//
// Functions:
//
// partition - Partition a range using a predicate.
//
file:///D|/97/c++_1/LIBREF.TXT (517 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 512 of 619
// begin - Returns an iterator that points to the first eleme
// in a sequence.
//
// end - Returns an iterator that points one past the end o
// a sequence.
//
// bind2nd - Returns true for elements for which the condition
// is true.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 6 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling partition" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
file:///D|/97/c++_1/LIBREF.TXT (518 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 513 of 619
cout << *it << " " ;
cout << " }\n" << endl ;
// partition the sequence such that all the elements
// less than 11 appear before all the elements greater than 11
it = partition(start, end, bind2nd(less<int>(), 11)) ;
cout << "After calling partition" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Before calling partition
Numbers { 6 20 10 15 12 7 9 10 }
After calling partition
Numbers { 6 10 10 9 7 12 15 20 }
prev_permutation (STL Sample)
The sample code below illustrates how to use the prev_permutation
STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator> inline
bool prev_permutation(BidirectionalIterator first,
BidirectionalIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The prev_permutation algorithm changes the order of the elements
the range [first, last), to the previous lexicographic permutation
and returns true. If there is no prev_permutation, it arranges the
sequence to be the first permutation and returns false. IMPORTANT:
The prev_permutation algorithm assumes the sequence is sorted in
descending order using operator<. The non-predicate version uses
the operator< to order the permutations.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (519 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 514 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// prev_permutation.cpp : Illustrates how to use the prev_permutatio
// function.
//
// Functions:
//
// prev_permutation : Change the order of the sequence to the
// previous lexicographic permutation.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 3 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
//Define an ostream iterator for strings
typedef ostream_iterator<string>
StrOstreamIt;
StrVector Pattern(VECTOR_SIZE) ;
StrVectorIt start, end, it ;
StrOstreamIt outIt(cout, " ") ;
start = Pattern.begin() ; // location of first
// element of Pattern
end = Pattern.end() ; // one past the location last
// element of Pattern
//Initialize vector Pattern
Pattern[0] = "C" ;
Pattern[1] = "B" ;
Pattern[2] = "A" ;
file:///D|/97/c++_1/LIBREF.TXT (520 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 515 of 619
// print content of Pattern
cout << "Before calling prev_permutation...\n" << "Pattern: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// Generate all possible permutations
cout << "After calling prev_permutation...." << endl ;
while ( prev_permutation(start, end) )
{
copy(start, end, outIt) ;
cout << endl ;
}
}
Program Output is:
Before calling prev_permutation...
Pattern: C B A
After calling prev_permutation....
C A B
B C A
B A C
A C B
A B C
priority_queue functions (STL Sample)
The sample code below illustrates how to use the
priority_queue::push, pop, empty, and top STL functions in Visual
C++.
Required Header:
<queue>
Prototype:
priority_queue::push();
priority_queue::pop();
priority_queue::empty();
priority_queue::top();
priority_queue::size();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample shows priority_queue implementation using deque and
vector containers.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (521 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 516 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : priority_queue.cpp
//
// Functions:
//
// priority_queue::push(), priority_queue::pop(),
// priority_queue::empty(), priority_queue::top(), queue::size()
//
////////////////////////////////////////////////////////////////////
#include <iostream>
#include <queue>
#include <deque>
#include <vector>
#include <functional>
using namespace std ;
// Using priority_queue with deque
// Use of function greater sorts the items in ascending order
typedef deque<int> INTDQU;
typedef priority_queue<int> INTPRQUE;
// Using priority_queue with vector
// Use of function less sorts the items in descending order
typedef vector<char> CHVECTOR;
typedef priority_queue<char> CHPRQUE;
void main(void)
{
int size_q;
INTPRQUE q;
CHPRQUE p;
// Insert items in the priority_queue(uses deque)
q.push(42);
q.push(100);
q.push(49);
q.push(201);
Program Output is:
// Output the size of priority_queue
size_q = q.size();
cout << "size of q is:" << size_q << endl;
// Output items in priority_queue using top()
// and use pop() to get to next item until
// priority_queue is empty
while (!q.empty())
file:///D|/97/c++_1/LIBREF.TXT (522 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 517 of 619
{
cout << q.top() << endl;
q.pop();
// Insert items in the priority_queue(uses vector)
p.push('c');
p.push('a');
p.push('d');
p.push('m');
p.push('h');
// Output the item at the top using top()
cout << p.top() << endl;
// Output the size of priority_queue
size_q = p.size();
cout << "size of p is:" << size_q << endl;
// Output items in priority_queue using top()
// and use pop() to get to next item until
// priority_queue is empty
while (!p.empty())
{
cout << p.top() << endl;
p.pop();
}
}
Program Output:
42
size of q is:4
42
49
100
201
m
size of p is:5
m
h
d
c
a
queue functions (STL Sample)
The sample code below illustrates how to use the queue::
(push,pop,empty,back,front) STL functions in Visual C++.
Required Header:
<queue>
Prototype:
file:///D|/97/c++_1/LIBREF.TXT (523 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 518 of 619
queue::push();
queue::pop();
queue::empty();
queue::back();
queue::front();
queue::size();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample shows queue implementation using list and deque
containers.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: none
//
// <filename> : queue.cpp
//
// Functions:
//
// queue::push(), queue::pop(), queue::empty(), queue::back(),
// queue::front(),queue::size()
//
////////////////////////////////////////////////////////////////////
/* Compile options needed:none
*/
#include <list>
#include <iostream>
#include <queue>
#include <deque>
using namespace std ;
// Using queue with list
typedef list<int > INTLIST;
typedef queue<int> INTQUEUE;
// Using queue with deque
typedef deque<char*> CHARDEQUE;
typedef queue<char*> CHARQUEUE;
void main(void)
{
int size_q;
INTQUEUE q;
CHARQUEUE p;
// Insert items in the queue(uses list)
q.push(42);
file:///D|/97/c++_1/LIBREF.TXT (524 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 519 of 619
q.push(100);
q.push(49);
q.push(201);
Program Output is:
// Output the size of queue
size_q = q.size();
cout << "size of q is:" << size_q << endl;
// Output items in queue using front()
// and use pop() to get to next item until
// queue is empty
while (!q.empty())
{
cout << q.front() << endl;
q.pop();
// Insert items in the queue(uses deque)
p.push("cat");
p.push("ape");
p.push("dog");
p.push("mouse");
p.push("horse");
// Output the item inserted last using back()
cout << p.back() << endl;
// Output the size of queue
size_q = p.size();
cout << "size of p is:" << size_q << endl;
// Output items in queue using front()
// and use pop() to get to next item until
// queue is empty
while (!p.empty())
{
cout << p.front() << endl;
p.pop();
}
}
Program Output:
201
size of q is:4
42
100
49
201
horse
file:///D|/97/c++_1/LIBREF.TXT (525 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 520 of 619
size of p is:5
cat
ape
dog
mouse
horse
random_shuffle (STL Sample)
The sample code below illustrates how to use the random_shuffle STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator> inline
void random_shuffle(RandomAccessIterator first,
RandomAccessIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The random_shuffle algorithm shuffles the elements of a sequence
[first..last) in a random order. The non-predicate version uses an
internal random-number generator to generate the indices of the
elements to swap. The non-predicate version of random_shuffle uses
operator= to perform swaps.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// random_shuffle.cpp : Illustrates how to use the random_shuffle
// function.
//
// Functions:
//
// random_shuffle : Shuffle the elements in a random order.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std ;
file:///D|/97/c++_1/LIBREF.TXT (526 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 521 of 619
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling random_shuffle\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// shuffle the elements in a random order
random_shuffle(start, end) ;
cout << "After calling random_shuffle\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling random_shuffle
Numbers { 4 10 70 30 10 69 96 100 }
file:///D|/97/c++_1/LIBREF.TXT (527 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 522 of 619
After calling random_shuffle
Numbers { 10 30 4 70 96 100 69 10 }
Predicate Version of random_shuffle (STL Sample)
The sample code below illustrates how to use the predicate version
of the random_shuffle STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class RandomAccessIterator, class Predicate> inline
void random_shuffle(RandomAccessIterator first, RandomAccessIte
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The random_shuffle algorithm shuffles the elements of a sequence
[first..last) in a random order. The predicate version uses the
pred function to generate the indices of the elements to swap. The
pred has to be a function object that takes a parameter n and
returns an integral random number in the range 0 - (n - 1). The
predicate version of random_shuffle uses operator= to perform
swaps.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// random_shuffle.cpp: Illustrates how to use the predicate version
// of the random_shuffle function.
//
// Functions:
//
// random_shuffle: Shuffle the elements in a random order.
//
// Rand: Given n, generates an integral random number in the
// in the range 0 - (n - 1).
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
file:///D|/97/c++_1/LIBREF.TXT (528 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 523 of 619
using namespace std;
// return an integral random number in the range 0 - (n - 1)
int Rand(int n)
{
return rand() % n ;
}
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 30 ;
Numbers[4] = 10;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling random_shuffle:\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// shuffle the elements in a random order.
// the pointer_to_unary_function adapter converts a function to
// function object.
random_shuffle(start, end, pointer_to_unary_function<int, int>(R
cout << "After calling random_shuffle:\n" << endl ;
cout << "Numbers { " ;
for(it = start; it != end; it++)
file:///D|/97/c++_1/LIBREF.TXT (529 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 524 of 619
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Before calling random_shuffle
Numbers { 4 10 70 30 10 69 96 100 }
After calling random_shuffle
Numbers { 10 30 4 70 96 100 69 10 }
remove (STL Sample)
The sample code below illustrates how to use the remove STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class Type> inline
ForwardIterator remove(ForwardIterator first, ForwardIterator l
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The remove algorithm removes all elements that match value from the
range (first, last). It returns an iterator equal to last - N,
where N = number of elements removed. The last N elements of the
range have undefined values. The size of the container remains the
same.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// remove.cpp : Illustrates how to use the remove function.
//
// Functions:
//
// remove - remove all elements from the sequence that match value
// begin - Returns an iterator that points to the first element in
// sequence.
// end - Returns an iterator that points one past the end of a seq
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (530 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 525 of 619
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it, last;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling remove" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove all elements from Numbers that match 10
last = remove(start, end, 10) ;
cout << "After calling remove" << endl ;
// print content of Numbers
file:///D|/97/c++_1/LIBREF.TXT (531 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 526 of 619
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//print number of elements removed from Numbers
cout << "Total number of elements removed from Numbers = "
<< end - last << endl ;
//print only the valid elements of Number
cout << "Valid elements of Numbers { " ;
for(it = start; it != last; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Before calling remove
Numbers { 10 20 10 15 12 7 9 10 }
After calling remove
Numbers { 20 15 12 7 9 7 9 10 }
Total number of elements removed from Numbers = 3
Valid elements of Numbers { 20 15 12 7 9 }
remove_copy (STL Sample)
The sample code below illustrates how to use the remove_copy STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class OutputIterator, class Type> in
OutputIterator remove_copy(ForwardIterator first, ForwardIterat
OutputIterator result, const T& value)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The remove_copy algorithm copies all elements from the range
(first, last) to the range starting at result, skipping any element
that matches value. It returns an iterator positioned immediately
after the last new element.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (532 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 527 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// remove_copy.cpp : Illustrates how to use the remove_copy function
//
// Functions:
//
// remove_copy - copy the elements of a sequence to another sequen
// eliminating any elements that match value.
// begin - Returns an iterator that points to the first element in
// sequence.
// end - Returns an iterator that points one past the end of a seq
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS), Result(MAX_ELEMENTS) ;
IntVectorIt start, end, it, last, resultIt ;
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
file:///D|/97/c++_1/LIBREF.TXT (533 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 528 of 619
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// skipping any item that equals 10
last = remove_copy(start, end, resultIt, 10) ;
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Numbers { 10 20 10 15 12 7 9 10 }
Total number of elements copied to Result = 5
Result { 20 15 12 7 9 0 0 0 }
remove_copy_if (STL Sample)
The sample code below illustrates how to use the remove_copy_if STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class OutputIterator, class Predicat
inline OutputIterator remove_copy_if(ForwardIterator first, For
OutputIterator result, Predicate pred)
Note: The class/parameter names in the prototype do not match the
file:///D|/97/c++_1/LIBREF.TXT (534 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 529 of 619
version in the header file. Some have been modified to improve
readability.
Description:
The remove_copy_if algorithm copies all elements from the range
(first, last) to the range starting at result, skipping any element
that causes the predicate to return true. It returns an iterator
positioned immediately after the last new element.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// remove_copy_if.cpp : Illustrates how to use the remove_copy_if fu
//
// Functions:
//
// remove_copy_if - copy the elements of a sequence to another seq
// eliminating any elements that satisfy a predic
// bind2nd - Returns true for elements for which the condition is
// begin - Returns an iterator that points to the first element in
// sequence
// end - Returns an iterator that points one past the end of a seq
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS), Result(MAX_ELEMENTS) ;
IntVectorIt start, end, it, last, resultIt ;
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
file:///D|/97/c++_1/LIBREF.TXT (535 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 530 of 619
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 25 ;
Numbers[6] = 30 ;
Numbers[7] = 10 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// skipping any item that >= 25
last = remove_copy_if(start, end, resultIt,
bind2nd(greater_equal<int>(), 25)) ;
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output is:
Numbers { 10 20 10 15 12 25 30 10 }
Total number of elements copied to Result = 6
Result { 10 20 10 15 12 10 0 0 }
remove_if (STL Sample)
The sample code below illustrates how to use the remove_if STL
function in Visual C++.
file:///D|/97/c++_1/LIBREF.TXT (536 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 531 of 619
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class Predicate> inline
ForwardIterator remove_if(ForwardIterator first, ForwardIterato
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The remove_if algorithm removes all elements from the range (first,
last) that cause the predicate to return true. It returns an
iterator equal to last - N, where N = number of elements removed.
The last N elements of the range have undefined values. The size of
the container remains the same.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// remove_if.cpp : Illustrates how to use the remove_if function.
//
// Functions:
//
// remove_if - remove all elements from the sequence that
// satisfies a predicate.
// bind2nd - Returns true for elements for which the condition is
// begin - Returns an iterator that points to the first element in
// sequence
// end - Returns an iterator that points one past the end of a seq
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
file:///D|/97/c++_1/LIBREF.TXT (537 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 532 of 619
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it, last;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling remove_if" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove all elements from Numbers that <= 10
last = remove_if(start, end, bind2nd(less_equal<int>(), 10) ) ;
cout << "After calling remove_if" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//print number of elements removed from Numbers
cout << "Total number of elements removed from Numbers = "
<< end - last << endl ;
//print only the valid elements of Number
cout << "Valid elements of Numbers { " ;
for(it = start; it != last; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (538 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 533 of 619
Program Output is:
Before calling remove_if
Numbers { 10 20 10 15 12 7 9 10 }
After calling remove_if
Numbers { 20 15 12 15 12 7 9 10 }
Total number of elements removed from Numbers = 5
Valid elements of Numbers { 20 15 12 }
replace (STL Sample)
The sample code below illustrates how to use the replace STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class Type> inline
void remove(ForwardIterator first, ForwardIterator last,
const T& old_value, const T& new_value)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The replace algorithm replaces all elements that match old_value
from the range [first, last) with new_value.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// replace.cpp : Illustrates how to use the replace function.
//
// Functions:
//
// replace - Replace all elements from the sequence that match va
// with another value.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
file:///D|/97/c++_1/LIBREF.TXT (539 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 534 of 619
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling replace" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove all elements from Numbers that match 10
replace(start, end, 10, 35) ;
cout << "After calling replace, to replace all 10's with 35" <<
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (540 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 535 of 619
Program Output is:
Before calling replace
Numbers { 10 20 10 15 12 7 9 10 }
After calling replace, to replace all 10's with 35
Numbers { 35 20 35 15 12 7 9 35 }
replace_copy (STL Sample)
The sample code below illustrates how to use the replace_copy STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class OutputIterator, class Type> in
OutputIterator replace_copy(ForwardIterator first, ForwardIter
OutputIterator result, const T& old_value, const T& new_value)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The replace_copy algorithm copies all elements from the range
[first, last) to a same-size range starting at result, replacing
all occurrences of old_value with new_value in the resulting
sequence. It returns an iterator positioned immediately after the
last new element in the resulting sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// replace_copy.cpp : Illustrates how to use the replace_copy functi
//
// Functions:
//
// replace_copy - Copy the elements of a sequence to another
// same-size sequence replacing any elements
// that match a value with another value.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
file:///D|/97/c++_1/LIBREF.TXT (541 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 536 of 619
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS), Result(MAX_ELEMENTS) ;
IntVectorIt start, end, it, last, resultIt ;
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// replacing any item that equals 10 with 30
last = replace_copy(start, end, resultIt, 10, 30) ;
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
file:///D|/97/c++_1/LIBREF.TXT (542 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 537 of 619
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Numbers { 10 20 10 15 12 7 9 10 }
Total number of elements copied to Result = 8
Result { 30 20 30 15 12 7 9 30 }
replace_copy_if (STL Sample)
The sample code below illustrates how to use the replace_copy_if
STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class OutputIterator, class Predicat
OutputIterator replace_copy_if(ForwardIterator first, ForwardIt
Predicate pred, const T& new_value)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The replace_copy_if algorithm copies all elements from the range
[first, last) to a same-size range starting at result, replacing
all occurrences that cause the predicate to return true with
new_value in the resulting sequence. It returns an iterator
positioned immediately after the last new element in the resulting
sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// replace_copy_if.cpp : Illustrates how to use the replace_copy_if
// function.
//
// Functions:
file:///D|/97/c++_1/LIBREF.TXT (543 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 538 of 619
//
// replace_copy_if - Copy the elements of a sequence to another
// same-size sequence replacing any elements
// that satisfies a predicate, with another val
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS), Result(MAX_ELEMENTS) ;
IntVectorIt start, end, it, last, resultIt ;
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
file:///D|/97/c++_1/LIBREF.TXT (544 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 539 of 619
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// replacing any item that >= 10 with 30
last = replace_copy_if(start, end, resultIt,
bind2nd(greater_equal<int>(), 10), 30) ;
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Numbers { 10 20 10 15 12 7 9 10 }
Total number of elements copied to Result = 8
Result { 30 30 30 30 30 7 9 30 }
replace_if (STL Sample)
The sample code below illustrates how to use the replace_if STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class Predicate, class Type> inline
void replace_if(ForwardIterator first, ForwardIterator last, Pr
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The replace_if algorithm replaces all elements from the range
[first, last) that cause the predicate to return true with value.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (545 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 540 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// replace_if.cpp : Illustrates how to use the replace_if function.
//
// Functions:
//
// replace_if - Replace all elements from the sequence that
// satisfies a predicate with a specified value.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
//Define an iterator for template class vector of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling replace_if" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (546 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 541 of 619
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// replace all elements from Numbers that are <= 10 with 4
replace_if(start, end, bind2nd(less_equal<int>(), 10), 4 ) ;
cout << "After calling replace_if" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
Program Output is:
Before calling replace_if
Numbers { 10 20 10 15 12 7 9 10 }
After calling replace_if
Numbers { 4 20 4 15 12 4 4 4 }
reverse (STL Sample)
The sample code below illustrates how to use the reverse STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator> inline
void reverse(BidirectionalIterator first, BidirectionalIterator
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The reverse algorithm reverses the order of the elements in the
range [first, last).
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
file:///D|/97/c++_1/LIBREF.TXT (547 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 542 of 619
//
// reverse.cpp : Illustrates how to use the reverse function.
//
// Functions:
//
// reverse - Reverse the items in a sequence.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string > StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
StrVector Tongue_Twister(VECTOR_SIZE) ;
StrVectorIt start, end, it ;
start = Tongue_Twister.begin() ; // location of first
// element of Tongue_Twister
end = Tongue_Twister.end() ; // one past the location last
// element of Tongue_Twister
//Initialize vector Tongue_Twister
Tongue_Twister[0] = "she" ;
Tongue_Twister[1] = "sells" ;
Tongue_Twister[2] = "sea" ;
Tongue_Twister[3] = "shells" ;
Tongue_Twister[4] = "by";
Tongue_Twister[5] = "the";
Tongue_Twister[6] = "sea" ;
Tongue_Twister[7] = "shore" ;
cout << "Before calling reverse \n" << endl ;
// print content of Tongue_Twister
cout << "Try this Tongue Twister: " ;
for(it = start; it != end; it++)
file:///D|/97/c++_1/LIBREF.TXT (548 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 543 of 619
cout << *it << " " ;
cout << "\n\n" ;
// reverse the items in the vector Tongue_Twister
reverse(start, end) ;
cout << "After calling reverse \n" << endl ;
// print content of Tongue_Twister
cout << "Now try the reversed Tongue Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
Program Output is:
Before calling reverse
Try this Tongue Twister: she sells sea shells by the sea shore
After calling reverse
Now try the reversed Tongue Twister: shore sea the by shells sea sel
reverse_copy (STL Sample)
The sample code below illustrates how to use the reverse_copy STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class BidirectionalIterator, class OutputIterator> inline
OutputIterator reverse_copy(BidirectionalIterator first,
BidirectionalIterator last,
OutputIterator result)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The reverse_copy algorithm reverses the order of the elements in
the range [first, last) and copies the result into a sequence of
the same size starting at result. It returns an iterator positioned
immediately after the last new element in the resulting sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (549 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 544 of 619
//
// Compile options needed: /GX
//
// reverse_copy.cpp : Illustrates how to use the reverse_copy functi
//
// Functions:
//
// reverse_copy - Reverse a sequence, copy the results to another
// same-sized sequence.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
StrVector Tongue_Twister(VECTOR_SIZE) ;
StrVector Reversed_Twister(VECTOR_SIZE) ;
StrVectorIt start, end, it, RTstart, RTend ;
start = Tongue_Twister.begin() ; // location of first
// element of Tongue_Twister
end = Tongue_Twister.end() ; // one past the location last
// element of Tongue_Twister
RTstart = Reversed_Twister.begin() ; // location of first
// element of Reversed_Twis
RTend = Reversed_Twister.end() ; // one past the location last
// element of Reversed_Twister
//Initialize vector Tongue_Twister
Tongue_Twister[0] = "she" ;
Tongue_Twister[1] = "sells" ;
Tongue_Twister[2] = "sea" ;
Tongue_Twister[3] = "shells" ;
Tongue_Twister[4] = "by";
file:///D|/97/c++_1/LIBREF.TXT (550 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 545 of 619
Tongue_Twister[5] = "the";
Tongue_Twister[6] = "sea" ;
Tongue_Twister[7] = "shore" ;
cout << "Before calling reverse_copy \n" << endl ;
// print content of Tongue_Twister
cout << "Try this Tongue Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// reverse the items in the vector Tongue_Twister
// and copy the results to Reversed_Twister
reverse_copy(start, end, RTstart) ;
cout << "After calling reverse_copy: \n"
<< endl ;
// print content of Tongue_Twister
cout << "Tongue_Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// print content of Reversed_Twister
cout << "Now try the reversed Tongue Twister: " ;
for(it = RTstart; it != RTend; it++)
cout << *it << " " ;
cout << "\n\n" ;
Program Output is:
Before calling reverse_copy
Try this Tongue Twister: she sells sea shells by the sea shore
After calling reverse_copy:
Tongue_Twister: she sells sea shells by the sea shore
Now try the reversed Tongue Twister: shore sea the by shells sea sel
rotate (STL Sample)
The sample code below illustrates how to use the rotate STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
file:///D|/97/c++_1/LIBREF.TXT (551 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 546 of 619
template<class ForwardIterator> inline
void rotate(ForwardIterator first,
ForwardIterator middle,
ForwardIterator last)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The rotate algorithm rotates the elements in the range [first,
last) to the right by N positions, where N = middle - first.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// rotate.cpp : Illustrates how to use the rotate function.
//
// Functions:
//
// rotate - Rotate the items in a sequence by n positions.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
StrVector Tongue_Twister(VECTOR_SIZE) ;
StrVectorIt start, end, middle, it ;
start = Tongue_Twister.begin() ; // location of first
// element of Tongue_Twister
file:///D|/97/c++_1/LIBREF.TXT (552 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 547 of 619
end = Tongue_Twister.end() ; // one past the location last
// element of Tongue_Twister
//Initialize vector Tongue_Twister
Tongue_Twister[0] = "she" ;
Tongue_Twister[1] = "sells" ;
Tongue_Twister[2] = "sea" ;
Tongue_Twister[3] = "shells" ;
Tongue_Twister[4] = "by";
Tongue_Twister[5] = "the";
Tongue_Twister[6] = "sea" ;
Tongue_Twister[7] = "shore" ;
middle = start + 3 ; // start position for rotating elements
cout << "Before calling rotate\n" << endl ;
// print content of Tongue_Twister
cout << "Try this Tongue Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// rotate the items in the vector Tongue_Twister by 3 positions
rotate(start, middle, end) ;
cout << "After calling rotate \n" << endl ;
// print content of Tongue_Twister
cout << "Now try the rotated Tongue Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
}
Program Output is:
Before calling rotate
Try this Tongue Twister: she sells sea shells by the sea shore
After calling rotate
Now try the rotated Tongue Twister: shells by the sea shore she sell
rotate_copy (STL Sample)
The sample code below illustrates how to use the rotate_copy STL
function in Visual C++.
Required Header:
<algorithm>
file:///D|/97/c++_1/LIBREF.TXT (553 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 548 of 619
Prototype:
template<class ForwardIterator, class OutputIterator> inline
OutputIterator rotate_copy(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last,
OutputIterator result)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The rotate_copy algorithm rotates the elements in the range [first,
last) to the right by N positions (where N = middle - first), and
copies the result into a sequence of the same size, starting at
result. It returns an iterator positioned immediately after the
last new element in the resulting sequence. Note that the
OutputIterator should be different from the sequence to be rotated.
If they are the same, the result will depend on the implementation.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// rotate_copy.cpp : Illustrates how to use the rotate_copy function
//
// Functions:
//
// rotate_copy - Rotate a sequence by n positions, copy the
// results to another same sized sequence.
//
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string> StrVector ;
file:///D|/97/c++_1/LIBREF.TXT (554 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 549 of 619
//Define an iterator for template class vector of strings
typedef StrVector::iterator StrVectorIt ;
StrVector Tongue_Twister(VECTOR_SIZE) ;
StrVector Rotated_Twister(VECTOR_SIZE) ;
StrVectorIt start, middle, end, it, RTstart, RTend ;
start = Tongue_Twister.begin() ; // location of first
// element of Tongue_Twister
end = Tongue_Twister.end() ; // one past the location las
// element of Tongue_Twister
middle = start + 3 ; // start position for
// rotating elements
RTstart = Rotated_Twister.begin() ; // location of first
// element of Rotated_Twiste
RTend = Rotated_Twister.end() ; // one past the location las
// element of Rotated_Twiste
//Initialize vector Tongue_Twister
Tongue_Twister[0] = "she" ;
Tongue_Twister[1] = "sells" ;
Tongue_Twister[2] = "sea" ;
Tongue_Twister[3] = "shells" ;
Tongue_Twister[4] = "by";
Tongue_Twister[5] = "the";
Tongue_Twister[6] = "sea" ;
Tongue_Twister[7] = "shore" ;
cout << "Before calling rotate_copy:\n" << endl ;
// print content of Tongue_Twister
cout << "Try this Tongue Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// rotate the items in the vector Tongue_Twist to the right by
// 3 positions and copy the results to Rotated_Twister
rotate_copy(start, middle, end, RTstart) ;
cout << "After calling rotate_copy:\n" << endl ;
// print content of Tongue_Twister
cout << "Tongue_Twister: " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << "\n\n" ;
// print content of Rotated_Twister
cout << "Now try the rotated Tongue Twister: " ;
for(it = RTstart; it != RTend; it++)
cout << *it << " " ;
file:///D|/97/c++_1/LIBREF.TXT (555 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 550 of 619
cout << "\n\n" ;
}
Program Output is:
Before calling rotate_copy:
Try this Tongue Twister: she sells sea shells by the sea shore
After calling rotate_copy:
Tongue_Twister: she sells sea shells by the sea shore
Now try the rotated Tongue Twister: shells by the sea shore she sell
set::(lower_, upper_)bound, equal_range (STL Sample)
The sample code below illustrates how to use the set::lower_bound,
set::upper_bound, and set::equal_range STL functions in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
const_iterator lower_bound(const _K& _Kv) const;
// Function 2:
const_iterator upper_bound(const _K& _Kv) const;
// Function 3:
_Paircc equal_range(const _K& _Kv) const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The lower_bound function returns an iterator to the earliest
element in the controlled sequence that has a key that does not
match the value passed to the lower_bound function. The upper_bound
function returns an iterator to the earliest element in the
controlled sequence that has a key matching the value passed to the
upper_bound function. If no such element exists, the function
returns end(). In both cases, the function set::key_comp()(key, x)
is used to determine if the keys match. The equal_range function
returns a pair value, where .first is the result of the lower_bound
function, and .second is the result of the upper_bound function.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (556 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 551 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetBoundRange.cpp:
// Illustrates how to use the lower_bound function to get an
// iterator to the earliest element in the controlled sequence
// that has a key that does not match the value passed to the
// function. It also illustrates how to use the upper_bound
// function to get an iterator to the earliest element in the
// controlled sequence that has a key that matches the value
// passed to the function. The last thing it illustrates is
// how to use the equal_range function to get a pair value that
// contains the lower_bound and upper_bound results of the key.
//
// Functions:
//
// lower_bound Returns an iterator whose value does not match th
// key passed to the function, or end() if no such
// element exists.
// upper_bound Returns an iterator whose value matches the key
// passed to the function, or end() if no such eleme
// exists.
// equal_range Returns a pair of (lower_bound,upper_bound).
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void main() {
SET_INT s1;
SET_INT::iterator i;
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(10)" << endl;
s1.insert(10);
cout << "s1.insert(15)" << endl;
s1.insert(15);
cout << "s1.insert(20)" << endl;
s1.insert(20);
cout << "s1.insert(25)" << endl;
s1.insert(25);
cout << "s1 -- starting at s1.lower_bound(12)" << endl;
// prints: 15,20,25
for (i=s1.lower_bound(12);i!=s1.end();i++)
cout << "s1 has " << *i << " in its set." << endl;
cout << "s1 -- starting at s1.lower_bound(15)" << endl;
// prints: 15,20,25
for (i=s1.lower_bound(15);i!=s1.end();i++)
file:///D|/97/c++_1/LIBREF.TXT (557 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 552 of 619
cout << "s1 has " << *i << " in its set." << endl;
cout << "s1 -- starting at s1.upper_bound(12)" << endl;
// prints: 15,20,25
for (i=s1.upper_bound(12);i!=s1.end();i++)
cout << "s1 has " << *i << " in its set." << endl;
cout << "s1 -- starting at s1.upper_bound(15)" << endl;
// prints: 20,25
for (i=s1.upper_bound(15);i!=s1.end();i++)
cout << "s1 has " << *i << " in its set." << endl;
cout << "s1 -- s1.equal_range(12)" << endl;
// does not print anything
for (i=s1.equal_range(12).first;i!=s1.equal_range(12).second;i++)
cout << "s1 has " << *i << " in its set." << endl;
cout << "s1 -- s1.equal_range(15)" << endl;
// prints: 15
for (i=s1.equal_range(15).first;i!=s1.equal_range(15).second;i++)
cout << "s1 has " << *i << " in its set." << endl;
}
Program Output is:
s1.insert(5)
s1.insert(10)
s1.insert(15)
s1.insert(20)
s1.insert(25)
s1 -- starting at s1.low
s1 has 15 in its set.
s1 has 20 in its set.
s1 has 25 in its set.
s1 -- starting at s1.low
s1 has 15 in its set.
s1 has 20 in its set.
s1 has 25 in its set.
s1 -- starting at s1.upp
s1 has 15 in its set.
s1 has 20 in its set.
s1 has 25 in its set.
s1 -- starting at s1.upp
s1 has 20 in its set.
s1 has 25 in its set.
s1 -- s1.equal_range(12)
s1 -- s1.equal_range(15)
s1 has 15 in its set.
set::(key_, value_)comp (STL Sample)
The sample code below illustrates how to use the set::key_comp and
set::value_comp STL functions in Visual C++.
file:///D|/97/c++_1/LIBREF.TXT (558 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 553 of 619
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
key_compare key_comp() const;
// Function 2:
value_compare value_comp() const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The key_comp function returns the stored function object that
determines the order of elements in the controlled sequence. The
value_comp function returns the same function that key_comp
returns.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetComp.cpp:
// Illustrates how to use the key_comp function to obtain a
// function pointer that is the stored function object that
// determines the order of elements in the controlled sequence.
// It also illustrates how to use the value_comp function to
// obtain a function pointer that is the stored function object
// that determines the order of the elements in the controlled
// sequence (same as key_comp result).
//
// Functions:
//
// key_comp Returns a function pointer to the function that
// determines the order of elements in the controlle
// sequence.
// value_comp Returns a function pointer to the function that
// determines the order of elements in the controlle
// sequence (same as key_comp).
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
file:///D|/97/c++_1/LIBREF.TXT (559 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 554 of 619
typedef set<int> SET_INT;
void truefalse(int x)
{
cout << (x?"True":"False") << endl;
}
void main() {
SET_INT s1;
cout << "s1.key_comp()(8,10) returned ";
truefalse(s1.key_comp()(8,10)); // True
cout << "s1.value_comp()(8,10) returned ";
truefalse(s1.value_comp()(8,10)); // True
cout << "s1.key_comp()(10,8) returned ";
truefalse(s1.key_comp()(10,8)); // False
cout << "s1.value_comp()(10,8) returned ";
truefalse(s1.value_comp()(10,8)); // False
cout << "s1.key_comp()(8,8) returned ";
truefalse(s1.key_comp()(8,8)); // False
cout << "s1.value_comp()(8,8) returned ";
truefalse(s1.value_comp()(8,8)); // False
}
Program Output is:
s1.key_comp()(8,10) returned True
s1.value_comp()(8,10) returned True
s1.key_comp()(10,8) returned False
s1.value_comp()(10,8) returned False
s1.key_comp()(8,8) returned False
s1.value_comp()(8,8) returned False
set::count (STL Sample)
The sample code below illustrates how to use the set::count STL
function in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
file:///D|/97/c++_1/LIBREF.TXT (560 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 555 of 619
// Function 1:
size_type count(const _K& _Kv) const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The count function is used to determine the number of elements in
the controlled sequence that have a particular key.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetCount.cpp:
// Illustrates how to use the count function to determine how
// many elements have a particular key.
//
// Functions:
//
// count Returns the number of elements in the controlled
// sequence that have a particular key.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void truefalse(int x)
{
cout << (x?"True":"False") << endl;
}
void main() {
SET_INT s1;
SET_INT::_Pairib pib;
cout << "s1.insert(5)" << endl;
pib=s1.insert(5);
cout << "Inserted element: ";
truefalse(pib.second); // True
cout << "s1.insert(5)" << endl;
pib=s1.insert(5);
cout << "Inserted element: ";
truefalse(pib.second); // True
cout << "s1.insert(8)" << endl;
s1.insert(8);
file:///D|/97/c++_1/LIBREF.TXT (561 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 556 of 619
cout << "s1.insert(12)" << endl;
s1.insert(12);
cout << "s1.count(5) returned ";
cout << s1.count(5) << endl; // 1
cout << "s1.count(9) returned ";
cout << s1.count(9) << endl; // 0
}
Program Output is:
s1.insert(5)
Inserted element: True
s1.insert(5)
Inserted element: False
s1.insert(8)
s1.insert(12)
s1.count(5) returned 1
s1.count(9) returned 0
set::empty and set::clear (STL Sample)
The sample code below illustrates how to use the set::empty and
set::clear STL functions in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
bool empty() const;
// Function 2:
void clear();
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The empty function returns true when there are no elements in the
controlled sequence. By calling erase(begin,end), the clear
function removes all elements in the controlled sequence. For more
information on the erase function, see set::erase.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (562 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 557 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetEmpty&Clear.cpp:
// Illustrates how to use the empty function to determine if
// there are elements in the controlled sequence. It also
// illustrates how to use the clear function to remove all
// elements from the controlled sequence.
//
// Functions:
//
// empty Returns true if there are no elements in the
// controlled sequence.
// clear Removes all elements from the controlled sequence
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void truefalse(int x)
{
cout << (x?"True":"False") << endl;
}
void main() {
SET_INT s1;
cout << "s1.empty() returned ";
truefalse(s1.empty()); // True
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(8)" << endl;
s1.insert(8);
cout << "s1.empty() returned ";
truefalse(s1.empty()); // False
cout << "s1.clear()" << endl;
s1.clear();
cout << "s1.empty() returned ";
truefalse(s1.empty()); // True
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (563 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 558 of 619
s1.empty() returned True
s1.insert(5)
s1.insert(8)
s1.empty() returned False
s1.clear()
s1.empty() returned True
set::find (STL Sample)
The sample code below illustrates how to use the set::find STL
function in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
const_iterator find(const _K& _Kv) const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The find function is used to locate an element in a controlled
sequence. It returns an iterator to the first element in the
controlled sequence whose sort key matches its parameter. If no
such element exists, the returned iterator equals end().
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetFind.cpp:
// Illustrates how to use the find function to get an iterator
// that points to the first element in the controlled sequence
// that has a particular sort key.
//
// Functions:
//
// find Returns an iterator that points to the first elem
// in the controlled sequence that has the same sort
// as the value passed to the find function. If no s
// element exists, the iterator equals end().
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
file:///D|/97/c++_1/LIBREF.TXT (564 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 559 of 619
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void truefalse(int x)
{
cout << (x?"True":"False") << endl;
}
void main() {
SET_INT s1;
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(8)" << endl;
s1.insert(8);
cout << "s1.insert(12)" << endl;
s1.insert(12);
SET_INT::iterator it;
cout << "it=find(8)" << endl;
it=s1.find(8);
cout << "it!=s1.end() returned ";
truefalse(it!=s1.end()); // True
cout << "it=find(6)" << endl;
it=s1.find(6);
cout << "it!=s1.end() returned ";
truefalse(it!=s1.end()); // False
}
Program Output is:
s1.insert(5)
s1.insert(8)
s1.insert(12)
it=find(8)
it!=s1.end() returned True
it=find(6)
it!=s1.end() returned False
set::max_size (STL Sample)
The sample code below illustrates how to use the set::max_size STL
function in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
file:///D|/97/c++_1/LIBREF.TXT (565 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 560 of 619
class set
{
public:
// Function 1:
size_type max_size() const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The max_size function is used to determine the maximum number of
elements the controlled sequence can contain.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetMax_size.cpp:
// Illustrates how to use the max_size function to determine ho
// many elements the controlled sequence can contain.
//
// Functions:
//
// max_size Returns the maximum number of elements the contro
// sequence can contain.
//
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
#include <assert.h>
using namespace std ;
typedef set<int> SET_INT;
void main() {
SET_INT s1;
cout << "s1.max_size() returned ";
cout << s1.max_size() << endl; // 1073741823 [value may vary]
for (int x=0;(x<1000 && x<s1.max_size());x++)
assert(s1.insert(x).second);
cout << "s1.size() returned ";
cout << s1.size() << endl; // 1000
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (566 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 561 of 619
s1.max_size() returned 1073741823
s1.size() returned 1000
set::rbegin and set::rend (STL Sample)
The sample code below illustrates how to use the set::rbegin and
set::rend STL functions in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
const_reverse_iterator rbegin() const;
// Function 2:
const_reverse_iterator rend() const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The rbegin function returns a reverse bidirectional iterator that
points just beyond the end of the controlled sequence. The rend
function returns a reverse bidirectional iterator that points at
the first element of the sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetRbeginRend.cpp:
// Illustrates how to use the rbegin function to get a reverse
// bidirectional iterator that points just beyond the end of
// the controlled sequence. It also illustrates how to use
// the rend function to get a reverse bidirectional iterator
// that points at the first element of the sequence.
//
// Functions:
//
// rbegin Returns a reverse bidirectional iterator that poin
// just beyond the end of the controlled sequence.
// rend Returns a reverse bidirectional iterator that poin
// at the first element of the sequence.
//
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
file:///D|/97/c++_1/LIBREF.TXT (567 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 562 of 619
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void main() {
SET_INT s1;
SET_INT::reverse_iterator i;
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(10)" << endl;
s1.insert(10);
cout << "s1.insert(15)" << endl;
s1.insert(15);
cout << "s1.insert(20)" << endl;
s1.insert(20);
// displays: 20,15,10,5
for (i=s1.rbegin();i!=s1.rend();i++)
cout << "s1 has " << *i << " in its set." << endl;
}
Program Output is:
s1.insert(5)
s1.insert(10)
s1.insert(15)
s1.insert(20)
s1 has 20 in its set.
s1 has 15 in its set.
s1 has 10 in its set.
s1 has 5 in its set.
set::size (STL Sample)
The sample code below illustrates how to use the set::size STL
function in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
size_type size() const;
}
file:///D|/97/c++_1/LIBREF.TXT (568 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 563 of 619
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The size function is used to determine the number of elements in
the controlled sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetSize.cpp:
// Illustrates how to use the size function to determine how
// many elements are in the controlled sequence.
//
// Functions:
//
// size Returns the number of elements in the controlled
// sequence.
//
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void main() {
SET_INT s1;
cout << "s1.size() returned ";
cout << s1.size() << endl; // 0
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(8)" << endl;
s1.insert(8);
cout << "s1.insert(12)" << endl;
s1.insert(12);
cout << "s1.size() returned ";
cout << s1.size() << endl; // 3
}
Program Output is:
s1.size() returned 0
file:///D|/97/c++_1/LIBREF.TXT (569 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 564 of 619
s1.insert(5)
s1.insert(8)
s1.insert(12)
s1.size() returned 3
set::swap, begin, end (STL Sample)
The sample code below illustrates how to use the set::(swap, begin,
end) STL functions in Visual C++.
Required Header:
<set>
Prototype:
template<class _K, class _Pr, class _A>
class set
{
public:
// Function 1:
void swap(_Myt& _X);
// Function 2:
friend void swap(_Myt& _X, _Myt& _Y);
// Function 3:
const_iterator begin() const;
// Function 4:
const_iterator end() const;
}
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The swap function swaps the two controlled sequences. The begin
function returns a bidirectional iterator that points at the first
element of the sequence. The end function returns a bidirectional
iterator that points just beyond the end of the sequence.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// SetSwapBeginEnd.cpp:
// Illustrates how to use the swap function to exchange the two
// controlled sequences. It also illustrates how to use the
// begin function to get a bidirectional iterator that points a
// the first element of the controlled sequence. Finally, it
// illustrates how to use the end function to get a bidirection
// iterator that points just beyond the end of the controlled
// sequence.
//
// Functions:
//
file:///D|/97/c++_1/LIBREF.TXT (570 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 565 of 619
// swap Exchanges the two controlled sequences.
// begin Returns a bidirectional iterator that points at th
// first element of the controlled sequence.
// end Returns a bidirectional iterator that points just
// beyond the end of the controlled sequence.
//
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <set>
#include <iostream>
using namespace std ;
typedef set<int> SET_INT;
void main() {
SET_INT s1;
SET_INT s2;
SET_INT::iterator i;
cout << "s1.insert(5)" << endl;
s1.insert(5);
cout << "s1.insert(10)" << endl;
s1.insert(10);
cout << "s1.insert(15)" << endl;
s1.insert(15);
cout << "s2.insert(2)" << endl;
s2.insert(2);
cout << "s2.insert(4)" << endl;
s2.insert(4);
cout << "swap(s1,s2)" << endl;
swap(s1,s2);
// Displays: 2,4
for (i=s1.begin();i!=s1.end();i++)
cout << "s1 has " << *i << " in its set." << endl;
// Displays: 5,10,15
for (i=s2.begin();i!=s2.end();i++)
cout << "s2 has " << *i << " in its set." << endl;
cout << "s1.swap(s2)" << endl;
s1.swap(s2);
// Displays: 5,10,15
for (i=s1.begin();i!=s1.end();i++)
cout << "s1 has " << *i << " in its set." << endl;
// Displays: 2,4
for (i=s2.begin();i!=s2.end();i++)
cout << "s2 has " << *i << " in its set." << endl;
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (571 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 566 of 619
s1.insert(5)
s1.insert(10)
s1.insert(15)
s2.insert(2)
s2.insert(4)
swap(s1,s2)
s1 has 2 in its set.
s1 has 4 in its set.
s2 has 5 in its set.
s2 has 10 in its set.
s2 has 15 in its set.
s1.swap(s2)
s1 has 5 in its set.
s1 has 10 in its set.
s1 has 15 in its set.
s2 has 2 in its set.
s2 has 4 in its set.
sqrt and pow (STL Sample)
The sample code below illustrates how to use the sqrt and pow STL
functions in Visual C++.
Required Header:
<valarray>
Prototype:
// sqrt
template<class T>
inline valarray<T> sqrt(const valarray<T>& x);
// pow
template<class T>
inline valarray<T> pow(const valarray<T>& x, const valarray<T>&
template<class T>
inline valarray<T> pow(const valarray<T> x, const T& y);
template<class T>
inline valarray<T> pow(const T& x, const valarray<T>& y);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
This article illustrates the use of STL sqrt() and pow() functions
through sample code. sqrt() returns an object of class valarray<T>,
each of whose elements at index I is the square root of x[I]. pow()
has three template functions. The first template function returns
an object of class valarray<T>, each of whose elements at index I
is x[I] raised to the power of y[I]. The second template function
stores in element I x[I] raised to the power of y. The third
file:///D|/97/c++_1/LIBREF.TXT (572 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 567 of 619
template function stores in element I x raised to the power of y
[I].
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// main.cpp : Illustrates the use of STL sqrt() and pow() functions.
//
// Functions:
//
// sqrt, pow
////////////////////////////////////////////////////////////////////
#include <iostream> // for i/o functions
#include <valarray> // for valarray
#include <cmath> // for sqrt() and pow()
using namespace std ;
#define ARRAY_SIZE 3 // array size
void main()
{
// Set val_array to contain values 1, 4, 9 for the following tes
valarray<double> val_array(ARRAY_SIZE);
for (int i = 0; i < ARRAY_SIZE; i++)
val_array[i] = (i+1) * (i+1);
// Display the size of val_array
cout << "Size of val_array = " << val_array.size() << endl;
// Display the values of val_array before calling sqrt() and pow
cout << "The values in val_array:" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << val_array[i] << " ";
cout << endl << endl;
// Initialize rev_valarray that is the reverse of val_array.
valarray<double> rev_valarray(ARRAY_SIZE);
for (i = 0; i < ARRAY_SIZE; i++)
rev_valarray[i] = val_array[ARRAY_SIZE - i - 1];
// Display the size of rev_valarray.
cout << "Size of rev_valarray = " << rev_valarray.size() << endl
// Display the values of rev_valarray.
cout << "The values in rev_valarray:" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rev_valarray[i] << " ";
cout << endl << endl;
// rvalue_array to hold the return value from calling the sqrt()
// pow() functions.
file:///D|/97/c++_1/LIBREF.TXT (573 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 568 of 619
valarray<double> rvalue_array;
// -------------------------------------------------------------
// sqrt() - display the content of rvalue_array
// -------------------------------------------------------------
// Display the result of val_array after calling sqrt().
rvalue_array = sqrt(val_array);
cout << "The result of val_array after calling sqrt():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// pow() - display the content of rvalue_array
// -------------------------------------------------------------
// This template function returns an object of class valarray<T>
// each of whose elements at I is x[I] raised to the power of y[
rvalue_array = pow(val_array, rev_valarray);
cout << "The result after calling pow(val_array, rev_valarray):"
<< endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// This template function stores in element I x[I] raised to the
// power of y, where y=2.0.
rvalue_array = pow(val_array, 2.0);
cout << "The result after calling pow(val_array, 2.0):" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// This template function stores in element I x raised to the
// y[I] power, where x=2.0.
rvalue_array = pow(2.0, val_array);
cout << "The result after calling pow(2.0, val_array):" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
}
Program Output is:
Size of val_array = 3
The values in val_array:
1 4 9
Size of rev_valarray = 3
The values in rev_valarray:
9 4 1
The result of val_array after calling sqrt():
file:///D|/97/c++_1/LIBREF.TXT (574 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 569 of 619
1 2 3
The result after calling pow(val_array, rev_valarray):
1 256 9
The result after calling pow(val_array, 2.0):
1 16 81
The result after calling pow(2.0, val_array):
2 16 512
stack::operator== (STL Sample)
The sample code below illustrates how to use the stack::operator==
STL function in Visual C++.
Required Header:
<stack>
Prototype:
template<class _TYPE, class _C, class _A>
bool stack::bool operator==(const stack<_TYPE, _C, _A>& _X) con
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The stack::operator== function returns true if both stacks have
equal elements arranged in the same sequence. The stack::operator==
function always returns false if the two stacks are of different
size.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StackEqual.cpp : Illustrates how to use the stack::operator==
// function to determine if two stacks are equal.
//
// Functions:
//
// operator== : Returns true if both stacks are the same.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <iostream>
using namespace std ;
typedef stack<double> STACK_DOUBLE;
file:///D|/97/c++_1/LIBREF.TXT (575 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 570 of 619
void main()
{
STACK_DOUBLE stack1,stack2;
// Add item 4.0 to Stack1.
cout << "stack1.push(4.0) s1=[4.0]" << endl;
stack1.push(4.0);
// Add item 3.0 to Stack1. Current Stack1 contains items 3.0 (top
// 4.0 (bottom).
cout << "stack1.push(3.0) s1=[3.0 4.0]" << endl;
stack1.push(3.0);
// Add item 4.0 to Stack2.
cout << "stack2.push(4.0) s2=[4.0]" << endl;
stack2.push(4.0);
// Compare Stack1 and Stack2. Should return False.
cout << "stack1==stack2 is " <<
((stack1==stack2)? "True": "False") << endl << endl;
// Add item 6.0 to Stack2. Current Stack2 contains items 6.0 (top
// 4.0 (bottom)
cout << "stack2.push(6.0) s2=[6.0 4.0]" << endl;
stack2.push(6.0);
// Compare Stack1 and Stack2. Should return False.
cout << "stack1==stack2 is " <<
((stack1==stack2)? "True": "False") << endl << endl;
// Keep adding item 8.0 to Stack2. Current Stack2 contains items
// 8.0 (top), 6.0 and 4.0 (bottom).
cout << "stack2.push(8.0) s2=[8.0 6.0 4.0]" << endl;
stack2.push(8.0);
// Compare Stack1 and Stack2. Should return False.
cout << "stack1==stack2 is " <<
((stack1==stack2)? "True": "False") << endl << endl;
// Delete the top item from Stack2. Current Stack2 contains items
// 6.0 (top) and 4.0 (bottom).
cout << "stack2.pop() s2=[6.0 4.0]" << endl;
stack2.pop();
// Delete another item from Stack2. Current Stack2 contains item
cout << "stack2.pop() s2=[4.0]" << endl;
stack2.pop();
// Add item 3.0 to Stack2. Current Stack2 contains item 3.0 (top)
// 4.0 (bottom).
cout << "stack2.push(3.0) s2=[3.0 4.0]" << endl;
stack2.push(3.0);
// Compare Stack2 and Stack2. Should return True.
cout << "stack1==stack2 is " <<
((stack1==stack2)? "True": "False") << endl << endl;
file:///D|/97/c++_1/LIBREF.TXT (576 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 571 of 619
// Delete the top item from Stack2. Current Stack2 contains 4.0.
cout << "stack2.pop() s2=[4.0]" << endl;
stack2.pop();
// Delete another item from Stack2. Stack2 should be empty.
cout << "stack2.pop() s2=[]" << endl;
stack2.pop();
// Push item 8.0 to Stack2.
cout << "stack2.push(8.0) s2=[8.0]" << endl;
stack2.push(8.0);
// Compare Stack1 and Stack2. Should return False.
cout << "stack1==stack2 is " <<
((stack1==stack2)? "True": "False") << endl << endl;
}
Program Output is:
stack1.push(4.0) s1=[4.0]
stack1.push(3.0) s1=[3.0 4.0]
stack2.push(4.0) s2=[4.0]
stack1==stack2 is False
stack2.push(6.0) s2=[6.0 4.0]
stack1==stack2 is False
stack2.push(8.0) s2=[8.0 6.0 4.0]
stack1==stack2 is False
stack2.pop() s2=[6.0 4.0]
stack2.pop() s2=[4.0]
stack2.push(3.0) s2=[3.0 4.0]
stack1==stack2 is True
stack2.pop() s2=[4.0]
stack2.pop() s2=[]
stack2.push(8.0) s2=[8.0]
stack1==stack2 is False
stack::operator< (STL Sample)
The sample code below illustrates how to use the stack::operator<<
STL function in Visual C++.
Required Header:
<stack>
Prototype:
template<class _TYPE, class _C, class _A>
bool stack::operator<(const stack<_TYPE, _C, _A>& _X) const;
file:///D|/97/c++_1/LIBREF.TXT (577 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 572 of 619
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The stack::operator< function returns true if the stack on the left
side of the operator is less than the stack on the right side. The
following steps are used to determine if one stack is less than
another stack: 1. Compare the bottom-most (very first element
pushed onto the stack). 2. If the elements are different, the stack
with the smaller element is less than the stack with the greater
element. Go to Step 5. 3. If the elements are the same and there
are more elements, move to the next element in the stack and go
back to step 2. 4. If all the elements in the stacks are processed
at this point, the stacks are equal. 5. Done.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StackLessThan.cpp : Illustrates how to use the stack::operator<
// function to determine if one stack is less th
// another stack.
//
// Functions:
//
// operator< : Returns true if the stack is smaller than the sta
// passed as the operand.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <iostream>
using namespace std ;
typedef stack<double> STACK_DOUBLE;
void main()
{
STACK_DOUBLE stack1,stack2;
// Add item 4.0 to Stack1. Stack1 contains 4.0.
cout << "stack1.push(4.0) s1=[4.0]" << endl;
stack1.push(4.0);
// Add item 3.0 to Stack1. Stack1 contains 3.0(top) and 4.0(botto
cout << "stack1.push(3.0) s1=[3.0 4.0]" << endl;
stack1.push(3.0);
// Add item 4.0 to Stack2. Stack2 contains 4.0 (top=bottom).
cout << "stack2.push(4.0) s2=[4.0]" << endl;
stack2.push(4.0);
file:///D|/97/c++_1/LIBREF.TXT (578 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 573 of 619
// Compare if Stack1 is smaller than Stack2. Should return False.
cout << "stack1<stack2 is " <<
((stack1<stack2)? "True": "False") << endl << endl;
// Add item 6.0 to Stack2. Stack2 contains 6.0(top) and 4.0(botto
cout << "stack2.push(6.0) s2=[6.0 4.0]" << endl;
stack2.push(6.0);
// Compare if Stack1 is smaller than Stack2. Should return True.
cout << "stack1<stack2 is " <<
((stack1<stack2)? "True": "False") << endl << endl;
// Add item 8.0 to Stack2. Stack2 contains 8.0(top), 6.0 and
// 4.0(bottom).
cout << "stack2.push(8.0) s2=[8.0 6.0 4.0]" << endl;
stack2.push(8.0);
// Compare if Stack1 is smaller than Stack2. Should return True.
cout << "stack1<stack2 is " <<
((stack1<stack2)? "True": "False") << endl << endl;
// Delete item 8.0 from Stack2.
cout << "stack2.pop() s2=[6.0 4.0]" << endl;
stack2.pop();
// Delete item 6.0 from Stack2.
cout << "stack2.pop() s2=[4.0]" << endl;
stack2.pop();
// Add item 3.0 to Stack2. Stack2 contains 3.0(top) and 4.0(botto
cout << "stack2.push(3.0) s2=[3.0 4.0]" << endl;
stack2.push(3.0);
// Compare if Stack1 is smaller than Stack2. Should return False.
cout << "stack1<stack2 is " <<
((stack1<stack2)? "True": "False") << endl << endl;
// Delete item 3.0 from Stack2.
cout << "stack2.pop() s2=[4.0]" << endl;
stack2.pop();
// Delete item 4.0 from Stack2.
cout << "stack2.pop() s2=[]" << endl;
stack2.pop();
// Add item 8.0 to Stack2. Stack2 contains 8.0(top=bottom).
cout << "stack2.push(8.0) s2=[8.0]" << endl;
stack2.push(8.0);
// Compare if Stack1 is smaller than Stack2. Should return True.
cout << "stack1<stack2 is " <<
((stack1<stack2)? "True": "False") << endl << endl;
}
Program Output is:
file:///D|/97/c++_1/LIBREF.TXT (579 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 574 of 619
stack1.push(4.0) s1=[4.0]
stack1.push(3.0) s1=[3.0 4.0]
stack2.push(4.0) s2=[4.0]
stack1<stack2 is False
stack2.push(6.0) s2=[6.0 4.0]
stack1<stack2 is True
stack2.push(8.0) s2=[8.0 6.0 4.0]
stack1<stack2 is True
stack2.pop() s2=[6.0 4.0]
stack2.pop() s2=[4.0]
stack2.push(3.0) s2=[3.0 4.0]
stack1<stack2 is False
stack2.pop() s2=[4.0]
stack2.pop() s2=[]
stack2.push(8.0) s2=[8.0]
stack1<stack2 is True
stack::size (STL Sample)
The sample code below illustrates how to use the stack::size STL
function in Visual C++.
Required Header:
<stack>
Prototype:
template<class _TYPE, class _C, class _A>
size_type stack::size() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The stack::size function returns the number of elements in the
stack. It is okay to call this function with an empty stack; it
will return a value of 0.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StackSize.cpp : Illustrates how to use the size function to deter
// the number of elements on the stack.
//
// Functions:
//
// size : returns the number of elements in the stack.
file:///D|/97/c++_1/LIBREF.TXT (580 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 575 of 619
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <string>
#include <iostream>
using namespace std ;
typedef stack<string> STACK_STRING;
void main()
{
STACK_STRING stack1;
// Check the size of an empty stack. Should return 0.
cout << "stack1.size() equals " << stack1.size() << endl;
// Add item "Hello" to Stack1.
cout << "stack1.push('Hello')" << endl;
stack1.push("Hello");
// Add item "This is the second element" to Stack1.
cout << "stack1.push('This is the second element')" << endl;
stack1.push("This is the second element");
// Check the size of Stack1. Should return 2.
cout << "stack1.size() equals " << stack1.size() << endl << endl;
// Add item "Third element" to Stack1.
cout << "stack1.push('Third element')" << endl;
stack1.push("Third element");
// Check the size of Stack1. Should return 3.
cout << "stack1.size() equals " << stack1.size() << endl << endl;
// Pop "Third element".
cout << "stack1.pop()" << endl;
stack1.pop();
// Pop "This is the second element".
cout << "stack1.pop()" << endl;
stack1.pop();
// Check the size of Stack1 again. Should return 1.
cout << "stack1.size() equals " << stack1.size() << endl << endl
// Pop "Hello".
cout << "stack1.pop()" << endl;
stack1.pop();
// Check the size of Stack1. Should return 0.
cout << "stack1.size() equals " << stack1.size() << endl << endl;
}
file:///D|/97/c++_1/LIBREF.TXT (581 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 576 of 619
Program Output is:
stack1.size() equals 0
stack1.push('Hello')
stack1.push('This is the second element')
stack1.size() equals 2
stack1.push('Third element')
stack1.size() equals 3
stack1.pop()
stack1.pop()
stack1.size() equals 1
stack1.pop()
stack1.size() equals 0
stack::top and stack::empty (STL Sample)
The sample code below illustrates how to use the stack::top and
stack::empty STL functions in Visual C++.
Required Header:
<stack>
Prototype:
template<class _TYPE, class _C, class _A> // Function 1
value_type& stack::top();
template<class _TYPE, class _C, class _A> // Function 2
const value_type& stack::top() const;
template<class _TYPE, class _C, class _A> // Function 3
bool stack::empty() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The top function returns the topmost element of the stack. You
should ensure that there are one or more elements on the stack
before calling the top function. The first version of the top
function returns a reference to the element of the top of the
stack, allowing you to modify the value. The second function
returns a constant reference, ensuring that you don't accidentally
modify the stack. The empty function returns true if there are no
elements in the stack. If there are one or more elements, the
function will return false. You should use the empty function to
verify that there are elements left on the stack before calling the
top function.
Sample Code:
file:///D|/97/c++_1/LIBREF.TXT (582 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 577 of 619
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StackTop&Empty.cpp : Illustrates how to use the top function to
// retrieve the last element of the controlled
// sequence. It also illustrates how to use the
// empty function to loop though the stack.
// Functions:
//
// top : returns the top element of the stack.
// empty : returns true if the stack has 0 elements.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <iostream>
using namespace std ;
typedef stack<int> STACK_INT;
void main()
{
STACK_INT stack1;
cout << "stack1.empty() returned " <<
(stack1.empty()? "true": "false") << endl; // Function 3
cout << "stack1.push(2)" << endl;
stack1.push(2);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(5)" << endl;
stack1.push(5);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(11)" << endl;
stack1.push(11);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
// Modify the top item. Set it to 6.
if (!stack1.empty()) { // Function 3
cout << "stack1.top()=6;" << endl;
stack1.top()=6; // Function 1
}
file:///D|/97/c++_1/LIBREF.TXT (583 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 578 of 619
// Repeat until stack is empty
while (!stack1.empty()) { // Function 3
const int& t=stack1.top(); // Function 2
cout << "stack1.top() returned " << t << endl;
cout << "stack1.pop()" << endl;
stack1.pop();
}
}
Program Output is:
stack1.empty() returned true
stack1.push(2)
stack1.top() returned 2
stack1.push(5)
stack1.top() returned 5
stack1.push(11)
stack1.top() returned 11
stack1.top()=6;
stack1.top() returned 6
stack1.pop()
stack1.top() returned 5
stack1.pop()
stack1.top() returned 2
stack1.pop()
string::getline (STL Sample)
The sample code below illustrates how to use the string::getline
STL function in Visual C++.
Required Header:
<string>
Prototype:
template<class _E, class _TYPE, class _A> inline
basic_istream<_E, _TYPE>& getline( basic_istream<_E, _TYPE>& Is
basic_string<_E, _TYPE, _A>& Xstring,
const _E _D=_TYPE::newline());
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The getline function creates a string containing all of the
characters from the input stream until one of the following
situations occurs: - End of file. - The delimiter is encountered. -
is.max_str() elements have been extracted.
Sample Code:
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (584 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 579 of 619
//
// Compile options needed: /GX
//
// Getline.cpp : Illustrates how to use the getline function to read
// line of text from the keyboard.
//
// Functions:
//
// getline Returns a string from the input stream.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void main()
{
string s1;
cout << "Enter a sentence (use <space> as the delimiter):";
getline(cin,s1, ' ');
cout << "You entered: " << s1;
}
Program Output is:
Enter a sentence (use <space> as the delimiter): A_space_at_the_end.
You entered: A_space_at_the_end.
string::operator== (STL Sample)
The sample code below illustrates how to use the string::operator==
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator==(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator==(const _E * LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Function 3:
template<class _E, class _TYPE, class _A> inline
bool operator==(const basic_string<_E, _TYPE, _A>& LString,
const basic_string<_E, _TYPE, _A>& RString);
file:///D|/97/c++_1/LIBREF.TXT (585 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 580 of 619
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are three versions of the string::operator== function. The
first two functions compare a null-terminated character array
against a basic_string. They perform this operation by using the
basic_string's string::compare function and returning true if the
compare function returns a 0 value. The third function compares two
basic_string variables, using the string::compare function of the
first basic_string variable. For more information on the compare
function, see the string::compare function. Note that this operator
does not work with NULL pointer for the character array. You will
need to make sure that the character array is not NULL before you
pass it to the operator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringEqual.cpp: Illustrates how to use the operator== to test fo
// equality of a basic_string variable and a
// null-terminated string. It also illustrates how
// use the operator== to test for equality of two
// basic_string variables.
//
// Functions:
//
// operator== returns true if the basic_string and the null-
// terminated string are equal.
// operator== returns true if both basic_strings are equal.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void trueFalse(int x)
{
cout << (x? "True": "False") << endl;
}
void main()
{
string S1="ABC";
string S2="ABC";
string S3="DEF";
string S4; //This specifies an empty initial-controlled sequence.
char CP1[]="abc";
char CP2[]="DEF";
char *CP3 = NULL;
file:///D|/97/c++_1/LIBREF.TXT (586 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 581 of 619
cout << "S1 is " << S1 << endl;
cout << "S2 is " << S2 << endl;
cout << "S3 is " << S3 << endl;
cout << "S4 is " << S4 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "S1==CP1 returned ";
trueFalse(S1==CP1); // False (calls function 1)
cout << "S1==CP2 returned ";
trueFalse(S1==CP2); // False (calls function 1)
cout << "CP1==S1 returned ";
trueFalse(CP1==S1); // False (calls function 2)
cout << "CP2==S1 returned ";
trueFalse(CP2==S1); // False (calls function 2)
cout << "S1==S2 returned ";
trueFalse(S1==S2); // True (calls function 3)
cout << "S1==S3 returned ";
trueFalse(S1==S3); // False (calls function 3)
cout << "S1==S4 returned ";
trueFalse(S1==S4); // False (calls function 3)
// Following use of the operator will cause the program to
// crash since CP3 is NULL.
// cout << "S1==CP3 returned ";
// trueFalse(S1==CP3);
}
Program Output is:
S1 is ABC
S2 is ABC
S3 is DEF
S4 is
CP1 is abc
CP2 is DEF
S1==CP1 returned False
S1==CP2 returned False
CP1==S1 returned False
CP2==S1 returned False
S1==S2 returned True
S1==S3 returned False
S1==S4 returned False
string::operator> (STL Sample)
The sample code below illustrates how to use the string::operator>
file:///D|/97/c++_1/LIBREF.TXT (587 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 582 of 619
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator>(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator>(const _E *LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are two versions of the string::operator> function. Both
versions are used to compare a null-terminated character array to a
basic_string. They perform this operation by returning the result
of (RString<LCharArray or RCharArray<LString). For more information
on this comparison, see the string::operator< function. Note that
this operator does not work with NULL pointer for the character
array. You will need to make sure that the character array is not
NULL before you pass it to the operator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringGreaterThan.cpp : Illustrates how to use the operator> to
// compare a basic_string variable to a
// null-terminated string.
//
// Functions:
//
// operator> Returns true if the second parameter is less than
// the first.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void trueFalse(int x)
{
cout << (x? "True": "False") << endl;
file:///D|/97/c++_1/LIBREF.TXT (588 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 583 of 619
void main()
{
string S1="ABC";
char CP1[]="ABC";
char CP2[]="DEF";
char CP3[]="ABCD";
char CP4[]="abc";
cout << "S1 is " << S1 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "CP3 is " << CP3 << endl;
cout << "CP4 is " << CP4 << endl;
cout << "S1>CP1 returned ";
trueFalse(S1>CP1); // False (calls function 1)
cout << "S1>CP2 returned ";
trueFalse(S1>CP2); // False (calls function 1)
cout << "S1>CP4 returned ";
trueFalse(S1>CP4); // False (calls function 1)
cout << "CP1>S1 returned ";
trueFalse(CP1>S1); // False (calls function 2)
cout << "CP2>S1 returned ";
trueFalse(CP2>S1); // True (calls function 2)
cout << "CP3>S1 returned ";
trueFalse(CP3>S1); // True (calls function 2)
}
Program Output is:
S1 is ABC
CP1 is ABC
CP2 is DEF
CP3 is ABCD
CP4 is abc
S1>CP1 returned False
S1>CP2 returned False
S1>CP4 returned False
CP1>S1 returned False
CP2>S1 returned True
CP3>S1 returned True
string::operator>= (STL Sample)
The sample code below illustrates how to use the string::operator>=
STL function in Visual C++.
Required Header:
file:///D|/97/c++_1/LIBREF.TXT (589 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 584 of 619
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator>=(const basic_string<_E, _TYPE, _A>& _L,
const _E *_R);
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator>=(const _E * _L,
const basic_string<_E, _TYPE, _A>& _R);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are two versions of the string::operator>= function. Both
versions are used to compare a null-terminated character array
against a basic_string. They perform this operation by negating the
result of (_L < _R). For more information on this comparison,
please see the string::operator< function.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: none
//
// StringGreaterEqual.cpp:
// Illustrates how to use the operator>= to compare a
// basic_string variable and a null-terminated string.
//
// Functions:
//
// operator>= Returns true if the first parameter is not less
// the second.
//
// Written by Derek Jamison
// of Microsoft AnswerPoint Support,
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void truefalse(int x)
{
cout << (x?"True":"False") << endl;
}
file:///D|/97/c++_1/LIBREF.TXT (590 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 585 of 619
void main()
{
string S1="ABC";
char CP1[4]="ABC";
char CP2[4]="DEF";
cout << "S1 is " << S1 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "S1>=CP1 returned ";
truefalse(S1>=CP1); // True (calls function 1)
cout << "S1>=CP2 returned ";
truefalse(S1>=CP2); // False (calls function 1)
cout << "CP1>=S1 returned ";
truefalse(CP1>=S1); // True (calls function 2)
cout << "CP2>=S1 returned ";
truefalse(CP2>=S1); // True (calls function 2)
}
Program Output is:
S1 is ABC
CP1 is ABC
CP2 is DEF
S1>=CP1 returned True
S1>=CP2 returned False
CP1>=S1 returned True
CP2>=S1 returned True
string::operator>> (STL Sample)
The sample code below illustrates how to use the string::operator>>
STL function in Visual C++.
Required Header:
<string>
Prototype:
template<class E, class TYPE, class A> inline
basic_istream<E, TYPE>&
operator>>(basic_istream<E, TYPE>& InStream,
basic_string<E, TYPE, A>& String);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
file:///D|/97/c++_1/LIBREF.TXT (591 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 586 of 619
Description:
The operator>> is used to populate a string with the contents of an
input stream.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringExtract.cpp : Illustrates how to use the operator>> to extr
// a string from an input stream, populating a s
// variable with the contents.
//
// Functions:
//
// operator>> Extracts a string from an input stream.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void main()
{
string s1;
cout << "Enter a word: ";
cin >> s1;
cout << endl << "You entered: " << s1;
}
Program Output is:
Enter a word: Sample
You entered: Sample
string::operator< (STL Sample)
The sample code below illustrates how to use the string::operator<
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator<(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
file:///D|/97/c++_1/LIBREF.TXT (592 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 587 of 619
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator<(const _E *LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Function 3:
template<class _E, class _TYPE, class _A> inline
bool operator<(const basic_string<_E, _TYPE, _A>& LString,
const basic_string<_E, _TYPE, _A>& RString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are three versions of the string::operator< function. Two of
the functions compare a null-terminated character array against a
basic_string. They perform this operation by using the
basic_string's string::compare function and returning a value based
on the results of the compare function. The third function compares
two basic_string variables, using the string::compare function of
the first basic_string variable. For more information on the
compare function, please see the string::compare function. Note
that this operator does not work with NULL pointer for the
character array. You will need to make sure that the character
array is not NULL before you pass it to the operator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringLessThan.cpp : Illustrates how to use the operator< to comp
// a basic_string variable and a null-terminate
// string. It also illustrates how to use the
// operator< to compare two basic_string variab
//
// Functions:
//
// operator< Returns true if the first parameter is less than
// second.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void trueFalse(int x)
{
cout << (x? "True": "False") << endl;
}
void main()
{
file:///D|/97/c++_1/LIBREF.TXT (593 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 588 of 619
string S1="ABC";
string S2="ABC";
string S3="DEF";
string S4="abc";
char CP1[]="ABC";
char CP2[]="DEF";
char CP3[]="ABCD";
cout << "S1 is " << S1 << endl;
cout << "S2 is " << S2 << endl;
cout << "S3 is " << S3 << endl;
cout << "S4 is " << S4 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "CP3 is " << CP3 << endl;
cout << "S1<CP1 returned ";
trueFalse(S1<CP1); // False (calls function 1)
cout << "S1<CP2 returned ";
trueFalse(S1<CP2); // True (calls function 1)
cout << "CP1<S1 returned ";
trueFalse(CP1<S1); // False (calls function 2)
cout << "CP2<S1 returned ";
trueFalse(CP2<S1); // False (calls function 2)
cout << "S1<S2 returned ";
trueFalse(S1<S2); // False (calls function 3)
cout << "S1<S3 returned ";
trueFalse(S1<S3); // True (calls function 3)
cout << "S1<S4 returned ";
trueFalse(S1<S4); // True (calls function 3)
cout << "S1<CP3 returned ";
trueFalse(S1<CP3); // True (calls function 1)
}
Program Output is:
S1 is ABC
S2 is ABC
S3 is DEF
S4 is abc
CP1 is ABC
CP2 is DEF
CP3 is ABCD
S1<CP1 returned False
S1<CP2 returned True
CP1<S1 returned False
CP2<S1 returned False
S1<S2 returned False
file:///D|/97/c++_1/LIBREF.TXT (594 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 589 of 619
S1<S3 returned True
S1<S4 returned True
S1<CP3 returned True
string::operator<= (STL Sample)
The sample code below illustrates how to use the string::operator<=
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator<=(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator<=(const _E * LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are two versions of the string::operator<= function. Both
versions are used to compare a null-terminated character array to a
basic_string. They perform this operation by negating the result of
(RString<LCharArray or RCharArray<LString). For more information on
this comparison, please see the string::operator< function. Note
that this operator does not work with NULL pointer for the
character array. You will need to make sure that the character
array is not NULL before you pass it to the operator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringLessEqual.cpp : Illustrates how to use the operator<= to co
// a basic_string variable to a null-terminate
// string.
//
// Functions:
//
// operator<= Returns true if the second parameter is not less
// than the first.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
file:///D|/97/c++_1/LIBREF.TXT (595 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 590 of 619
#include <iostream>
using namespace std ;
void trueFalse(int x)
{
cout << (x? "True": "False") << endl;
}
void main()
{
string S1="DEF";
char CP1[]="ABC";
char CP2[]="DEF";
char CP3[]="DEFG";
char CP4[]="def";
cout << "S1 is " << S1 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "CP3 is " << CP3 << endl;
cout << "CP4 is " << CP4 << endl;
cout << "S1<=CP1 returned ";
trueFalse(S1<=CP1); // False (calls function 1)
cout << "S1<=CP2 returned ";
trueFalse(S1<=CP2); // True (calls function 1)
cout << "S1<=CP3 returned ";
trueFalse(S1<=CP3); // True (calls function 1)
cout << "CP1<=S1 returned ";
trueFalse(CP1<=S1); // True (calls function 2)
cout << "CP2<=S1 returned ";
trueFalse(CP2<=S1); // True (calls function 2)
cout << "CP4<=S1 returned ";
trueFalse(CP4<=S1); // False (calls function 2)
}
Program Output is:
S1 is DEF
CP1 is ABC
CP2 is DEF
CP3 is DEFG
CP4 is def
S1<=CP1 returned False
S1<=CP2 returned True
S1<=CP3 returned True
CP1<=S1 returned True
CP2<=S1 returned True
CP4<=S1 returned False
file:///D|/97/c++_1/LIBREF.TXT (596 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 591 of 619
string::operator<< (STL Sample)
The sample code below illustrates how to use the string::operator<<
STL function in Visual C++.
Required Header:
<string>
Prototype:
template<class _E, class _TYPE, class _A> inline
basic_ostream<_E, _TYPE>&
operator<<( basic_ostream<_E, _TYPE>& OStream,
const basic_string<_E, _TYPE, _A>& XString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The operator<< is used to insert a string into an output stream.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringInsertion.cpp : Illustrates how to use the insertion operat
// (operator<<) to insert a string into an out
// stream.
//
// Functions:
//
// operator<< Inserts a string into an output stream.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void main()
{
string msg="Hello! This is the insertion operator.";
cout << msg << endl;
}
Program Output is:
Hello! This is the insertion operator.
file:///D|/97/c++_1/LIBREF.TXT (597 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 592 of 619
string::operator+ (STL Sample)
The sample code below illustrates how to use the string::operator+
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
basic_string<_E, _TYPE, _A>
operator+(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
Function 2:
template<class _E, class _TYPE, class _A> inline
basic_string<_E, _TYPE, _A>
operator+(const _E *LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Function 3:
template<class _E, class _TYPE, class _A> inline
basic_string<_E, _TYPE, _A>
operator+(const basic_string<_E, _TYPE, _A>& LString,
const _E RChar);
Function 4:
template<class _E, class _TYPE, class _A> inline
basic_string<_E, _TYPE, _A>
operator+(const _E LChar,
const basic_string<_E, _TYPE, _A>& RString);
Function 5:
template<class _E, class _TYPE, class _A> inline
basic_string<_E, _TYPE, _A>
operator+(const basic_string<_E, _TYPE, _A>& LString,
const basic_string<_E, _TYPE, _A>& RString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are five versions of the string::operator+ function. Two
functions are used to concatenate a null-terminated character array
and a basic_string. Two functions are used to concatenate a
character and a basic_string. The last function is used to
concatenate two basic_string variables.
Sample Code:
////////////////////////////////////////////////////////////////////
//
file:///D|/97/c++_1/LIBREF.TXT (598 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 593 of 619
// Compile options needed: /GX
//
// StringPlus.cpp : Illustrates how to use the operator+ to concaten
// a null-terminated character array and a basic_st
// how to concatenate a character and a basic_strin
// and how to concatenate two basic_string variable
//
// Functions:
//
// operator+ : Concatenates a null-terminated character array and
// a basic_string.
// operator+ : Concatenates a character array and a basic_string.
// operator+ : Concatenates two basic_string variables.
////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void main()
{
string result;
string S1="ABC";
string S2="DEF";
char CP1[]="GHI";
char C='J';
cout << "S1 is " << S1 << endl;
cout << "S2 is " << S2 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "C is " << C << endl;
result=S1+CP1; // Function 1 (ABCGHI)
cout << "S1+CP1 is " << result << endl;
result=CP1+S1; // Function 2 (GHIABC)
cout << "CP1+S1 is " << result << endl;
result=S1+S2; // Function 3 (ABCDEF)
cout << "S1+S2 is " << result << endl;
result=S1+C; // Function 4 (ABCJ)
cout << "S1+C is " << result << endl;
result=C+S1; // Function 5 (JABC)
cout << "C+S1 is " << result << endl;
}
Program Output is:
S1 is ABC
S2 is DEF
CP1 is GHI
file:///D|/97/c++_1/LIBREF.TXT (599 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 594 of 619
C is J
S1+CP1 is ABCGHI
CP1+S1 is GHIABC
S1+S2 is ABCDEF
S1+C is ABCJ
C+S1 is JABC
string::operator!= (STL Sample)
The sample code below illustrates how to use the string::operator!=
STL function in Visual C++.
Required Header:
<string>
Prototype:
Function 1:
template<class _E, class _TYPE, class _A> inline
bool operator!=(const basic_string<_E, _TYPE, _A>& LString,
const _E *RCharArray);
Function 2:
template<class _E, class _TYPE, class _A> inline
bool operator!=(const _E *LCharArray,
const basic_string<_E, _TYPE, _A>& RString);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
There are two versions of the string::operator!= function. Both
versions are used to compare a null-terminated character array
against a basic_string. They perform this operation by negating the
result of (LString==RCharArray) or (LCharArray==RString). For more
information on this comparison, please see the string::operator==
function. Notice that this operator does not work with NULL pointer
for the character array. You will need to make sure that the
character array is not NULL before you pass it to the operator.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// StringNotEqual.cpp : Illustrates how to use the operator!= to tes
// non-equality of a basic_string variable and
// null-terminated string.
//
// Functions:
//
// operator!= Returns true if the basic_string and the null-
// terminated string are not equal.
////////////////////////////////////////////////////////////////////
file:///D|/97/c++_1/LIBREF.TXT (600 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 595 of 619
#pragma warning(disable:4786)
#include <string>
#include <iostream>
using namespace std ;
void trueFalse(int x)
{
cout << (x? "True": "False") << endl;
}
void main()
{
string S1="ABC";
char CP1[]="ABC";
char CP2[]="DEF";
char CP3[]="abc";
cout << "S1 is " << S1 << endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "CP3 is " << CP3 << endl;
cout << "S1!=CP1 returned ";
trueFalse(S1!=CP1); // False (calls function 1)
cout << "S1!=CP2 returned ";
trueFalse(S1!=CP2); // True (calls function 1)
cout << "S1!=CP3 returned ";
trueFalse(S1!=CP3); // True (calls function 1)
cout << "CP1!=S1 returned ";
trueFalse(CP1!=S1); // False (calls function 2)
cout << "CP2!=S1 returned ";
trueFalse(CP2!=S1); // True (calls function 2)
cout << "CP3!=S1 returned ";
trueFalse(CP3!=S1); // True (calls function 2)
}
Program Output is:
S1 is ABC
CP1 is ABC
CP2 is DEF
CP3 is abc
S1!=CP1 returned False
S1!=CP2 returned True
S1!=CP3 returned True
CP1!=S1 returned False
CP2!=S1 returned True
CP3!=S1 returned True
file:///D|/97/c++_1/LIBREF.TXT (601 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 596 of 619
Trigonometry Functions (Sample)
The sample code below illustrates how to use trigonometry (sin,
cos, tan, and so on) functions in Visual C++.
Required Header:
<valarray>
Prototype:
// acos
template<class T>
inline valarray<T> acos(const valarray<T>& x);
// asin
template<class T>
inline valarray<T> asin(const valarray<T>& x);
// atan
template<class T>
inline valarray<T> atan(const valarray<T>& x);
// atan2
template<class T>
inline valarray<T> atan2(const valarray<T>& x, const valarray<T
template<class T>
inline valarray<T> atan2(const valarray<T> x, const T& y);
template<class T>
inline valarray<T> atan2(const T& x, const valarray<T>& y);
// cos
template<class T>
inline valarray<T> cos(const valarray<T>& x);
// cosh
template<class T>
inline valarray<T> cosh(const valarray<T>& x);
// sin
template<class T>
inline valarray<T> sin(const valarray<T>& x);
// sinh
template<class T>
inline valarray<T> sinh(const valarray<T>& x);
// tan
template<class T>
inline valarray<T> tan(const valarray<T>& x);
// tanh
template<class T>
inline valarray<T> tanh(const valarray<T>& x);
file:///D|/97/c++_1/LIBREF.TXT (602 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 597 of 619
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
This article illustrates the use of STL trigonometry functions
through sample code.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// main.cpp : Illustrates the use of STL trigonometry functions.
//
// Functions:
//
// acos, asin, atan, atan2, cos, cosh, sin, sinh, tan, tanh
////////////////////////////////////////////////////////////////////
#include <iostream> // for i/o functions
#include <valarray> // for valarray
#include <cmath> // for trigonometry functions
using namespace std ;
#define ARRAY_SIZE 3 // array size
void main()
{
// Initialize val_array to values -1, 0 and 1.
valarray<double> val_array(ARRAY_SIZE);
for (int i = 0; i < ARRAY_SIZE; i++)
val_array[i] = i - 1;
// Display the size of val_array.
cout << "Size of val_array = " << val_array.size() << endl;
// Display the values of val_array before calling any trigonomet
// functions.
cout << "The values in val_array:" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << val_array[i] << " ";
cout << endl << endl;
// Initialize rev_valarray that is the reverse of val_array.
valarray<double> rev_valarray(ARRAY_SIZE);
for (i = 0; i < ARRAY_SIZE; i++)
rev_valarray[i] = val_array[ARRAY_SIZE - i - 1];
// Display the size of rev_valarray.
cout << "Size of rev_valarray = " << rev_valarray.size() << endl
// Display the values of rev_valarray.
cout << "The values in rev_valarray:" << endl;
file:///D|/97/c++_1/LIBREF.TXT (603 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 598 of 619
for (i = 0; i < ARRAY_SIZE; i++)
cout << rev_valarray[i] << " ";
cout << endl << endl;
// rvalue_array to hold the return value from calling the trigon
// functions.
valarray<double> rvalue_array;
// -------------------------------------------------------------
// acos() - display the result of rvalue_array
// -------------------------------------------------------------
rvalue_array = acos(val_array);
cout << "The result after calling acos():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// asin() - display the result of rvalue_array
// -------------------------------------------------------------
rvalue_array = asin(val_array);
cout << "The result after calling asin():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// atan() - display the result of rvalue_array
// -------------------------------------------------------------
rvalue_array = atan(val_array);
cout << "The result after calling atan():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// atan2() - display the result of rvalue_array
// -------------------------------------------------------------
// This template function returns an object of class valarray<T>
// each of whose elements at I is the arctangent of x[I] / y[I].
rvalue_array = atan2(val_array, rev_valarray);
cout << "The result after calling atan2(val_array, rev_valarray)
<< endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// This template function stores in element I the arctangent of
// x[I] / y.
rvalue_array = atan2(val_array, 3.1416);
cout << "The result after calling atan2(val_array, 3.1416):" <<
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// This template function stores in element I the arctangent of
file:///D|/97/c++_1/LIBREF.TXT (604 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 599 of 619
// x / y[I].
rvalue_array = atan2(3.1416, val_array);
cout << "The result after calling atan2(3.1416, val_array):" <<
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// cos() - display the result of rvalue_array
// -------------------------------------------------------------
rvalue_array = cos(val_array);
cout << "The result after calling cos():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// cosh() - display the result of rvalue_array
// -------------------------------------------------------------
rvalue_array = cosh(val_array);
cout << "The result after calling cosh():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// sin() - display the result of val_array
// -------------------------------------------------------------
rvalue_array = sin(val_array);
cout << "The result after calling sin():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// sinh() - display the result of val_array
// -------------------------------------------------------------
rvalue_array = sinh(val_array);
cout << "The result after calling sinh():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// tan() - display the result of val_array
// -------------------------------------------------------------
rvalue_array = tan(val_array);
cout << "The result after calling tan():" << endl;
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
// -------------------------------------------------------------
// tanh() - display the result of val_array
// -------------------------------------------------------------
rvalue_array = tanh(val_array);
cout << "The result after calling tanh():" << endl;
file:///D|/97/c++_1/LIBREF.TXT (605 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 600 of 619
for (i = 0; i < ARRAY_SIZE; i++)
cout << rvalue_array[i] << " ";
cout << endl << endl;
}
Program Output is:
Size of val_array = 3
The values in val_array:
-1 0 1
Size of rev_valarray = 3
The values in rev_valarray:
1 0 -1
The result after calling acos():
3.14159 1.5708 0
The result after calling asin():
-1.5708 0 1.5708
The result after calling atan():
-0.785398 0 0.785398
The result after calling atan2(val_array, rev_valarray):
-0.785398 0 2.35619
The result after calling atan2(val_array, 3.1416):
-0.308168 0 0.308168
The result after calling atan2(3.1416, val_array):
1.87896 1.5708 1.26263
The result after calling cos():
0.540302 1 0.540302
The result after calling cosh():
1.54308 1 1.54308
The result after calling sin():
-0.841471 0 0.841471
The result after calling sinh():
-1.1752 0 1.1752
The result after calling tan():
-1.55741 0 1.55741
The result after calling tanh():
-0.761594 0 0.761594
unary_function<> Structure (STL Sample)
The sample code below illustrates how to use the unary_function<>
file:///D|/97/c++_1/LIBREF.TXT (606 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 601 of 619
structure in Visual C++.
Required Header:
< functional >
Prototype:
template<class _A, class _R>
struct unary_function
{
typedef _A argument_type;
typedef _R result_type;
};
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
unary_function is used as a base class to better define operator
functions in the following format: result_type classname::operatorX
(argument_type).
Sample Code:
////////////////////////////////////////////
//
// Compile options needed: none
//
// Structure used:
// unary_function<int, float> - allows us
// to write operator functions accepting an
// integer and returning floats.
////////////////////////////////////////////
#include <functional>
#include <iostream>
using namespace std ;
/* derive class from unary_function in order to use it */
class unary_test : public unary_function<int,float>
{
public:
float value;
unary_test(){value=10.0;}
unary_test(float x){value=x;}
result_type operator*(argument_type x);
result_type operator-(argument_type x);
};
/* You can now easily create operators that accept */
/* an int and return a float. */
unary_test::result_type unary_test::operator*(unary_test::argument_t
file:///D|/97/c++_1/LIBREF.TXT (607 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 602 of 619
{
value*=x;
cout << "New value after * is " << value << endl ;
return value;
}
unary_test::result_type unary_test::operator-(unary_test::argument_t
{
value-+(float)x;
cout << "New value after minus is " << value << endl ;
return value;
}
void main(void)
{
unary_test item;
unary_test item2(18.0);
cout << "Begin" << endl ;
cout.setf(ios::fixed) ;
item = item * 2;
item2 = item2 - 5;
}
Program Output is:
Begin
New value after * is 20.000000
New value after minus is 18.000000
upper_bound (STL Sample)
The sample code below illustrates how to use the upper_bound STL
function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class T>
inline ForwardIterator upper_bound(ForwardIterator first, Forwa
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The upper_bound algorithm returns the last location in the sequence
that value can be inserted such that the order of the sequence is
maintained. upper_bound returns an iterator positioned at the
location that value can be inserted in the range [first..last), or
returns last if no such position exists. upper_bound assumes the
file:///D|/97/c++_1/LIBREF.TXT (608 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 603 of 619
range [first ..last) is sorted using operator<.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// upper_bound.cpp : Illustrates how to use the upper_bound
// function.
//
// Functions:
//
// upper_bound : Return the upper bound within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 10 ;
Numbers[3] = 30 ;
Numbers[4] = 69 ;
Numbers[5] = 70 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
file:///D|/97/c++_1/LIBREF.TXT (609 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 604 of 619
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//return the last location at which 10 can be inserted
// in Numbers
location = upper_bound(start, end, 10) ;
cout << "Element 10 can be inserted at index "
<< location - start << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
Element 10 can be inserted at index 3
Predicate Version of upper_bound (STL Sample)
The sample code below illustrates how to use the predicate version
of the upper_bound STL function in Visual C++.
Required Header:
<algorithm>
Prototype:
template<class ForwardIterator, class T, class Compare>
inline orwardIterator upper_bound(ForwardIterator first, Forwar
const T& value, Compare compare)
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The upper_bound algorithm returns the last location in the sequence
that value can be inserted such that the order of the sequence
[first..last) is maintained. upper_bound returns an iterator
positioned at the location that value can be inserted in the range
[first..last), or returns last if no such position exists. This
version assumes the range [first..last) is sorted sequentially
using the compare function.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
file:///D|/97/c++_1/LIBREF.TXT (610 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 605 of 619
// upper_bound.cpp : Illustrates how to use the predicate version
// of the upper_bound function.
//
// Functions:
//
// upper_bound : Return the upper bound within a range.
////////////////////////////////////////////////////////////////////
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it, location ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//sort Numbers using the function object less<int>()
//upper_bound assumes that Numbers is sorted
//using the "compare" (less<int>() in this case)
//function
sort(start, end, less<int>()) ;
file:///D|/97/c++_1/LIBREF.TXT (611 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 606 of 619
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//return the highest location at which 10 can be inserted
// in Numbers
location = upper_bound(start, end, 10, less<int>()) ;
cout << "Last location for element 10 in Numbers is: "
<< location - start << endl ;
}
Program Output is:
Numbers { 4 10 10 30 69 70 96 100 }
Last location for element 10 in Numbers is: 3
Vector Class, operator== (STL Sample)
The sample code below illustrates how to use the vector class
operator== STL function in Visual C++.
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A> inline
bool operator==(const vector<_TYPE, _A>& _X,
const vector<_TYPE, _A>& _Y);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares three empty vectors, of a user-defined class
called ID, each of which contains a Name string member and a Score
integer member. It creates three vectors of IDs, then compares
vectors using the operator== as defined for ID.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// Opequal.cpp : Illustrates how to define the operator== to comp
// vectors.
//
// Functions:
file:///D|/97/c++_1/LIBREF.TXT (612 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 607 of 619
//
// vector::operator== - Vector equality comparison.
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disab
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std ;
using namespace std::rel_ops ;
// The ID class is used for team scoring. It holds each player's nam
// and score.
class ID
{
public:
string Name;
int Score;
ID() : Name(""), Score(0) {}
ID(string NewName, int NewScore) : Name(NewName), Score(NewScore
};
// In this example, an ID is equivalent only if both name and score
bool operator==(const ID& x, const ID& y)
{
return (x.Name == y.Name) && (x.Score == y.Score);
}
// IDs will be sorted by Score, not by Name.
bool operator<(const ID& x, const ID& y)
{
return x.Score < y.Score;
}
// Define a template class for a vector of IDs.
typedef vector<ID> NAMEVECTOR;
void main()
{
// Declare 3 dynamically allocated vectors of names.
NAMEVECTOR Vector1, Vector2, Vector3;
// Create 3 short vectors of names.
Vector1.push_back(ID("Karen Palmer", 2));
Vector1.push_back(ID("Ada Campbell", 1));
Vector2.push_back(ID("John Woloschuk", 3));
file:///D|/97/c++_1/LIBREF.TXT (613 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 608 of 619
Vector2.push_back(ID("Grady Leno", 2));
Vector3.push_back(ID("Karen Palmer", 2));
Vector3.push_back(ID("Ada Campbell", 1));
// Compare Vector1 to Vector2 and show whether they're equivalen
Vector1 == Vector2 ? cout << "Vector1 == Vector2"
: cout << "Vector1 != Vector2";
cout << endl;
// Compare Vector1 to Vector3 and show whether they're equivalen
Vector1 == Vector3 ? cout << "Vector1 == Vector3"
: cout << "Vector1 != Vector3";
cout << endl;
Program Output is:
Vector1 != Vector2
Vector1 == Vector3
vector::empty, erase, and push_back (STL Sample)
The sample code below illustrates how to use the vector::(empty,
erase, push_back) STL functions in Visual C++.
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A>
void vector::push_back(const _TYPE& X);
template<class _TYPE, class _A>
iterator vector::erase(iterator Iterator);
template<class _TYPE, class _A>
iterator vector::erase(iterator First, iterator Last);
template<class _TYPE, class _A>
bool vector::empty() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares an empty vector of integers. It adds 10
integers to the vector, then displays the contents of the vector.
It deletes the sixth element by using erase, and then displays the
contents of the vector again. It deletes the rest of the elements
using a different form of erase, then displays the vector (now
empty) again. The ShowVector routine uses the empty function to
file:///D|/97/c++_1/LIBREF.TXT (614 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 609 of 619
determine whether to generate the contents of the vector.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// Empty.cpp -- Illustrates the vector::empty and vector::erase
// functions.
// Also demonstrates the vector::push_back function.
//
// Functions:
//
// vector::empty - Returns true if vector has no elements.
//
// vector::erase - Deletes elements from a vector (single & range
//
// vector::begin - Returns an iterator to start traversal of the
// vector.
//
// vector::end - Returns an iterator for the last element of the
// vector.
//
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
// vector::iterator - Traverses the vector.
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disab
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
const ARRAY_SIZE = 10;
void ShowVector(INTVECTOR &theVector);
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Intialize the vector to contain the numbers 0-9.
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back(cEachItem);
file:///D|/97/c++_1/LIBREF.TXT (615 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 610 of 619
Program Output is:
// Using void iterator erase(iterator Iterator) to
// delete the 6th element (Index starts with 0).
theVector.erase(theVector.begin() + 5);
// Output the contents of the dynamic vector of integers.
ShowVector(theVector);
// Using iterator erase(iterator First, iterator Last) to
// delete a range of elements all at once.
theVector.erase(theVector.begin(), theVector.end());
// Show what's left (actually, nothing).
ShowVector(theVector);
}
// Output the contents of the dynamic vector or display a
// message if the vector is empty.
void ShowVector(INTVECTOR &theVector)
{
// First see if there's anything in the vector. Quit if so.
if (theVector.empty())
{
cout << endl << "theVector is empty." << endl;
return;
}
// Iterator is used to loop through the vector.
INTVECTOR::iterator theIterator;
// Output contents of theVector.
cout << endl << "theVector [ " ;
for (theIterator = theVector.begin(); theIterator != theVector.e
theIterator++)
{
cout << *theIterator;
if (theIterator != theVector.end()-1) cout << ", ";
// cosmetics for the o
}
cout << " ]" << endl ;
}
Program Output is:
theVector [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
theVector [ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]
theVector is empty.
vector::front and vector::back (STL Sample)
The sample code below illustrates how to use the vector::front and
vector::back STL functions in Visual C++.
file:///D|/97/c++_1/LIBREF.TXT (616 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 611 of 619
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A>
reference vector::front();
template<class _TYPE, class _A>
reference vector::back();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares an empty vector of integers with the members
[100, 200, 300, 400]. It displays the first element of the vector
using vector::front to obtain it. It displays the last element of
the vector using vector::back to obtain it. It displays the number
of elements of the vector using vector::size. The sample erases the
last element of the vector using vector::end()-1, and then displays
the new last element using vector::back. It erases the first
element of the vector using vector::begin, and then displays the
new first element using vector::front. Finally, the sample displays
the number of elements remaining in the vector using vector::size.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// front.cpp: Illustrates the vector::front and vector::back meth
//
// Functions:
//
// vector::front - Returns reference to first element of vector.
//
// vector::back - Returns reference to last element of vector.
//
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
// vector::size - Returns number of elements in the vector.
//
// vector::begin - Returns an iterator to start traversal of the
//
// vector::end - Returns an iterator for the last element of the
//
// vector::erase - Deletes elements from a vector (single & range
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
file:///D|/97/c++_1/LIBREF.TXT (617 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 612 of 619
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is issue
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
const ARRAY_SIZE = 4;
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 40
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "First element: " << theVector.front() << endl;
cout << "Last element: " << theVector.back() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
// Delete the last element of the vector. Remember that the vect
// is 0-based, so theVector.end() actually points 1 element beyo
// the end.
theVector.erase(theVector.end() - 1);
cout << endl << "After erasing last element, new last element is
<< theVector.back() << endl;
// Delete the first element of the vector.
theVector.erase(theVector.begin());
cout << "After erasing first element, new first element is: "
<< theVector.front() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
}
Program Output is:
First element: 100
Last element: 400
Elements in vector: 4
After erasing last element, new last element is: 300
After erasing first element, new first element is: 200
Elements in vector: 2
Vector Class, operator< (STL Sample)
file:///D|/97/c++_1/LIBREF.TXT (618 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 613 of 619
The sample code below illustrates how to use the the vector class
operator< STL function in Visual C++.
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A> inline
bool operator<(const vector<_TYPE, _A>& _X,
const vector<_TYPE, _A>& _Y);
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares an empty vector of IDs, a user-defined type. It
initializes and adds four IDs to the vector in random order. It
sorts them using the operator< defined for ID and generates the
newly sorted vector. (Note that it sorts in order of Score, not
Name.)
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// Opless.cpp -- Illustrates the defining the < operator to sort
//
// Functions:
//
// operator< - Vector comparison operator.
//
// vector::begin - Returns an iterator to start traversal of the
//
// vector::end - Returns an iterator for the last element of the
//
// vector::iterator - Traverses the vector.
//
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
// sort algorithm - Sorts the vector.
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disab
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
file:///D|/97/c++_1/LIBREF.TXT (619 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 614 of 619
#include <string>
#include <algorithm>
using namespace std ;
// The ID class is used for team scoring. It holds each player's nam
// and score.
class ID
{
public:
string Name;
int Score;
ID() : Name(""), Score(0) {}
ID(string NewName, int NewScore) : Name(NewName), Score(NewScore
};
// In this example, an ID is equivalent only if both name and score
bool operator==(const ID& x, const ID& y)
{
return (x.Name == y.Name) && (x.Score == y.Score);
}
// IDs will be sorted by Score, not by Name.
bool operator<(const ID& x, const ID& y)
{
return x.Score < y.Score;
}
// Define a template class for a vector of IDs.
typedef vector<ID> NAMEVECTOR;
void main()
{
// Declare a dynamically allocated vector of IDs.
NAMEVECTOR theVector;
// Iterator is used to loop through the vector.
NAMEVECTOR::iterator theIterator;
// Create a pseudo-random vector of players and scores.
theVector.push_back(ID("Karen Palmer", 2));
theVector.push_back(ID("Ada Campbell", 1));
theVector.push_back(ID("John Woloschuk", 3));
theVector.push_back(ID("Grady Leno", 2));
for (theIterator = theVector.begin(); theIterator != theVector.e
theIterator++)
cout << theIterator->Score << "\t"
<< theIterator->Name << endl;
cout << endl;
// Sort the vector of players by score.
sort(theVector.begin(), &theVector[theVector.size()]);
// Output the contents of the vector in its new, sorted order.
cout << "Players ranked by score:" << endl;
for (theIterator = theVector.begin(); theIterator != theVector.e
file:///D|/97/c++_1/LIBREF.TXT (620 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 615 of 619
theIterator++)
cout << theIterator->Score << "\t"
<< theIterator->Name << endl;
cout << endl << endl;
}
Program Output is:
Players and scores:
2 Karen Palmer
1 Ada Campbell
3 John Woloschuk
2 Grady Leno
Players ranked by score:
1 Ada Campbell
2 Karen Palmer
2 Grady Leno
3 John Woloschuk
vector::push_back and vector::pop_back (STL Sample)
The sample code below illustrates how to use the vector::push_back
and vector::pop_back STL functions in Visual C++.
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A>
void vector::push_back(const _TYPE& X);
template<class _TYPE, class _A>
void vector::pop_back();
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares an empty vector of integers. It adds three
integers to the vector, and then deletes one. Finally, it generates
the remaining elements in the vector.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// Pushpop.cpp: Illustrates how to use the push and pop member
// functions of the vector container.
//
file:///D|/97/c++_1/LIBREF.TXT (621 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 616 of 619
// Functions:
//
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
// vector::pop_back - Erases the last element of the vector.
//
// vector::begin - Returns an iterator to start traversal of the
//
// vector::end - Returns an iterator for the last element of the
//
// vector::iterator - Traverses the vector.
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disab
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Iterator is used to loop through the vector.
INTVECTOR::iterator theIterator;
// Add one element to the end of the vector, an int with the val
// Allocate memory if necessary.
theVector.push_back(42) ;
// Add two more elements to the end of the vector.
// theVector will contain [ 42, 1, 109 ].
theVector.push_back(1) ;
theVector.push_back(109) ;
// Erase last element in vector.
theVector.pop_back();
// Print contents of theVector. Shows [ 42, 1 ]
cout << "theVector [ " ;
for (theIterator = theVector.begin(); theIterator != theVector.e
theIterator++)
{
cout << *theIterator;
if (theIterator != theVector.end()-1) cout << ", ";
}
cout << " ]" << endl ;
file:///D|/97/c++_1/LIBREF.TXT (622 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 617 of 619
Program Output is:
theVector [ 42, 1 ]
vector::size, vector::capacity, and more (STL Sample)
The sample code below illustrates how to use the vector::size and
vector::capacity STL functions in Visual C++.
Required Header:
<vector>
Prototype:
template<class _TYPE, class _A>
void vector::reserve(size_type _N);
template<class _TYPE, class _A>
size_type vector::max_size() const;
template<class _TYPE, class _A>
void vector::resize(size_type _N, _TYPE _X = _TYPE());
template<class _TYPE, class _A>
size_type vector::capacity() const;
template<class _TYPE, class _A>
size_type vector::size() const;
Note: The class/parameter names in the prototype do not match the
version in the header file. Some have been modified to improve
readability.
Description:
The sample declares an empty vector of integers. It adds a single
integer element to the vector, and then shows information about the
vector's size, maximum size, and capacity. It reserves storage for
1000 elements and displays the same information about the vector.
Finally, it resizes the vector to 2000 elements, and then displays
the information.
Sample Code:
////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// Remax.cpp: Illustrates vector::reserve, vector::max_size,
// vector::resize, vector::resize, and vector::capacit
//
// Functions:
//
file:///D|/97/c++_1/LIBREF.TXT (623 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 618 of 619
// vector::max_size - Returns maximum number of elements vector c
// hold.
//
// vector::capacity - Returns number of elements for which memory
// been allocated.
//
// vector::size - Returns number of elements in the vector.
//
// vector::resize - Reallocates memory for vector, preserves its
// contents if new size is larger than existing
//
// vector::reserve - Allocates elements for vector to ensure a mi
// size, preserving its contents if the new siz
// larger than existing size.
//
// vector::push_back - Appends (inserts) an element to the end of
// vector, allocating memory for it if necess
//
////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disab
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Add one element to the end of the vector, an int with the val
theVector.push_back(42) ;
// Show statistics about vector.
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << e
// Ensure there's room for at least 1000 elements.
theVector.reserve(1000);
cout << endl << "After reserving storage for 1000 elements:" <<
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << e
// Ensure there's room for at least 2000 elements.
theVector.resize(2000);
cout << endl << "After resizing storage to 2000 elements:" << en
file:///D|/97/c++_1/LIBREF.TXT (624 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
Standard C++ Library Reference Page 619 of 619
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << e
}
Program Output is:
theVector's size is: 1
theVector's maximum size is: 1073741823
theVector's capacity is: 1
After reserving storage for 1000 elements:
theVector's size is: 1
theVector's maximum size is: 1073741823
theVector's capacity is: 1000
After resizing storage to 2000 elements:
theVector's size is: 2000
theVector's maximum size is: 1073741823
theVector's capacity is: 2000
file:///D|/97/c++_1/LIBREF.TXT (625 of 626) [28/10/2007 12:33:48 PM]
file:///D|/97/c++_1/LIBREF.TXT
file:///D|/97/c++_1/LIBREF.TXT (626 of 626) [28/10/2007 12:33:48 PM]