1 CXX The CXX command invokes the C++ compiler to compile C++ source programs. The syntax is as follows: CXX file-spec,... +library-file-spec/LIBRARY... Qualifiers indicate special actions to be performed by the compiler or special input file properties. Compiler qualifiers can apply to either the CXX command or to the specification of the file being compiled. When a qualifier follows the CXX command, it applies to all the files listed. When a qualifier follows the file specification, it applies only to the file immediately preceding it. For help on the C++ Class Library, type $ HELP CXXL For help on the Standard Library, type $ HELP CXXLSTD An HTML version of this online help is accessible from: file:/sys$common/syshlp/cxx$help/cphelp.htm 2 Command_Parameters file-spec,... One or more C++ source files separated by plus signs or commas. If plus signs are used, the input files are concatenated into a single object file. If commas are used, each file is compiled separately to create separate object files. If no input file type is specified, C++ assumes the .CXX default file type. library-file-spec A text library containing #include modules referenced in one or more of the source files. A library file specification must be concatenated with a file specification with a plus sign and qualified using the /LIBRARY qualifier. If the input file type is not specified, C++ assumes the .TLB default file type. Format CXX 2 Qualifiers /ALTERNATIVE_TOKENS /ALTERNATIVE_TOKENS /NOALTERNATIVE_TOKENS Enables use of the following operator keywords and digraphs to generate tokens: Operator Keyword Token and && and_eq &= bitand & bitor | compl ~ not ! not_eq != or || or_eq |= xor ^ xor_eq ^= Digraph Token :> ] %: # %> } <% { <: [ The default is /NOALTERNATIVE_TOKENS when compiling with the /STANDARD=ARM, /STANDARD=MS, or /STANDARD=RELAXED option. The default is /ALTERNATIVE_TOKENS when compiling with the /STANDARD=STRICT_ANSI or /STANDARD=GNU option. Specifying /ALTERNATIVE_TOKENS also defines the __ALTERNATIVE_TOKENS macro. /ANSI_ALIAS /ANSI_ALIAS /ANSI_ALIAS (D) /NOANSI_ALIAS Directs the compiler to assume the ANSI/ISO C aliasing rules, which gives it the freedom to generate better optimized code. /NOANSI_ALIAS specifies that any pointer can point to any object, regardless of type. /ANSI_ALIAS specifies that pointers to a type T can point to objects of the same type, ignoring type qualifiers such as const, unaligned, or volatile, or whether the object is signed or unsigned. Pointers to a type T can also point to structures, unions, or array members whose type follows the rules above. The aliasing rules are further explained in Section 3.3, paragraphs 20 and 25, of the ANSI C89 Standard (Section 6.3 of the ISO version, same paragraphs). /ARCHITECTURE /ARCHITECTURE=option /ARCHITECTURE=GENERIC (D) Determines the Alpha or Intel processor instruction set to be used by the compiler. The /ARCHITECTURE qualifier uses the same keyword options (keywords) as the /OPTIMIZE=TUNE qualifier. Where the /OPTIMIZE=TUNE qualifier is primarily used by certain higher-level optimizations for instruction scheduling purposes, the /ARCHITECTURE qualifier determines the type of code instructions generated for the program unit being compiled. OpenVMS Version 7.1 and subsequent releases provide an operating system kernel that includes an instruction emulator. This emulator allows new instructions, not implemented on the host processor chip, to execute and produce correct results. Applications using emulated instructions will run correctly, but may incur significant software emulation overhead at runtime. All Alpha processors implement a core set of instructions. Certain Alpha processor versions include additional instruction extensions. Select one of the /ARCHITECTURE qualifier options shown in the following table. Option Usage GENERIC Generates code that is appropriate for all processor generations. This is the default. HOST Generates code for the processor generation in use on the system being used for compilation. Running programs compiled with this option on other implementations of the Alpha architecture may encounter instruction- emulation overhead. ITANIUM2 (I64 only) Generates code for the Intel Itanium 2 processor family. For use on I64 systems only. EV4 (Alpha only) Generates code for the 21064, 21064A, 21066, and 21068 implementations of the Alpha architecture. Programs compiled with the EV4 option run without instruction-emulation overhead on all Alpha processors. EV5 (Alpha only) Generates code for some 21164 chip implementations of the Alpha architecture that use only the base set of Alpha instructions (no extensions). Programs compiled with the EV5 option will without instruction-emulation overhead on all Alpha processors. EV56 (Alpha only) Generates code for some 21164 chip implementations that use the byte and word- manipulation instruction extensions of the Alpha architecture. Running programs compiled with the EV56 option might incur emulation overhead on EV4 and EV5 processors, but will still run correctly on OpenVMS Version 7.1 (or higher) systems. PCA56 (Alpha only) Generates code for the 21164PC chip implementation that uses the byte- and word-manipulation instruction extensions and multimedia instruction extensions of the Alpha architecture. Programs compiled with the PCA56 option might incur emulation overhead on EV4, EV5, and EV56 processors, but still run correctly on OpenVMS Version 7.1 (or higher) systems. EV6 (Alpha only) Generates code for the 21264 implementation of the Alpha architecture. EV68 (Alpha only) Generates code for the 21264/EV68 implementation of the Alpha architecture. EV7 (Alpha only) Generates code for the EV7 implementation of the Alpha architecture. See also /OPTIMIZE=TUNE, which is a more typical option. Note that if /ARCHITECTURE is explicitly specified and /OPTIMIZE=TUNE is not, the tuning processor defaults to the architecture processor; for example, /ARCHITECTURE=EV6 implies /OPTIMIZE=TUNE=EV6. /ASSUME /ASSUME /ASSUME=(option[,...]) Controls compiler assumptions. You may select the following options: Option Usage [NO]WRITABLE_STRING_ Stores string constants in a writable LITERALS psect. Otherwise, such constants are placed in a nonwriteable psect. The default is NOWRITABLE_STRING_LITERALS. [NO]ACCURACY_ Specifies whether certain code SENSITIVE transformations that affect floating-point operations are allowed. These changes may or may not affect the accuracy of the program's results. If you specify NOACCURACY_SENSITIVE, the compiler is free to reorder floating- point operations based on algebraic identities (inverses, associativity, and distribution). This allows the compiler to move divide operations outside of loops, which improves performance. The default, ACCURACY_SENSITIVE, directs the compiler to use only certain scalar rules for calculations. This setting can prevent some optimization. [NO]ALIGNED_OBJECTS Controls an optimization for dereferencing pointers. Dereferencing a pointer to a longword- or quadword-aligned object is more efficient than dereferencing a pointer to a byte- or word-aligned object. Therefore, the compiler can generate more optimized code if it makes the assumption that a pointer object of an aligned pointer type does point to an aligned object. Because the compiler determines the alignment of the dereferenced object from the type of the pointer, and the program is allowed to compute a pointer that references an unaligned object (even though the pointer type indicates that it references an aligned object), the compiler must assume that the dereferenced object's alignment matches or exceeds the alignment indicated by the pointer type. The default, /ASSUME=ALIGNED_OBJECTS, allows the compiler to make such an assumption. With this assumption made, the compiler can generate more efficient code for pointer dereferences of aligned pointer types. To prevent the compiler from assuming the pointer type's alignment for objects to which it points, use the /ASSUME=NOALIGNED_OBJECTS qualifier. This option causes the compiler to generate longer code sequences to perform indirect load and store operations to avoid hardware alignment faults for arbitrarily aligned addresses. Although /ASSUME=NOALIGNED_OBJECTS might generate less efficient code than the default /ASSUME=ALIGNED_OBJECTS option, by avoiding hardware alignment faults, it speeds the execution of programs that reference unaligned data. [NO]GLOBAL_ARRAY_NEW Controls whether calls to global array new and delete are generated as specified by ANSI. Pre-ANSI global array new generated calls to operator new(). According to ANSI, use of global array new generates calls to operator new()[]. The GLOBAL_ ARRAY_NEW option also defines the macro __GLOBAL_ARRAY_NEW. GLOBAL_ARRAY_NEW generates calls to operator new()[] for global array new expressions such as new int[4]; this is the default when compiling /STANDARD=RELAXED, /STANDARD=STRICT_ANSI, /STANDARD=GNU, and /STANDARD=MS. NOGLOBAL_ARRAY_NEW generates calls to operator new() for global array new expressions such as new int[4]; and preserves compatibility with Version 5.n; this is the default when compiling /STANDARD=ARM. [NO]HEADER_TYPE_ Controls whether the compiler appends a DEFAULT file extension to a file name. The default is /ASSUME=NOHEADER_TYPE_DEFAULT. To prevent the compiler from appending a file extension to files (such as STL header files that must not have file extensions) use the /ASSUME=NOHEADER_TYPE_DEFAULT qualifier. [NO]MATH_ERRNO Controls whether intrinsic code is generated for math functions that set the errno variable. The default is /ASSUME=MATH_ERRNO, which does not allow intrinsic code for such math functions to be generated, even if /OPTIMIZE=INTRINSICS is in effect. Their prototypes and call formats, however, are still checked. [NO]POINTERS_TO_ Controls whether the compiler can safely GLOBALS assume that global variables have not had their addresses taken in code that is not visible to the current compilation. The default is /ASSUME=POINTERS_TO_ GLOBALS, which directs the compiler to assume that global variables have had their addresses taken in separately compiled modules and that, in general, any pointer dereference could be accessing the same memory as any global variable. This is often a significant barrier to optimization. While the /ANSI_ALIAS option allows some resolution based on data type, /ASSUME=POINTERS_TO_GLOBALS provides significant additional resolution and improved optimization in many cases. The /ASSUME=NOPOINTERS_TO_GLOBALS option tells the compiler that any global variable accessed through a pointer in the compilation must have had its address taken within that compilation. The compiler can see any code that takes the address of an extern variable. If it does not see the address of the variable being taken, the compiler can assume that no pointer points to the variable. Note that /ASSUME=NOPOINTERS_TO_GLOBALS does not tell the compiler that the compilation never uses pointers to access global variables. Also note that on I64 systems, the NOPOINTERS_TO_GLOBALS option is ignored and should not cause any behavior changes. [NO]STDNEW Controls whether calls are generated to the ANSI or pre-ANSI implementation of the operator new(). On memory allocation failure, the ANSI implementation throws std::bad_alloc, while the pre-ANSI implementation returns 0. /ASSUME=STDNEW generates calls to the ANSI new() implementation; this is the default when compiling with /STANDARD=RELAXED, /STANDARD=STRICT_ANSI, and /STANDARD=GNU. /ASSUME=NOSTDNEW generates calls to the pre-ANSI new() implementation; this is the default when compiling with /STANDARD=ARM and /STANDARD=MS. [NO]TRUSTED_SHORT_ Allows the compiler additional assumptions ALIGNMENT about the alignment of short types that, although thought to be naturally aligned, might cross a quadword boundary. The TRUSTED_SHORT_ALIGNMENT option indicates that the compiler should assume any datatype accessed through a pointer is naturally aligned. This generates the fastest code, but can silently generate the wrong results when an unaligned short object crosses a quadword boundary. Note that on I64 systems, the TRUSTED_ SHORT_ALIGNMENT option is ignored and should not cause any behavior changes. The NOTRUSTED_SHORT_ALIGNMENT tells the compiler that short objects might not be naturally aligned. The compiler generates slightly larger (and slower) code that gives the correct result, regardless of the actual alignment of the data. This is the default. Note that the NOTRUSTED_SHORT_ALIGNMENT option does not override the __unaligned type qualifier or the /ASSUME=NOALIGNED_ OBJECTS option. [NO]WHOLE_PROGRAM Tells the compiler that except for well- behaved library routines, the whole program consists only of the single object module being produced by this compilation. The optimizations enabled by /ASSUME=WHOLE_PROGRAM include all those enabled by /ASSUME=NOPOINTERS_TO_GLOBALS and possibly other optimizations. Note that on I64 systems, the WHOLE_ PROGRAM option is ignored and should not cause any behavior changes. The default is /ASSUME=NOWHOLE_PROGRAM. /CHECK /CHECK /CHECK[=([NO]UNINITIALIZED_VARIABLES)] (Alpha only) /NOCHECK (D) Use this qualifier as a debugging aid. Use /CHECK=UNINITIALIZED_VARIABLES to initialize all automatic variables to the value 0x7ff580057ff58005. This value is a floating NaN and, if used, causes a floating-point trap. If used as a pointer, this value is likely to cause an ACCVIO. Note that on I64 systems, /CHECK=UNINITIALIZED_VARIABLES emits a warning and is ignored. /COMMENTS /COMMENTS /COMMENTS[=option] /COMMENTS=SPACE (D) /NOCOMMENTS Specifies whether comments appear in preprocessor output files. If comments do not appear, this qualifier specifies what replaces them. The options are: Option Usage AS_IS Specifies that the comment appear in the output file. This is the default if you use the /COMMENTS qualifier without specifying an option. SPACE Specifies that a single space replaces the comment in the output file. This is the default if you do not specify the /COMMENTS qualifier at all. Specifying /NOCOMMENTS tells the preprocessor that nothing replaces the comment in the output file. This may result in inadvertent token pasting. The preprocessor may replace a comment at the end of a line or replace a line by itself with nothing, even if you specify /COMMENTS=SPACE. Specifying /COMMENTS=SPACE cannot change the meaning of the program. /DEBUG /DEBUG /DEBUG[=(option[,...])] /DEBUG=(TRACEBACK,NOSYMBOLS) (D) /NODEBUG Requests that information be included in the object module for use with the OpenVMS Debugger. You can select the following options: Option Usage ALL Includes all possible debugging information. /DEBUG=ALL is equivalent to /DEBUG=(TRACEBACK,SYMBOLS), which on I64 systems is equivalent to /DEBUG=(TRACEBACK,SYMBOLS=NOBRIEF). NONE Excludes all debugging information. This option is equivalent to specifying /NODEBUG, which is equivalent to /DEBUG=(NOTRACEBACK,NOSYMBOLS). NOSYMBOLS Turns off symbol generation SYMBOLS Generates symbol-table records. On I64 systems, /DEBUG=SYMBOLS is equivalent to /DEBUG=SYMBOLS=BRIEF. On Alpha systems, /DEBUG=SYMBOLS is effectively equivalent to /DEBUG=NOBRIEF. SYMBOLS=BRIEF Generates debug information with unreferenced (I64 only) labels and types pruned out to produce smaller object sizes. On Alpha systems, BRIEF is ignored. SYMBOLS=NOBRIEF Generates complete debug information. On Alpha (I64 only) systems, the NOBRIEF keyword is ignored, but you still get complete debug information. NOTRACEBACK Excludes traceback records. This option is equivalent to specifying /NODEBUG and is used to avoid generating extraneous information from thoroughly debugged program modules. TRACEBACK Includes only traceback records. This option is the default if you do not specify the /DEBUG qualifier on the command line. On Alpha systems, /DEBUG is equivalent to /DEBUG=(TRACEBACK,SYMBOLS). On I64 systems, /DEBUG is equivalent to /DEBUG=(TRACEBACK,SYMBOLS), which is equivalent to /DEBUG=(TRACEBACK,SYMBOLS=BRIEF). /DEFINE /DEFINE /DEFINE=(identifier[=definition][,...]) /NODEFINE (D) Performs the same function as the #define preprocessor directive. That is, /DEFINE defines a token string or macro to be substituted for every occurrence of a given identifier in the program. DCL converts all input to uppercase unless it is enclosed in quotation marks. The simplest form of a /DEFINE definition is as follows: /DEFINE=true This results in a definition like the one that would result from the following definition: #define TRUE 1 When more than one /DEFINE is present on the CXX command line or in a single compilation unit, only the last /DEFINE is used. When both /DEFINE and /UNDEFINE are present on a command line, /DEFINE is evaluated before /UNDEFINE. /DEFINE /DEFINE=__FORCE_INSTANTIATIONS (Alpha only) /NODEFINE=__FORCE_INSTANTIATIONS (D) Forces the standard library template preinstantiations to be created in the user's repository. Normally these instantiations are suppressed because the library already contains them. On I64 systems, defining __FORCE_INSTANTIATIONS has no effect. /DEFINE /DEFINE=__[NO_]USE_STD_IOSTREAM /DEFINE=__NO_USE_STD_IOSTREAM (D) Use or do not use the standard iostreams. Specifying /DEFINE=__USE_STD_IOSTREAM forces the inclusion of the ANSI standard version of the iostream header file. This is the default in STRICT_ANSI mode. Otherwise, the pre-standard AT&T-compatible version of iostreams is used. /DIAGNOSTICS /DIAGNOSTICS /DIAGNOSTICS[=file-spec] /NODIAGNOSTICS (D) Creates a file containing compiler diagnostic messages. The default file extension for a diagnostics file is .DIA. The diagnostics file is used with the DEC Language-Sensitive Editor (LSE). To display a diagnostics file, enter the command REVIEW/FILE=file-spec while in LSE. /DISTINGUISH_NESTED_ENUMS /DISTINGUISH_NESTED_ENUMS /NODISTINGUISH_NESTED_ENUMS (D) Causes the compiler, when forming a mangled name, to include the name of any enclosing classes within which an enum is nested, thereby preventing different functions from receiving the same mangled name. This qualifier has no meaning on I64 systems because it modifies the behavior of programs compiled with /MODEL=ARM, and that model is not supported on I64 systems. /ENDIAN /ENDIAN /ENDIAN={BIG | LITTLE} /ENDIAN=LITTLE (D) Controls whether big or little endian ordering of bytes is carried out in character constants. /ERROR_LIMIT /ERROR_LIMIT /ERROR_LIMIT[=number] /ERROR_LIMIT=30 (D) /NOERROR_LIMIT Limits the number of error-level diagnostic messages that are acceptable during program compilation. Compilation terminates when the limit (number) is exceeded. /NOERROR_LIMIT specifies that there is no limit on error messages. The default is /ERROR_LIMIT=30, which specifies that compilation terminates after issuing 30 error messages. /EXCEPTIONS /EXCEPTIONS /EXCEPTIONS=CLEANUP (D) /EXCEPTIONS=NOCLEANUP (Alpha only) /EXCEPTIONS=EXPLICIT (D) /EXCEPTIONS=IMPLICIT (Alpha only) /NOEXCEPTIONS Controls whether support for C++ exceptions is enabled or disabled. C++ exceptions are enabled by default (equivalent to /EXCEPTIONS=CLEANUP). When C++ exceptions are enabled, the compiler generates code for throw expressions, try blocks, and catch statements. The compiler also generates special code for main programs so that the terminate() routine is called for unhandled exceptions. You can select from the following options: CLEANUP Generate cleanup code for automatic objects. When an exception is handled at run-time and control passes from a throw-point to a handler, call the destructors for all automatic objects that were constructed because the try-block containing the handler was entered. NOCLEANUP Do not generate cleanup code. Using this option can (Alpha reduce the size of your executable when you want to only) throw and handle exceptions and cleanup of automatic objects during exception processing is not important for your application. The NOCLEANUP option is ignored on I64 systems. EXPLICIT Tells the compiler to assume the standard C++ rules about exceptions. Catch clauses can catch only those exceptions resulting from the evaluation of a throw expression within the body of the catch clause's try block or from within a procedure called from within the catch clause's try block. IMPLICIT On Alpha systems, tells the compiler that an exception (Alpha might be thrown at any time the program is executing only) code within the body of the try block. These exceptions might be the result of a throw expression, hardware errors, or software errors (such as dereferencing an invalid pointer). Specifying /EXCEPTIONS=IMPLICIT seriously interferes with the compiler's ability to optimize code. When the compiler optimizes a function, it must ensure that the values of all variables after an exception is caught remain the same as they were at the point where the exception was throw. The optimizer is therefore limited in its ability to rearrange stores and expressions that might cause an exception to be thrown. With /EXCEPTIONS=EXPLICIT, this is not a serious restriction, because the compiler cannot rearrange stores and expressions around the code that explicitly raises an exception. In implicit exception mode, however, almost any code has the potential to cause an exception to be thrown, thereby dramatically reducing the optimizer's ability to rearrange code. Also, if the compiler can determine that no throw expressions occur within a try block, it can eliminate the exception handling overhead the try block introduces, including all code within the catch clauses associated with the try block. Because no exceptions can occur during the execution of the code within the try block, no code within the catch clauses can ever be executed. The compiler cannot do this with /EXCEPTIONS=IMPLICIT. Use /EXCEPTIONS=IMPLICIT if your program converts signals to C++ exceptions by calling cxxl$set_ condition(cxx_exception). Failure to do so may result in your code not catching the exceptions produced by signals. The /NOEXCEPTIONS qualifier disables C++ exceptions as follows: 1. The compiler issues errors for throw expressions, try blocks, and catch statements, but might generate code for these constructs. 2. On Alpha systems, the compiler does not generate cleanup code for automatic objects. 3. The compiler does not generate special code for main programs so that the terminate() function is called for unhandled exceptions. The /EXCEPTIONS qualifer defines the macro __EXCEPTIONS. /EXTERN_MODEL /EXTERN_MODEL /EXTERN_MODEL=option /EXTERN_MODEL=RELAXED_REFDEF (D) In conjunction with the /SHARE_GLOBALS qualifier, controls the initial extern model of the compiler. Conceptually, the compiler behaves as if the first line of the program being compiled was a #pragma extern_model directive with the model and psect name, if any, specified by the /EXTERN_MODEL qualifier and with the SHR or NOSHR keyword specified by the /SHARE_GLOBALS qualifier. For example, assume the command line contains the following qualifier: /EXTERN_MODEL=STRICT_REFDEF="MYDATA"/NOSHARE The compiler acts as if the program began with the following line: #pragma extern_model strict_refdef "MYDATA" noshr For more information on the various models, see "C++ Implementation" in the HP C++ User's Guide for OpenVMS Systems. The /EXTERN_MODEL qualifier takes the following options, which have the same meaning as for the #pragma extern_model directive: COMMON_BLOCK RELAXED_REFDEF STRICT_REFDEF=["NAME"] GLOBALVALUE The default is RELAXED_REFDEF. /FIRST_INCLUDE /FIRST_INCLUDE /FIRST_INCLUDE=(file[, . . . ]) /NOFIRST_INCLUDE (D) Includes the specified files before any source files. This qualifier corresponds to the Tru64 UNIX -FI switch. When /FIRST_INCLUDE=file is specified, file is included in the source as if the line before the first line of the source were: #include "file" If more than one file is specified, the files are included in their order of appearance on the command line. This qualifier is useful if you have command lines to pass to the C compiler that are exceeding the DCL command-line length limit. Using the /FIRST_INCLUDE qualifier can help solve this problem by replacing lengthy /DEFINE and /WARNINGS qualifiers with #define and #pragma message preprocessor directives placed in a /FIRST_ INCLUDE file. The default is /NOFIRST_INCLUDE. /FLOAT /FLOAT /FLOAT=option /FLOAT=G_FLOAT (Alpha only) (D) /FLOAT=IEEE_FLOAT (I64 only) (D) Controls the format of floating-point variables. The options are: Option Usage D_FLOAT double variables are represented in VAX D_ floating format. float variables are represented in VAX F_floating format. The __D_FLOAT macro is predefined. G_FLOAT double variables are represented in VAX G_ floating format. float variables are represented in VAX F_floating format. The __G_FLOAT macro is predefined. IEEE_FLOAT float and double variables are represented in IEEE floating-point format (S_float and T_ float, respectively). The __IEEE_FLOAT macro is predefined. Use the /IEEE_MODE qualifier for controlling the handling of IEEE exceptional values. On Alpha systems, the default is /FLOAT=G_FLOAT. On I64 systems, the default is /FLOAT=IEEE_FLOAT. See the HP C++ User's Guide for OpenVMS Systems for additional information on floating-point representation on I64 and Alpha systems. /GRANULARITY /GRANULARITY /GRANULARITY=option /GRANULARITY=QUADWORD (D) Controls the size of shared data in memory that can be safely accessed from different threads. The possible size values are BYTE, LONGWORD, and QUADWORD. Specifying BYTE allows single bytes to be accessed from different threads sharing data in memory without corrupting surrounding bytes. This option will slow runtime performance. Specifying LONGWORD allows naturally aligned 4-byte longwords to be accessed safely from different threads sharing data in memory. Accessing data items of 3 bytes or less, or unaligned data, may result in data items written from multiple threads being inconsistently updated. Specifying QUADWORD allows naturally aligned 8-byte quadwords to be accessed safely from different threads sharing data in memory. Accessing data items of 7 bytes or less, or unaligned data, might result in data items written from multiple threads being inconsistently updated. This is the default. /IEEE_MODE /IEEE_MODE /IEEE_MODE=option /IEEE_MODE=FAST (D) (Alpha only) /IEEE_MODE=DENORM_RESULTS (D) (I64 only) Selects the IEEE floating-point mode to be used if the /FLOAT=IEEE_FLOAT qualifier is specified. The options are: Option Usage FAST During program execution, only finite values (no infinities, NaNs, or denorms) are created. Underflows and denormal values are flushed to zero. Exceptional conditions, such as floating- point overflow, divide-by-zero, or use of an IEEE exceptional operand are fatal. UNDERFLOW_ Generate infinities and NaNs. Flush denormalized TO_ZERO results and underflow to zero without exceptions. DENORM_ Same as the UNDERFLOW_TO_ZERO option, except that RESULTS denorms are generated. INEXACT Same as the DENORM_RESULTS option, except that inexact values are trapped. This is the slowest mode, and is not appropriate for any sort of general-purpose computations. On Alpha systems, the default is /IEEE_MODE=FAST. On I64 systems, the default is /IEEE_MODE=DENORM_RESULTS. The INFINITY and NAN macros defined in are available to programs compiled with /FLOAT=IEEE and /IEEE_MODE={anything other than FAST}. On Alpha sytems, the /IEEE_MODE qualifier generally has its greatest effect on the generated code of a compilation. When calls are made between functions compiled with different /IEEE_ MODE qualifiers, each function produces the /IEEE_MODE behavior with which it was compiled. On I64 systems, the /IEEE_MODE qualifier primarily affects only the setting of a hardware register at program startup. In general, the /IEEE_MODE behavior for a given function is controlled by the /IEEE_MODE option specified on the compilation that produced the main program: the startup code for the main program sets the hardware register according the command-line qualifiers used to compile the main program. When applied to a compilation that does not contain a main program, the /IEEE_MODE qualifier does have some effect: it might affect the evaluation of floating-point constant expressions, and it is used to set the EXCEPTION_MODE used by the math library for calls from that compilation. But the qualifier has no effect on the exceptional behavior of floating-point calculations generated as inline code for that compilation. Therefore, if floating-point exceptional behavior is important to an application, all of its compilations, including the one containing the main program, should be compiled with the same /IEEE_MODE setting. Even on Alpha systems, the particular setting of /IEEE_ MODE=UNDERFLOW_TO_ZERO has this characteristic: its primary effect requires the setting of a runtime status register, and so it needs to be specified on the compilation containing the main program in order to be effective in other compilations. Also see the /FLOAT qualifier. /IMPLICIT_INCLUDE /IMPLICIT_INCLUDE /IMPLICIT_INCLUDE (D) /NOIMPLICIT_INCLUDE /IMPLICIT_INCLUDE enables inclusion of source files as a method of finding definitions of template entities. By default it is enabled for normal compilation, and disabled for preprocessing only. The search rules for finding template definition files is the same as for include files. /NOIMPLICIT_INCLUDE disables inclusion of source files as a method of finding definitions of template entities. You might want to use this option in conjunction with the /STANDARD=MS command line option, to match more closely the behavior on Microsoft C++. /INCLUDE_DIRECTORY /INCLUDE_DIRECTORY /INCLUDE_DIRECTORY=(place[,...]) /NOINCLUDE_DIRECTORY (D) Provides an additional level of search for user-defined include files. Each pathname argument can be either a logical name or a legal UNIX style directory in a quoted string. The default is /NOINCLUDE_DIRECTORY. The /INCLUDE_DIRECTORY qualifier provides functionality similar to the -I option of the cxx command on Tru64 UNIX systems. This qualifier allows you to specify additional locations to search for files to include. Putting an empty string in the specification prevents the compiler from searching any of the locations it normally searches but directs it to search only in locations you identify explicitly on the command line with the /INCLUDE_DIRECTORY And /LIBRARY qualifiers (or by way of the specification of the primary source file, depending on the /NESTED_INCLUDE_DIRECTORY qualifier). The basic order for searching depends on the form of the header name (after macro expansion), with additional aspects controlled by other command line qualifiers as well as the presence or absence of logical name definitions. The valid possibilities for names are as follows: o Enclosed in quotes. For example: "stdio.h" o Enclosed in angle brackets. For example: Unless otherwise defined, searching a location means that the compiler uses the string specifying the location as the default file specification in a call to an RMS system service (that is, a $SEARCH/$PARSE) with a primary file specification consisting of the name in the #include (without enclosing delimiters). The search terminates successfully as soon as a file can be opened for reading. Specifying a null string in the /INCLUDE qualifier causes the compiler to do a non-standard search. This search path is as follows: 1. The current directory (quoted form only) 2. Any directories specified in the /INCLUDE qualifier 3. The directory of the primary input file 4. Text libraries specified on the command line using /LIBRARY For standard searches, the search order is as follows: 1. Search the current directory (directory of the source being processed). If angle-bracket form, search only if no directories are specified with /INCLUDE_DIRECTORY. 2. Search the locations specified in the /INCLUDE_DIRECTORY qualifier (if any). 3. If CXX$SYSTEM_INCLUDE is defined as a logical name, search CXX$SYSTEM_INCLUDE:.HXX or just CXX$SYSTEM_INCLUDE:., depending on the qualifier /ASSUME=NOHEADER_TYPE_DEFAULT. If nothing is found, go to step 6. 4. If CXX$LIBRARY_INCLUDE is defined as a logical name, CXX$LIBRARY_INCLUDE:.HXX or CXX$LIBRARY_INCLUDE:., depending on the qualifier /ASSUME=NOHEADER_TYPE_DEFAULT. If nothing is found, go to step 6. 5. If /ASSUME=HEADER_TYPE_DEFAULT is not specified, search the default list of locations for plain-text copies of compiler header files as follows: SYS$COMMON:[CXX$LIB.INCLUDE.CXXL$ANSI_DEF] SYS$COMMON:[CXX$LIB.INCLUDE.DECC$RTLDEF_HXX].HXX SYS$COMMON:[DECC$LIB.INCLUDE.DECC$RTLDEF].H SYS$COMMON:[DECC$LIB.INCLUDE.SYS$STARLET_C].H If /ASSUME=HEADER_TYPE_DEFAULT is specified, search the default list of locations for plain-text copies of compiler header files as follows: SYS$COMMON:[CXX$LIB.INCLUDE.DECC$RTLDEF_HXX].HXX SYS$COMMON:[DECC$LIB.INCLUDE.DECC$RTLDEF].H SYS$COMMON:[DECC$LIB.INCLUDE.SYS$STARLET_C].H SYS$COMMON:[CXX$LIB.INCLUDE.CXXL$ANSI_DEF] 6. Search the directory of the primary input file. 7. If quoted form, and CXX$USER_INCLUDE is defined as a logical name, search CXX$USER_INCLUDE:.HXX or CXX$USER_INCLUDE:., depending on the /ASSUME=NOHEADER_TYPE_DEFAULT qualifier. 8. Search the text libraries. Extract the simple file name and file type from the #include specification, and use them to determine a module name for each text library. There are three forms of module names used by the compiler: 1. type stripped: The file type will be removed from the include file specification to form a library module name. Examples: #include Module name "FOO" "foo.h" #include Module name "FOO" "foo" #include Module name "FOO" "foo" 2. type required: The file type must be a part of the file name. Examples: #include Module name "FOO.H" "foo.h" #include Module name "FOO." "foo" #include Module name "FOO." "foo" 3. type optional: First an attempt is made to find a module with the type included in the module name. If this is unsuccessful, an attempt is made with the type stripped from the module name. If this is unsuccessful, the search moves on to the next library. If /ASSUME=HEADER_TYPE_DEFAULT is specified, the following text libraries are searched in this order: Libraries specified on the command line with the /LIBRARY qualifier (all files, type stripped) CXX$TEXT_LIBRARY (all files, type stripped) DECC$RTLDEF (H files and unspecified files, type stripped) SYS$STARLET_C (all files, type stripped) CXXL$ANSI_DEF (unspecified files, type stripped) Otherwise, these text libraries are searched in this order: Libraries specified on the command line with the /LIBRARY qualifier (all files, type optional) CXX$TEXT_LIBRARY (all files, type optional) CXXL$ANSI_DEF (all files, type required) DECC$RTLDEF (H files and unspecified files, type stripped) SYS$STARLET_C (all files, type stripped) Two text library search examples (stop when something is found): Example 1 #include "foo" 1. For each library specified via the /LIBRARY qualifier: - Look for "FOO." - Look for "FOO" 2. Look for "FOO." in CXX$TEXT_LIBRARY 3. Look for "FOO" in CXX$TEXT_LIBRARY 4. Look for "FOO." in CXXL$ANSI_DEF (Do not look for "FOO" because the type is required as part of the module name) 5. Look for "FOO" in DECC$RTL_DEF (not "FOO." because the type must not be part of the module name) 6. Look for "FOO" in SYS$STARLET_C (not "FOO." because the type must not be part of the module name) Example 2 #include "foo.h" 1. For each library specified via the /LIBRARY qualifier: - Look for "FOO.H" - Look for "FOO" 2. Look for "FOO.H" in CXX$TEXT_LIBRARY 3. Look for "FOO" in CXX$TEXT_LIBRARY 4. Look for "FOO.H" in CXXL$ANSI_DEF (Do not look for "FOO" because the type is required as part of the module name) 5. Look for "FOO" in DECC$RTL_DEF (not "FOO.H" because the type must not be part of the module name) 6. Look for "FOO" in SYS$STARLET_C (not "FOO.H" because the type must not be part of the module name) 7. If neither CXX$LIBRARY_INCLUDE nor CXX$SYSTEM_INCLUDE is defined as a logical name, then search SYS$LIBRARY:.HXX. /L_DOUBLE_SIZE /L_DOUBLE_SIZE /L_DOUBLE_SIZE=option /L_DOUBLE_SIZE=128 (D) Determines how the compiler interprets the long double type. The qualifier options are 64 and 128. Specifying /L_DOUBLE_SIZE=64 treats all long double references as G_FLOAT, D_FLOAT, or T_FLOAT, depending on the value of the /FLOAT qualifier. Specifying /L_DOUBLE_SIZE=64 also defines the macro __X_FLOAT=0. Note: The /L_DOUBLE_SIZE=64 option is not available on I64 systems. If it is specified, the compiler issues a warning message and uses /L_DOUBLE_SIZE=128. Specifying /L_DOUBLE_SIZE=128 treats all long double references as X_FLOAT. The /L_DOUBLE_SIZE=128 option also defines the macro __X_FLOAT=1. This is the default. /LIBRARY Indicates that the associated input file is a text library containing source text modules specified in #include directives. The compiler searches the specified library for all #include module names that are not enclosed in angle brackets or quotation marks. The name of the library must be concatenated with the file specification using a plus sign. For example: CXX DATAB/LIBRARY+APPLICATION /LINE_DIRECTIVES /LINE_DIRECTIVES /LINE_DIRECTIVES (D) /NOLINE_DIRECTIVES Controls whether #line directives appear in preprocessed output files. /LIST /LIST /LIST[=file-spec] (Batch default) /NOLIST (Interactive default) Controls whether a listing file is produced. The default output file extension is .LIS. /MACHINE_CODE /MACHINE_CODE /NOMACHINE_CODE (D) Controls whether the listing produced by the compiler includes the machine-language code generated during the compilation. If you use this qualifier you also need to use the /LIST qualifier. On Alpha systems, machine-language code is not added to the listing file when object-file generation is disabled (using the /NOOBJECT qualifier). /MAIN /MAIN=POSIX_EXIT /MAIN=POSIX_EXIT /NOMAIN (D) Directs the compiler to call __posix_exit instead of exit when returning from main. /MEMBER_ALIGNMENT /MEMBER_ALIGNMENT /MEMBER_ALIGNMENT (D) /NOMEMBER_ALIGNMENT Directs the compiler to naturally align data structure members. This means that data structure members are aligned on the next boundary appropriate to the type of the member, rather than on the next byte. For instance, a long variable member is aligned on the next longword boundary; a short variable member is aligned on the next word boundary. Any use of the #pragma member_alignment or #pragma nomember_ alignment directives within the source code overrides the setting established by this qualifier. Specifying /NOMEMBER_ALIGNMENT causes data structure members to be byte-aligned (with the exception of bit-field members). /MMS_DEPENDENCIES /MMS_DEPENDENCIES /MMS_DEPENDENCIES[=(option[,option)]] /NOMMS_DEPENDENCIES (D) Instructs the compiler to produce a dependency file. The format of the dependency file is as follows: object_file_name: object_file_name: object_file_name: You can specify none, one, or both of the following qualifier options: FILE[=filespec] Specifies where to save the dependency file. The default file extension for a dependency file is .mms. Other than using a different default extension, this qualifier uses the same procedure that /OBJECT and /LIST use for determining the name of the output file. SYSTEM_INCLUDE_ Specifies whether to include dependency FILES information about system include files (that is, those included with #include ). The default is to include dependency information about system include files. /MODEL /MODEL (Alpha only) /MODEL={ANSI | ARM} /MODEL=ARM (D) On Alpha systems, determines the layout of C++ classes, name mangling, and exception handling. On I64 systems, the default (and only) object model & demangling scheme used is the I64 Application Binary Interface (ABI). The compiler accepts the /MODEL qualifier, but it has no effect. On Alpha systems, /MODEL=ARM is the default and generates objects that are link compatible with all releases prior to HP C++ version 6.3, and with all objects compiled with the /MODEL=ARM qualifier in releases of HP C++ Version 6.3 or later. Specifying this option defines the macro __MODEL_ARM. The /MODEL=ANSI qualifier supports the complete ISO/ANSI C++ specification, including distinct name mangling for templates. The ANSI model also reduces the size of C++ non-POD class objects. Note that this option generates objects that are not compatible with all prior and future releases of HP C++, or with objects compiled using the /MODEL=ARM qualifier. If you specify the /MODEL=ANSI qualifier, you must recompile and relink (using CXXLINK/MODEL=ANSI) your entire application, including libraries. Specifying this option defines the macro __MODEL_ANSI. /NAMES /NAMES /NAMES=(option1,option2) /NAMES=(UPPERCASE,TRUNCATED) (D) Option1 converts all definitions and references of external symbols and psects to the case specified. Option1 values are: Option Usage UPPERCASE Converts to uppercase. AS_IS Leaves the case as specified in the source. Option2 controls whether or not external names greater than 31 characters get truncated or shortened. Option2 values are: Option Usage /NAMES=TRUNCATED Truncates long external names to the first 31 (default) characters. /NAMES=SHORTENED Shortens long external names. A shortened name consists of the first 23 characters of the name followed by a 7- character Cyclic Redundancy Check (CRC) computed by looking at the full name, and then a "$". The default is /NAMES=(UPPERCASE,TRUNCATED). /NESTED_INCLUDE_DIRECTORY /NESTED_INCLUDE_DIRECTORY /NESTED_INCLUDE_DIRECTORY[=option] /NESTED_INCLUDE_DIRECTORY=INCLUDE_FILE (D) Controls the first step in the search algorithm the compiler uses when looking for files included using the quoted form of the #include preprocessing directive: #include "file-spec" The /NESTED_INCLUDE_DIRECTORY qualifier has the following options: Option Usage PRIMARY_ Directs the compiler to search the default file type FILE for headers using the context of the primary source file. This means that only the file type (".H" or ".") is used for the default file-spec but, in addition, the chain of "related file-specs" used to maintain the sticky defaults for processing the next top-level source file is applied when searching for the include file. INCLUDE_ Directs the compiler to search the directory FILE containing the file in which the #include directive itself occurred. The meaning of "directory containing" is: the RMS "resultant string" obtained when the file in which the #include occurred was opened, except that the filename and subsequent components are replaced by the default file type for headers (".H", or just "." if /ASSUME=NOHEADER_TYPE_DEFAULT is in effect). The "resultant string" will not have translated any concealed device logical. NONE Directs the compiler to skip the first step of processing #include "file.h" directives. The compiler starts its search for the include file in the /INCLUDE_DIRECTORY directories. For more information on the search order for included files, see the /INCLUDE_DIRECTORY qualifier. /OBJECT /OBJECT /OBJECT[=file-spec] /OBJECT=.OBJ (D) /NOOBJECT Controls whether the compiler produces an output object module. The default output file extension is .OBJ. Note that the /OBJECT qualifier has no impact on the output file of the /MMS_DEPENDENCIES qualifier. /OPTIMIZE /OPTIMIZE /OPTIMIZE[=option] /OPTIMIZE=(LEVEL=4,INLINE=AUTOMATIC,INTRINSICS,UNROLL=0, NOOVERRIDE_LIMITS,TUNE=GENERIC) (D) /NOOPTIMIZE Controls the level of code optimization that the compiler performs. The options are as follows: Option Usage LEVEL=n Selects the level of code optimization. Specify an integer from 0 (no optimization) to 5 (full optimization). [NO]INLINE Provides inline expansion of functions that yield optimized code when they are expanded. You can specify one of the following keywords to control inlining: NONE No inlining is done, even if requested by the language syntax. MANUAL Inlines only those function calls for which the program explicitly requests inlining. AUTOMATIC Inlines all of the function calls in the MANUAL category, plus additional calls that the compiler determines are appropriate on this platform. On Alpha systems, the heuristics for AUTOMATIC are similar to those for SIZE; on I64 systems, they are more like those for SPEED. AUTOMATIC is the default. SIZE Inlines all of the function calls in the MANUAL category plus any additional calls that the compiler determines would improve run-time performance without significantly increasing the size of the program. SPEED Performs more aggressive inlining for run-time performance, even when it might significantly increase the size of the program. ALL Inlines every call that can be inlined while still generating correct code. Recursive routines, however, will not cause an infinite loop at compile time. On I64 systems, ALL is treated as if SIZE had been specified. Note that /OPT=INLINE=ALL is not recommended for general use, because it performs very aggressive inlining and can cause the compiler to exhaust virtual memory or take an unacceptably long time to compile. [NO]OVERRIDE_ Controls whether or not the compiler uses certain LIMITS (I64 built-in limits on the size and complexity of only) a function to "throttle back" the amount of optimization performed in order to reduce the likelihood that the compiler will use excessive memory resources or CPU time attempting to optimize the code. The default is NOOVERRIDE_LIMITS, which means that when compiling a function that has an unusually large number of basic blocks, live variables, or other properties that tend to cause the optimizer to use extra resources, the informational message OPTLIMEXC might be issued to notify you that optimization has been reduced to avoid excessive resource use. You can choose to ignore this message or disable it (the message is not issued on compilations with optimization disabled). Or you can specify /OPTIMIZE=OVERRIDE_LIMITS, which instructs the compiler to not check the limits and to attempt full optimization no matter how large or complex the function, knowing that the compilation might exhaust memory or seem to be in a loop. If using /OPTIMIZE=OVERRIDE_LIMITS does result in excessive resource use, you are sure that the compiler process has plenty of memory quota available, you are convinced that the compilation does not contain any unusually large or complex functions, and you can provide complete source code, then you might want to contact your support channel to see if there is a problem in the compiler causing it to use more resources than it should for the particular compilation at hand. TUNE Specifies the preferred processor for execution. This option makes some decisions preferentially for the specified processor (for example, for code scheduling). Note that code valid only for the specified processor can be generated. However, parallel code can be generated for processors down to the specified architecture level if necessary; that is, tuning specifies the preferred target, while architecture level specifies a lower boundary on available processor features. For example, /ARCHITECTURE=EV56/OPTIMIZE=TUNE=EV6 specifies that the code does not need to run on a processor older than an EV56, and that the code will probably run on an EV6. The generated code will run on all EV56 and later systems without any emulation. The code might have run-time selected conditional regions specifically for EV6. Also, note that because emulation is provided, the code should run, but potentially at very significantly reduced speed, on pre-EV56 processors. The options for TUNE are the same as the options for /ARCH. You can specify one of the following keywords: GENERIC Selects instruction tuning that is appropriate for all implementations of the operating system architecture. This option is the default. HOST Selects instruction tuning that is appropriate for the machine on which the code is being compiled. ITANIUM2 Selects instruction tuning for the (I64 only) Intel Itanium 2 processor. EV4 (Alpha Selects instruction tuning for the only) 21064, 21064A, 21066, and 21068 implementations of the operating system architecture. EV5 (Alpha Selects instruction tuning for only) the 21164 implementation of the operating system architecture. EV56 (Alpha Selects instruction tuning for only) 21164 chip implementations that use the byte- and word-manipulation instruction extensions of the Alpha architecture. Running programs compiled with the EV56 keyword might incur emulation overhead on EV4 and EV5 processors, but will still run correctly on OpenVMS Version 7.1 (or later) systems. PCA56 (Alpha Selects instruction tuning for the only) 21164PC chip implementation that uses the byte- and word-manipulation instruction extensions and multimedia instruction extensions of the Alpha architecture. Programs compiled with the PCA56 keyword might incur emulation overhead on EV4, EV5, and EV56 processors, but will still run correctly on OpenVMS Version 7.1 (or later) systems. EV6 (Alpha Selects instruction tuning for only) the first-generation 21264 implementation of the Alpha architecture. EV67 (Alpha Selects instruction tuning for only) the second-generation 21264 implementation of the Alpha architecture. [NO]INTRINSICSControls whether certain functions are handled as intrinsic functions without explicitly enabling each of them as an intrinsic through the #pragma intrinsic preprocessor directive. Functions that can be handled as intrinsics are: Main Group - ANSI: abs atanl atan2l ceill cosl floorf memcpy sinf atan atan ceil cos fabs floorl memmove sinl sin atanf atan2f ceilf cosf floor labs memset strcpy strlen Main Group - Non-ANSI: alloca atand2 bzero sind atand bcopy cosd Printf functions: fprintf printf sprintf Printf non-ANSI: snprintf ANSI math functions that set errno, thereby requiring /ASSUME=NOMATH_ERRNO: acos asinf coshl log log10f powl sqrt tanf acosf asinl exp logf log10l sinh sqrtf tanl acosl cosh expf logl pow sinhf sqrtl tanh tanhl asin coshf expl log10 powf sinhl tan tanhf Non-ANSI math functions that set errno, thereby requiring /ASSUME=NOMATH_ERRNO: log2 tand The /OPTIMZE=INTRINSICS qualifier works with /OPTIMIZE=LEVEL=n and some other qualifiers to determine how intrinsics are handled: o If the optimization level specified is less than 4, the intrinsic-function prototypes and call formats are checked, but normal run-time calls are still made. o If the optimization level is o or higher, intrinsic code is generated. o Intrinsic code is not generated for math functions that set the errno variable unless /ASSUME=NOMATH_ERRNO is specified. Such math functions, however, do have their prototypes and call formats checked. The default is /OPTIMIZE=INTRINSICS, which turns on this handling. To turn it off, specify /NOOPTIMIZE or /OPTIMIZE=NOINTRINSICS. UNROLL=n Controls loop unrolling done by the optimizer. Specify a positive integer to indicate the number of times to unroll loop bodies. If you specify 0 or do not supply a value, the optimizer determines its own unroll amount. The default is UNROLL=0. Specifying UNROLL=1 effectively disables loop unrolling. On I64 systems, you do not have the ability to control the number of times a loop is unrolled. You can either disable loop unrolling with UNROLL=1, or accept the UNROLL=0 default, which lets the optimizer determine the unroll amount. The default is /OPTIMIZE, which is equivalent to /OPTIMIZE=LEVEL=4. /PENDING_INSTANTIATIONS /PENDING_INSTANTIATIONS /PENDING_INSTANTIATIONS[=n] /PENDING_INSTANTIATIONS=64(D) Limit the depth of recursive instantiations so that infinite instantiation loops can be detected before some resource is exhausted. The /PENDING_INSTANTIATIONS qualifier requires a positive non-zero value as argument and issues an error when n instantiations are pending for the same class template. The default value for n is 64. /POINTER_SIZE /POINTER_SIZE (Alpha only) /POINTER_SIZE=option /NOPOINTER_SIZE (D) On Alpha systems, controls whether pointer-size features are enabled, and whether pointers are 32 bits or 64 bits long. On I64 systems, the /POINTER_SIZE=option form of the qualifier is ignored. On both Alpha and I64 systems, the default is /NOPOINTER_SIZE, which disables pointer-size features, such as the ability to use #pragma pointer_size, and directs the compiler to assume that all pointers are 32-bit pointers. This default represents no change over previous versions of HP C++. On Alpha systems, you can specify one of the following options: SHORT The compiler assumes 32-bit pointers. 32 Same as SHORT. LONG The compiler assumes 64-bit pointers. 64 Same as LONG. Specifying /POINTER_SIZE=32 directs the compiler to assume that all pointers are 32-bit pointers. But unlike the default of /NOPOINTER_SIZE, /POINTER_SIZE=32 enables use of the #pragma pointer_size long and #pragma pointer_size short preprocessor directives to control pointer size throughout your program. Specifying /POINTER_SIZE=64 directs the compiler to assume that all pointers are 64-bit pointers, and also enables use of the #pragma pointer_size directives. /PREFIX_LIBRARY_ENTRIES /PREFIX_LIBRARY_ENTRIES /PREFIX_LIBRARY_ENTRIES=(option,...) /NOPREFIX_LIBRARY_ENTRIES /PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES (D) Controls C Run-Time Library (RTL) name prefixing. For user programs that do not include the ANSI header files but call the ANSI library, the compiler automatically adds a DECC$ prefix to all C RTL library calls just before the name for the external reference or global definition is put into the object file. The C RTL shareable image (DECC$SHR.EXE) resides in IMAGELIB.OLB with a DECC$ prefix for its entry points. Every external name in IMAGELIB.OLB has a DECC$ prefix, and, therefore, has an OpenVMS- conformant name space (a requirement for inclusion in IMAGELIB). The options are as follows: Option Usage EXCEPT=(name, The.names specified are not prefixed. ) ALL_ENTRIES All HP C++ names are prefixed. Note: ALL_ENTRIES prefixes all functions defined by the C99 standard, including those that may not be supported in the current run-time library. So calling functions introduced in C99 that are not yet implemented in the OpenVMS C RTL will produce unresolved references to symbols prefixed by DECC$ when the program is linked. In addition, the compiler will issue a CC-W-NOTINCRTL message when it prefixes a name that is not in the current C RTL. ANSI_C89_ Only ANSI/ISO C library names are prefixed. ENTRIES RTL=name References to the C RTL, indicated by NAME, are generated. NAME must be 1017 characters or fewer. If you want no names prefixed, specify /NOPREFIX_LIBRARY_ENTRIES. /PREPROCESS_ONLY /PREPROCESS_ONLY /PREPROCESS_ONLY[=filename] /NOPREPROCESS_ONLY (D) Causes the compiler to perform only the actions of the preprocessor phase and write the resulting processed text out to a file. The default output file extension is .IXX. /PSECT_MODEL /PSECT_MODEL /PSECT_MODEL=MULTILANGUAGE /PSECT_MODEL=NOMULTILANGUAGE (D) Controls whether the compiler allocates the size of overlaid psects to ensure compatibility when the psect is shared by code created by other HP compilers. This qualifier solves a problem that can occur when a psect generated by a Fortran COMMON block is overlaid with a psect consisting of a C struct. Because Fortran COMMON blocks are not padded, if the C struct is padded, the inconsistent psect sizes can cause linker error messages. Compiling with /PSECT_MODEL=MULTILANGUAGE ensures that the compiler uses a consistent psect size allocation scheme. The corresponding Fortran squalifier is /ALIGN=COMMON=[NO]MULTILANGUAGE. The default is /PSECT=NOMULTILANGUAGE, which should be sufficient for most applications. /PURE_CNAME /PURE_CNAME /PURE_CNAME (D) (/STANDARD=STRICT_ANSI) /NOPURE_CNAME (D) (All other modes) Affects insertion of the names into the global namespace by headers. In /PURE_CNAME mode, the headers insert the names into the std namespace only, as defined by the C++ Standard. In this mode, the __PURE_CNAME and __HIDE_FORBIDDEN_NAMES macros are predefined by the compiler. In /NOPURE_CNAME mode, the headers insert the name into the std namespace and also into the global namespace. In this mode, the __PURE_CNAME and __HIDE_FORBIDDEN_NAMES macros are not predefined by the compiler. The default depends on the standard mode: o In /STANDARD=STRICT_ANSI mode, the default is /PURE_CNAME. o In all other standard modes, the default is /NOPURE_CNAME. Inclusion of a header instead of its counterpart (for example, instead of ) results in inserting names defined in the header into both the std namespace and the global namespace. Effectively, this is the same as the inclusion of a header in /NOPURE_CNAME mode. /QUIET /QUIET /QUIET /NOQUIET (D) Specifying /QUIET causes the compiler to report errors like the Version 5.n compiler (issue fewer messages). This is the default for ARM mode (/STANDARD=ARM). All other modes default to /NOQUIET. Use /WARNINGS=ENABLE to enable specific messages normally disabled with /QUIET. /REENTRANCY /REENTRANCY /REENTRANCY=option /REENTRANCY=TOLERANT (D) Controls the type of reentrancy that reentrant HP C RTL routines exhibit. (See also the DECC$SET_REENTRANCY RTL routine.) This qualifier is for use only with a module containing the main routine. The reentrancy level is set at run time according to the /REENTRANCY qualifier specified while compiling the module containing the main routine. This option affects the behavior of the C RTL, but has no effect on the C++ libraries. You can specify one of the following options: Option Usage AST Uses the __TESTBITSSI built-in function to perform simple locking around critical sections of RTL code, and may additionally disable asynchronous system traps (ASTs) in locked region of codes. This type of locking should be used when AST code contains calls to DEC C RTL I/O routines. MULTITHREADDesigned to be used in conjunction with the DECthreads product. It performs DECthreads locking and never disables ASTs. NONE Gives optimal performance in the RTL, but does absolutely no locking around critical sections of RTL code. It should be used only in a single threaded environment when there is no chance that the thread of execution will be interrupted by an AST that would call the HP C RTL. TOLERANT Uses the __TESTBITSSI built-in function to perform simple locking around critical sections of RTL code, but ASTs are not disabled. This type of locking should be used when ASTs are used and must be delivered immediately. This is the default reentrancy type. /REPOSITORY /REPOSITORY /REPOSITORY=(PATHNAME [,...]) /REPOSITORY=[.CXX_REPOSITORY] (D) Specifies a repository that C++ uses to store requested template instantiations. The default is /REPOSITORY=[.CXX_REPOSITORY]. If multiple repositories are specified, only the first is considered writable and the default repository is ignored unless specified. /ROUNDING_MODE /ROUNDING_MODE /ROUNDING_MODE=option /ROUNDING_MODE=NEAREST (D) Lets you select an IEEE rounding mode if /FLOAT=IEEE_FLOAT is specified. The options are as follows: Option Usage CHOPPED Rounds toward 0. DYNAMIC Sets the rounding mode for IEEE floating-point instructions dynamically, as determined from the contents of the floating-point control register. MINUS_ Rounds toward minus infinity. INFINITY NEAREST Sets the normal rounding mode (unbiased round to nearest). This is the default. If you specify either /FLOAT=G_FLOAT or /FLOAT=D_FLOAT, then rounding defaults to /ROUNDING_MODE=NEAREST, with no other choice of rounding mode. /RTTI /RTTI /RTTI (D) /NORTTI (Alpha only) Enables or disables support for RTTI (runtime type identification) features: dynamic_cast and typeid. Disabling runtime type identification can also save space in your object file because static information to describe polymorphic C++ types is not generated. The default is to enable runtime type information features and generate static information in the object file. The /RTTI qualifier defines the macro __RTTI. Note that specifying /NORTTI does not disable exception handling. /SHARE_GLOBALS /SHARE_GLOBALS /SHARE_GLOBALS /NOSHARE_GLOBALS (D) Controls whether the initial extern_model is shared or not shared (for those extern_models where it is allowed). The initial extern_model of the compiler is a fictitious pragma constructed from the settings of the /EXTERN_MODEL and /SHARE_GLOBALS. The default value is /NOSHARE_GLOBALS, which has the following effects: o When linking old object files or object libraries with newly produced object files, you might get "conflicting attributes for psect" messages, which can be safely ignored as long as you are not building shareable libraries. o The /noshare_globals default makes building shareable libraries easier. /SHOW /SHOW /SHOW=(option[,...]) /SHOW=(HEADER,SOURCE) (D) Used with the /LIST qualifier to set or cancel specific listing options. You can select the following options: Option Usage ALL Print all listing information. [NO]HEADER Print/do not print header lines at the top of each page (D = HEADER) [NO]INCLUDE Print/do not print contents of #include files (D = NOINCLUDE) NONE Print no listing information [NO]SOURCE Print/do not print source file statements (D = SOURCE) [NO]STATISTICPrint/do not print compiler performance statistics (D = NOSTATISTICS). On I64 systems, the /SHOW=STATISTICS option is ignored. /STANDARD /STANDARD /STANDARD=(option) /STANDARD=RELAXED (D) The compiler implements the International ANSI C++ Standard. The /STANDARD qualifier directs the compiler to interpret source code according to certain nonstandard syntax conventions followed by other implementations of the C++ language. The options are: Option Usage RELAXED Allow language constructs required by the International ANSI C++ Standard. This mode also supports some non-ANSI extensions and issues messages for some nonstandard usage that does not strictly comply with the standard. This is the default compiler mode. This option also defines the macro __STD_ANSI. Please note that ANSI is accepted as a synonym for RELAXED to be compatible with previous C++ versions. ARM Minimize source changes when compiling programs developed using Version 5.n. This option also defines the macro __STD_ARM. The /STANDARD=ARM qualifier uses the pre-ansi AT&T version of the iostream library and defines the macro __NO_USE_STD_IOSTREAM. CFRONT As of Version 7.1 of the C++ compiler, support for /STANDARD=CFRONT is retired. GNU Use this option if you want to compile programs developed using the GNU C++ compiler. This option also defines the __STD_GNU macro. The /STANDARD=GNU qualifier uses the pre-ansi AT&T version of the iostream library and defines the macro __NO_USE_ STD_IOSTREAM. The following changes in behavior are provided for compatibility with the GNU C++ compiler: o These options are enabled by default: /ALTERNATIVE_TOKENS /TEMPLATE_DEFINE=LOCAL /NO_IMPLICIT_INCLUDE o Access control is not enforced for types defined inside a class. o Unrecognized character escape sequences in string literals produce an informational instead of a warning message. o The __INLINE keyword is enabled and is equivalent to inline. o The severity of the error "incompatible parameter" (tag incompatibleprm) is reduced to warning. o When overloading, enum types are treated as integral types. The following known incompatibility is not addressed in the /STANDARD=GNU mode: o The compiler strictly enforces the requirement to define functions before they are used. This requirement also applies to built-in functions such as strlen. MS Allow language constructs supported by the Visual C++ compiler. This option also defines the macro __STD_ MS. The /STANDARD=MS qualifier uses the pre-ansi AT&T version of the iostream library and defines the macro __NO_USE_STD_IOSTREAM. STRICT_ Enforce the ANSI standard strictly but permit some ANSI ANSI violations that should be errors to be warnings. This option also defines the macro __STD_STRICT_ANSI. To force ANSI violations to be issued as errors instead of warnings, use /WARNINGS=ANSI_ERRORS in addition to /STANDARD=STRICT_ANSI. This combination defines the macro __STD_STRICT_ANSI_ERRORS. The /STANDARD=STRICT_ ANSI qualifier uses the ANSI/ISO standard version of the iostream library and defines the macro __USE_STD_ IOSTREAM. LATEST Latest C++ standard dialect (Alpha, I64). /STANDARD=LATEST is currently equivalent to /STANDARD=STRICT_ANSI, but is subject to change when newer versions of the C++ standard are released. For more information on the effect of the /STANDARD qualifier on HP C++ compile-time error checking, "Compiler Compatibility" in the HP C++ User's Guide for OpenVMS Systems. /TEMPLATE_DEFINE /TEMPLATE_DEFINE=(option,...) /NOTEMPLATE_DEFINE Controls compiler behavior pertaining to the instantiation of C++ templates. See "Using Templates" in the HP C++ User's Guide for OpenVMS Systems for details on how to instantiate templates using this qualifier. Note that you must specify a value for this qualifier. /UNDEFINE /UNDEFINE /UNDEFINE=(identifier[,...]) /NOUNDEFINE (D) Performs the same function as the #undefine preprocessor directive: it cancels a macro definition. The /UNDEFINE qualifier is useful for undefining the predefined C++ preprocessor constants. For example, if you use a preprocessor constant to conditionally compile segments of code specific to C++ for OpenVMS systems, you can undefine constants to see how the portable sections of your program execute. For example: /UNDEFINE="deccxx" When both /DEFINE and /UNDEFINE are present on the CXX command line, /DEFINE is evaluated before /UNDEFINE. /UNSIGNED_CHAR /UNSIGNED_CHAR /UNSIGNED_CHAR /NOUNSIGNED_CHAR (D) The /UNSIGNED_CHAR qualifier changes the default for all char types from signed to unsigned. The /NOUNSIGNED_CHAR qualifier causes all plain char declarations to have the same representation and set of values as signed char declarations. /USING_STD /USING_STD /USING_STD /NOUSING_STD (D) Controls whether standard library header files are processed as though the compiled code were written as follows: using namespace std; #include
These options are provided for compatibility for users who do not want to qualify use of each standard library name with std:: or put using namespace std; at the top of their sources. /USING_STD turns implicit using namespace std on; this is the default when compiling /STANDARD=ARM, /STANDARD=GNU, /STANDARD=MS, or /STANDARD=RELAXED. /NOUSING_STD turns implicit using namespace std off; this is the default when compiling /STANDARD=STRICT_ANSI. /VERSION /VERSION /VERSION /NOVERSION (D) Causes the compiler to identify (print out) its version and operating system. The listing file also contains the compiler version. You cannot specify this qualifier with any other qualifiers. /WARNINGS /WARNINGS /WARNINGS[=(option[,...])] /WARNINGS (D) /NOWARNINGS Controls the issuance of compiler diagnostic messages and lets you modify the severity of messages. The default qualifier, /WARNINGS, outputs all enabled warning and informational messages for the compiler mode you are using. The /NOWARNINGS qualifier suppresses warning and informational messages. Options apply only to warning and informational messages. The message-list in the following table of options can be any one of the following: o A single message identifier (within parentheses, or not). The message identifier is the name following the message severity letter on the first line of an issued message. For example, in the following message, the message identifier is GLOBALEXT: %CC-W-GLOBALEXT, a storage class of globaldef, globalref, or globalvalue is a language extension. o A comma-separated list of message identifiers, enclosed in parentheses. o The keyword ALL. The options are processed and take effect in the following order: NOWARNINGS Suppresses warnings. NOINFORMATIONALS Suppresses informational messages. ENABLE=message-list Enables issuance of the specified messages. Can be used to enable specific messages that normally would not be issued when using /QUIET or messages disabled with /WARNINGS=DISABLE. DISABLE=message-list Disables issuance of the specified messages. Can be used for any nonerror message specified by a message number or tag. Specify ALL to suppress all informationals and warnings. INFORMATIONALS=message-Sets the severity of all specified list messages to Informational. Fatal and Error messages cannot be made less severe. Can also be used to enable informationals that are disabled by default. Note: With C++ Version 7.1, using /WARNINGS=INFORMATIONALS= no longer enables all other informational messages. WARNINGS=message- Sets the severity of the specified list messages to Warning. Fatal and Error messages cannot be made less severe. [NO]ANSI_ERRORS Issues error messages for all ANSI violations when in STRICT_ANSI mode. The default is /WARNINGS=NOANSI_ERRORS. [NO]TAGS Displays a descriptive tag at the end of each message. "D" indicates that the severity of the message can be controlled from the command line. The tag displayed can be used as the message identifier in the /WARNINGS qualifier options. ERRORS=message-list Sets the severity of the specified messages to Error. Supplied Error and Fatal messages cannot be made less severe. (Exception: A message can be upgraded from Error to Fatal, then later downgraded to Error again, but it can never be downgraded from Error.) Warnings and Informationals can be made any severity. FATALS=message-list Sets the severity of the specified messages to Fatal. Also see the #pragma message preprocessor directive. /XREF /XREF (Alpha only) /XREF[=file-spec] /NOXREF (D) Controls whether the compiler generates a file of source code analysis information. The default file name is the file name of the primary source file; the default file type is .XREF. Use the SCA IMPORT command to convert an .XREF file into an analysis data file that is ready for loading into an SCA library. 2 Language_Topics This section discusses language topics. 3 Built-In_Functions Built-in functions allow you direct access hardware and machine instructions to perform operations that are cumbersome, slow, or impossible in pure C. These functions are efficient because they are built into the C++ compiler. This means that a call to one of these functions does not result in a reference to a function in the C run-time library or in your programs. Instead, the compiler generates the machine instructions necessary to carry out the function directly at the call site. Because most of these built-in functions closely correspond to single Alpha or I64 machine instructions, the result is small, fast code. Some of these functions (such as those that operate on strings or bits) are of general interest. Others (such as the functions dealing with process context) are of interest if you are writing device drivers or other privileged software. Some of the functions are privileged and unavailable to user mode programs. Be sure to include the header file in your source program to access these built-in functions. C++ supports the #pragma builtins preprocessor directive for compatibility with VAX C, but it is not required. Some of the built-in functions have optional arguments or allow a particular argument to have one of many different types. To describe different valid combinations of arguments, the description of each built-in function may list several different prototypes for the function. As long as a call to a built-in function matches one of the prototypes listed, the call is valid. Furthermore, any valid call to a built-in function acts as if the corresponding prototype was in scope, so the compiler performs the argument checking and argument conversions specified by that prototype. The majority of the built-in functions are named after the machine instruction that they generate. For more information on these built-in functions, see the documentation on the corresponding machine instruction. In particular, see that reference for the structure of queue entries manipulated by the queue built-in functions. The C++ built-in functions available on OpenVMS Alpha systems are also available on I64 systems, with some differences. There are also built-in functions specific to I64 systems. For more information on built-in functions, see "Built-In Functions" in the HP C++ User's Guide for OpenVMS Systems. Translation_Macros C++ for OpenVMS Alpha and I64 systems does not support the VAX C built-in functions. However, the header file contains macro definitions that translate some VAX C builtins to the equivalent C++ for OpenVMS Alpha builtins. Consequently, the following VAX C builtins are effectively supported: _BBCCI (position, address) _BBSSI (position, address) _INSQHI (new_entry, head) _INSQTI (new_entry, head) _INSQUE (new_entry, predecessor) _REMQHI (head, removed_entry) _REMQTI (head, removed_entry) _PROBER (mode, length, address) _PROBEW (mode, length, address) Intrinsic Functions On OpenVMS Alpha systems, C++ supports in-line assembly code, commonly called ASMs on UNIX platforms. OpenVMS I64 systems do not support ASMs. Like builtin-functions, ASMs are implemented with a function- call syntax. But unlike built-in functions, to use ASMs you must include the header file containing prototypes for the three types of ASMs, and the #pragma intrinsic preprocessor directive. Syntax: __int64 asm(const char *, ...); /* for integer operations, like mulq */ float fasm(const char *, ...); /* for single precision float instructions */ double dasm(const char *, ...); /* for double precision float instructions */ #pragma intrinsic (asm) #pragma intrinsic (fasm) #pragma intrinsic (dasm) The first argument to the asm, fasm, or dasm function contains the instruction(s) to be generated inline and the metalanguage that describes the interpretation of the arguments. The remaining arguments (if any) are the source and destination arguments for the instruction being generated. 3 Variable_Length_Argument_Lists The set of functions and macros defined and declared in the and the header files provide a method of accessing variable-length argument lists. (Note that the functions are defined by the ANSI C++ standard and are, therefore, portable as compared with those defined in .) The C++ RTL functions such as printf and execl, for example, use variable-length argument lists. User-defined functions with variable-length argument lists that do not use or are not portable due to the different argument-passing conventions of various machines. To use these functions and macros in , you must include the header file with the following preprocessor directive: #include The header file declares a type (va_list) and three macros (va_start, va_arg, and va_end) for advancing through a list of function arguments of varying number and type. The macros have the following syntax: void va_start(va_list ap, parmN); type va_arg(va_list ap, type); void va_end(va_list ap); The va_start macro initializes the object ap of type va_list for subsequent use by va_arg and va_end. The va_start macro must be invoked before any access to the unnamed arguments. The parameter parmN is the identifier of the rightmost parameter in the variable parameter list of the function definition. If parmN is declared with the register storage class, with a function or array type, or with a type that is not compatible with the type that results after application of the default arguments promotions, the behavior is undefined. The va_start macro returns no value. The va_arg macro expands to an expresion that has the type and value of the next argument in the call. The parameter ap is the same as the one initialized by va_start. Each invocation of va_ arg modifies ap so that the values of successive arguments are returned in turn. The parameter "type" is a type name specified such that the type of a pointer to an object that has the specified type can be obtained by postfixing an asterisk (*) to "type". If there is no actual next argument, or if type is not compatible with the type of the next actual argument (as promoted according to the default argument promotions), the behavior is undefined. The first invocation of va_arg after that of va_ start returns the value of the argument after that specified by parmN. Successive invocations return the values of the remaining arguments in turn. The va_end macro facilitates a normal return from the function whose variable argument list was referred to by the expansion of va_start that initialized the va_list ap object. The va_end macro can modify ap) so that it can no longer be used (without an intervening invocation of va_start). If there is no corresponding invocation of va_start or if va_end is not invoked before the return, the behavior is undefined. The va_end macro returns no value. 3 Preprocessor The C++ preprocessor uses directives to affect the compilation of a source file. For C++ on OpenVMS systems, these directives are processed by an early phase of the compiler, not by a separate program. The preprocessor directives begin with a number sign (#) and do not end with a semicolon. The number sign must appear in the first column of the source line. o Null_directive (#) A preprocessing directive of the form # is a null directive and has no effect. o Conditional_Compilation Conditional compilation is provided by the following directives: #if constant-expression - Checks whether the constant expression is nonzero (true). #ifdef identifier - Checks whether the identifier is defined. #ifndef identifier - Checks whether the identifier is undefined. #else - Introduces source lines to be compiled as an alternative to the conditions tested by the previous directives. #elif constant-expression - Delimits alternative source lines to be compiled if the constant expression in the corresponding #if, ##ifdef, or #ifndef directive is false and if the additional constant expression presented in the #elif directive is true. An #elif directive is optional. #endif - Ends the scope of the previous directives. If the condition checked by #if, #ifdef, or #ifndef is true, then all lines between the #else, #elif, and #endif are ignored. If the condition is false, then any lines between the conditional directive and the #else or #elif (if any) are ignored. If there is no #else, then the lines between the conditional and the #endif are ignored. o #define The #define preprocessor directive has the form: #define identifier token-string The preprocessor substitutes the token string everywhere in the program that it finds the identifier except within comments, character constants, or string constants. Macro replacements are defined in a #define directive of the following form: #define name([parm1[,parm2,...]]) token-string Within the program, all macro references that have the following form are replaced by the token string. The arguments in the macro reference replace the corresponding parameters in the token string. name([arg1[,arg2,...]]) o #error The #error directive issues an optional diagnostic message, and ends compilation. This directive has the following form: #error [message] o #include The #include directive instructs the preprocessor to insert the contents of the specified file or module into the program. An #include directive can have one of three forms: #include "filespec" #include #include module-name The first two forms are ANSI-compliant methods of file inclusion and are therefore more portable. In these forms, .h is the default file type, unless the compiler is instructed to supply no default type (that is, a type of just ".") by the /ASSUME=NOHEADER_TYPE_DEFAULT qualifier. The third form is specific to OpenVMS systems for specifying the inclusion of a module from a text library, and is not generally needed or recommended because the ANSI forms also cause the text libraries to be searched. For the order of search, see /INCLUDE_DIRECTORY. There is no defined limit to the nesting level of #include files and modules. o #line The #line directive applies a specified line number and optional file specification to the next line of source text. This can be useful for diagnostic messages. The #line directive has the following forms: #line integer-constant #line integer-constant "filename" #line pp-tokens In the first two forms, the compiler gives the line following a #line directive the number specified by the integer constant. The optional filename in quotation marks indicates the name of the source file that the compiler will provide in its diagnostic messages. If the filename is omitted, the file name used is the name of the current source file or the last filename specified in a previous #line directive. In the third form, macros in the #line directive are expanded before it is interpreted. This allows a macro call to expand into the integer-constant, filename, or both. The resulting #line directive must match one of the other two forms, and is then processed as appropriate. o #pragma The #pragma directive performs compiler-specific tasks as designated by each implementation of the C language. HP C++ for OpenVMS Systems supports the following pragmas: #pragma [no]builtins Enables the C++ built-in functions that directly access processor instructions. If the pragma does not appear in your program, the default is #pragma nobuiltins. C++ supports the #pragma builtins preprocessor directive for compatibility with VAX C, but it is not required. #pragma define_template Instructs the compiler to instantiate a template with the arguments specified in the pragma. Syntax: #pragma define_template identifier For example, the following statement instructs the compiler to instantiate the template mytempl with the arguments arg1 and arg2: #pragma define_template mytempl #pragma environment Sets, saves, or restores the states of context pragmas. This directive protects include files from contexts set by encompassing programs, and protects encompassing programs from contexts that could be set in header files that they include. The #pragma environment directive affects the following pragmas: o #pragma extern_model o #pragma extern_prefix o #pragma member_alignment o #pragma message o #pragma pointer_size o #pragma required_pointer_size Syntax: #pragma environment command_line #pragma environment header_defaults #pragma environment restore #pragma environment save command_line Sets, as specified on the command line, the states of all the context pragmas. You can use this pragma to protect header files from environment pragmas that take effect before the header file is included. header_defaults Sets the states of all the context pragmas to their default values. This is almost equivalent to the situation in which a program with no command-line options and no pragmas is compiled, except that this pragma sets the #pragma message state to #pragma nostandard, as is appropriate for header files. save Saves the current state of every pragma that has an associated context. restore Restores the current state of every pragma that has an associated context. #pragma extern_model Controls the compiler's interpretation of objects that have external linkage. This pragma lets you choose the global symbol model to be used for externs. Syntax: #pragma extern_model common_block [attr[,attr]...] #pragma extern_model relaxed_refdef [attr[,attr]...] #pragma extern_model strict_refdef "name" [attr[,attr]...] #pragma extern_model strict_refdef #pragma extern_model globalvalue #pragma extern_model save #pragma extern_model restore The default model on C++ is #pragma relaxed_refdef noshr. This is different from the model used by VAX C, which is common block, shr. The [attr[,attr]...] are optional psect attribute specifications chosen from the following (at most one from each line): o gbl lcl (Not allowed with relaxed_refdef) o shr noshr o wrt nowrt o pic nopic (Not meaningful for Alpha) o ovr con o rel abs o exe noexe o vec novec o 0 byte 1 word 2 long 3 quad o octa 16 page See the HP C++ User's Guide for OpenVMS Systems for more information on the #pragma extern_model directive. #pragma extern_prefix Controls the compiler's synthesis of external names, which the linker uses to resolve external name requests. When you specify #pragma extern_prefix with a string argument, the compiler prepends the string to all external names produced by the declarations that follow the pragma specification. This pragma is useful for creating libraries where the facility code can be attached to the external names in the library. Syntax: #pragma extern_prefix "string" #pragma extern_prefix save #pragma extern_prefix restore Where "string" prepends the quoted string to external names in the declarations that follow the pragma specification. The save and restore keywords can be used to save the current pragma prefix string and to restore the previously saved pragma prefix string, respectively. The default external prefix, when none has been specified by a pragma, is the null string. #pragma function Specifies that calls to the specified functions are not intrinsic but are, in fact, function calls. This pragma has the opposite effect of #pragma intrinsic. Syntax: #pragma function (function1[, function2, ...]) #pragma include_directory The effect of each #pragma include_directory is as if its string argument (including the quotes) were appended to the list of places to search that is given its initial value by the /INCLUDE_DIRECTORY qualifier, except that an empty string is not permitted in the pragma form. Syntax: #pragma include_directory This pragma is intended to ease DCL command-line length limitations when porting applications from POSIX-like environments built with makefiles containing long lists of -I options that specify directories to search for headers. Just as long lists of macro definitions specified by the /DEFINE qualifier can be converted to #define directives in a source file, long lists of places to search specified by the /INCLUDE_DIRECTORY qualifier can be converted to #pragma include_directory directives in a source file. Note that the places to search, as described in the help text for the /INCLUDE_DIRECTORY qualifier, include the use of POSIX-style pathnames, for example "/usr/base". This form can be very useful when compiling code that contains POSIX- style relative pathnames in #include directives. For example, #include can be combined with a place to search such as "/usr/base" to form "/usr/base/subdir/foo.h", which will be translated to the filespec "USR:[BASE.SUBDIR]FOO.H" This pragma can appear only in the main source file or in the first file specified on the /FIRST_INCLUDE qualifier. Also, it must appear before any #include directives. #pragma [no]inline Expands function calls inline. The function call is replaced with the function code itself. Syntax: #pragma inline (id,...) #pragma noinline (id,...) If a function is named in an inline directive, calls to that function will be expanded as inline code, if possible. If a function is named in a noinline directive, calls to that function will not be expanded as inline code. If a function is named in both an inline and a noinline directive, an error message is issued. For calls to functions named in neither an inline nor a noinline directive, C++ expands the function as inline code whenever appropriate as determined by a platform-specific algorithm. #pragma intrinsic Specifies that calls to the specified functions are intrinsic (that is, handled internally by the compiler, allowing it to generate inline code, move or eliminate calls, or do various other optimizations). This pragma is only valid for functions that are known to the compiler. Syntax: #pragma intrinsic (function1[, function2, ...]) #pragma [no]member_alignment Tells the compiler to align structure members on the next boundary appropriate to the type of the member rather than the next byte. For example, a long variable is aligned on the next longword boundary; a short variable on the next word boundary. Syntax: #pragma nomember_alignment [base_alignment] #pragma member_alignment [save | restore] The optional base_alignment parameter can be used with #pragma nomember_alignment to specify the base alignment of the structure. Use one of the following keywords to specify the base_alignment: o BYTE (1 byte) o WORD (2 bytes) o LONGWORD (4 bytes) o QUADWORD (8 bytes) o OCTAWORD (16 bytes) The optional save and restore keywords can be used to save the current state of the member_alignment and to restore the previous state, respectively. This feature is necessary for writing header files that require member_alignment or nomember_alignment, or that require inclusion in a member_ alignment that is already set. #pragma message Controls the issuance of individual diagnostic messages or groups of messages. Use of this pragma overrides any command- line options that may affect the issuance of messages. Syntax: #pragma message option1 message-list #pragma message option2 where option1 is: disable Suppresses the issuance of the indicated messages. Only messages of severity Warning (W) or Information (I) can be disabled. If the message has severity of Error (E) or Fatal (F), it is issued regardless of any attempt to disable it. enable Enables the issuance of the indicated messages. error Sets the severity of each message in the message-list to Error. fatal Sets the severity of each message on the message-list to Fatal. informational Sets the severity of each message in the message-list to Informational. warning Sets the severity of each message in the message-list to Warning. The message-list can be any one of the following: o A single message identifier (within parentheses or not). o A comma-separated list of message identifiers, enclosed in parentheses. o The keyword ALL-All the messages in the compiler. option2 is: save-saves the current state of which messages are enabled and disabled. restore-restores the previous state of which messages are enabled and disabled. #pragma module Changes the system-recognized module name and version number. You can find the module name and version number in the compiler listing file and the linker load map. Syntax: #pragma module identifier identifier #pragma module identifier string The first parameter must be a valid C++ identifier. It specifies the module name to be used by the linker. The second parameter specifies the optional identification that appears on listings and in the object file. It must be either a valid DEC C identifier of 31 characters or less, or a character- string constant of 31 characters or less. Only one #pragma module directive can be processed per compilation unit, and that directive must appear before any C language text. The #pragma module directive can follow other directives, such as #define, but it must precede any function definitions or external data definitions. #pragma once Specifies that the header file is evaluated only once. Syntax: #pragma once #pragma pack Specifies the byte boundary for packing members of C structures. Syntax: #pragma pack [n] The n specifies the new alignment restriction in bytes: 1 - align to byte 2 - align to word 4 - align to longword 8 - align to quadword 16 - align to octaword A structure member is aligned to either the alignment specified by #pragma pack or the alignment determined by the size of the structure member, whichever is smaller. For example, a short variable in a structure gets byte-aligned if #pragma pack 1 is specified. If #pragma pack 2, 4, or 8 is specified, the short variable in the structure gets aligned to word. If #pragma pack is not used, or if it is specified without the n, packing defaults to 16 on OpenVMS Alpha and I64 systems, and to 1 (byte alignment) on OpenVMS VAX systems. #pragma pointer_size Controls whether pointers are 32-bit pointers or 64-bit pointers. Syntax: #pragma pointer_size keyword Where keyword is one of the following: short-32-bit pointer long-64-bit pointer system_default-32-bit pointers on OpenVMS systems; 64-bit pointers on Tru6 UNIX systems save-Saves the current pointer size restore-Restores the current pointer size to its last saved state This directive is enabled only when the /POINTER_SIZE command- line qualifier is specified. Otherwise, #pragma pointer_size has the same effect as #pragma required_pointer_size. #pragma required_pointer_size Intended for use by developers of header files to control pointer size within header files. Syntax: #pragma required_pointer_size keyword Where keyword is one of the following: short-32-bit pointer long-64-bit pointer system_default-32-bit pointers on OpenVMS systems; 64-bit pointers on Tru6 UNIX systems save-Saves the current pointer size restore-Restores the current pointer size to its last saved state This directive is always enabled, even if the /POINTER_ SIZE command-line qualifier is omitted. Otherwise, #pragma required_pointer_size has the same effect as #pragma pointer_ size. #pragma [no]standard Directs the compiler to define regions of source code where portability diagnostics are not to be issued. Use #pragma nostandard to suppress diagnostics about non-ANSI C extensions, regardless of the /STANDARD qualifier specified, until a #pragma standard directive is encountered. Use #pragma standard to reinstate the setting of the /STANDARD qualifier that was in effect before before the last #pragma nostandard was encountered. Every #pragma standard directive must be preceded by a corresponding #pragma nostandard directive. Note that this pragma does not change the current mode of the compiler or enable any extensions not already supported in that mode. #pragma use_linkage Associates a special linkage, defined by the #pragma linkage directive, with the specified functions. Syntax: #pragma use_linkage linkage-name (routine1, routine2, ...) The linkage-name is the name of a linkage previously defined by the #pragma linkage directive. The parenthesized list contains the names of functions you want to associated with the named linkage. o #undef The #undef directive cancels a previously defined macro replacement. Any other macro replacements that occurred before the #undef directive remain. The #undef directive has the following syntax: #undef identifier 3 Predefined_Macros The compiler defines the following macros and names. For more detailed information, see the HP C++ User's Guide for OpenVMS Systems. The * character following a name indicates that the name cannot be redefined or undefined. Macro Description _BOOL_EXISTS Indicates that bool is a type or keyword __BOOL_IS_A_RESERVED_WORD Indicates that bool is a keyword __DATE__ A string literal containing the date of the translation in the form Mmm dd yyyy, or Mmm d yyyy if the value of the date is less than 10 __FILE__ A string literal containing the name of the source file being compiled __IEEE_FLOAT Identifies floating-point format for compiling the program. The value is always 1 for HP Tru64 UNIX. __LINE__ A decimal constant containing the current line number in the C++ source file __PRAGMA_ENVIRONMENT Indicates that that the pragma environment directive is supported. __TIME__ A string literal containing the time of the translation in the form of hh:mm:ss _WCHAR_T Indicates that wchar_t is a keyword The following table lists names with a defined value of 1. Name Description __cplusplus Language identification name. __DECCXX Language identification name. __VMS System identification __vms System identification The compiler predefines __VMS; the C compiler predefines VMS and __VMS. Therefore, C++ programmers who plan to reuse code should check for __VMS. The compiler supports the following predefined macro names: Name Description __Alpha_AXP System identification name __ALPHA System identification name __alpha System identification name __32BITS Defined when pointers and data of type long are 32 bits on Alpha platforms The compiler predefines __32BITS when pointers and data of type long are 32 bits on Alpha platforms. On both UNIX and OpenVMS Alpha operating systems, programmers should use the predefined macro __alpha for code that is intended to be portable from one system to the other. Predefined macros (with the exception of vms_version, VMS_ VERSION, __vms_version, __VMS_VERSION, and __INITIAL_POINTER_ SIZE) are defined as 1 or 0, depending on the system (VAX or Alpha processor), the compiler defaults, and the qualifiers used. For example, if you compiled using G_FLOAT format, __D_FLOAT and __IEEE_FLOAT (Alpha processors only) are predefined to be 0, and __G_FLOAT is predefined as if the following were included before every compilation unit: #define __G_FLOAT 1 These macros can assist in writing code that executes conditionally. They can be used in #elif, #if, #ifdef, and #ifndef directives to separate portable and nonportable code in a C++ program. The vms_version, VMS_VERSION, __vms_version, and __VMS_VERSION macros are defined with the value of the OpenVMS version on which you are running (for example, Version 6.0). C++ automatically defines the following macros pertaining to the format of floating-point variables. You can use them to identify the format with which you are compiling your program. __D_FLOAT __G_FLOAT __IEEE_FLOAT _IEEE_FP __X_FLOAT The value of __X_FLOAT can be 0 or 1 depending on the floating point mode in effect. You can use the /FLOAT qualifier to change the mode. The following table lists predefined version string and version number macros. Name Description __VMS_VERSION Version identification __vms_version Version identification __DECCXX_VER Version identification __VMS_VER Version identification For example, the defined value of __VMS_VERSION on OpenVMS Version 6.1 is character string V6.1. You can use __DECCXX_VER to test that the current compiler version is newer than a particular version and __VMS_VER to test that the current OpenVMS Version is newer than a particular version. Newer versions of the compiler and the Openvms operating system always have larger values for these macros. If for any reason the version cannot be analyzed by the compiler, then the corresponding predefined macro is defined but has the value of 0. Releases of the compiler prior to Version 5.0 do not define these macros, so you can distinguish earlier compiler versions by checking to determine if the __DECCXX_VER macro is defined. The following example tests for C++ 5.1 or higher: #ifdef __DECCXX_VER #if __DECCXX_VER >= 50100000 / *Code */ #endif #endif The following tests for OpenVMS Version 6.2 or higher: #ifdef __VMS_VER #if __VMS_VER >= 60200000 /* code */ #endif #endif The following table shows the macro names for the listed command- line qualifiers. Command-line Option Macro Name /ASSUME=GLOBAL_ARRAY_NEW __GLOBAL_ARRAY_NEW /ASSUME=STDNEW __STDNEW /DEFINE=__FORCE_ __FORCE_INSTANTIATIONS INSTANTATIONS /EXCEPTIONS __EXCEPTIONS /IEEE_MODE _IEEE_FP /IMPLICIT_INCLUDE __IMPLICIT_INCLUDE_ENABLED /L_DOUBLE_SIZE __X_FLOAT /MODEL=ANSI __MODEL_ANSI /MODEL=ARM __MODEL_ARM /PURE_CNAME __PURE_CNAME, __HIDE_FORBIDDEN_NAMES /ROUNDING_MODE __BIASED_FLT_ROUNDS /RTTI __RTTI /STANDARD=RELAXED __STD_ANSI, __NOUSE_STD_IOSTREAM /STANDARD=ANSI __STD_ANSI, __NOUSE_STD_IOSTREAM /STANDARD=ARM __STD_ARM, __NOUSE_STD_IOSTREAM /STANDARD=GNU __STD_GNU, __NOUSE_STD_IOSTREAM /STANDARD=MS __STD_MS, __NOUSE_STD_IOSTREAM /STANDARD=STRICT_ANSI __STD_STRICT_ANSI, __USE_STD_IOSTREAM, __PURE_CNAME __HIDE_FORBIDDEN_NAMES /STANDARD=STRICT_ANSI __STD_STRICT_ANSI_ERRORS /WARNINGS=ANSI_ERRORS __PURE_CNAME, __HIDE_FORBIDDEN_NAMES /STANDARD=LATEST __STD_STRICT_ANSI, __USE_STD_IOSTREAM, __PURE_CNAME __HIDE_FORBIDDEN_NAMES /STANDARD=LATEST __STD_STRICT_ANSI_ERRORS /WARNINGS=ANSI_ERRORS __PURE_CNAME, __HIDE_FORBIDDEN_NAMES /USING=STD __IMPLICIT_USING_STD 2 Release_Notes The release notes for C++ are contained in the following files: SYS$HELP:CXX.RELEASE_NOTES SYS$HELP:CXX_RELEASE_NOTES.PS You can type or print these files to read the release notes information. 2 Class_Library To access help on the C++ Class Library, enter the following command at the DCL command prompt: $ HELP CXXL 2 Standard_Library To access help on the C++ Standard Library, enter the following command at the DCL command prompt: $ HELP CXXLSTD 2 Customer_Support Premium support is available on a per-incident basis http://www.hp.com/hps/perevent/pv_software.html and annual contracts http://www.hp.com/hps/os/os_openvms.html from HP Services in the US and some other countries. In the US and Canada, call, toll-free, 1-800-354-9000. In other countries, support phone numbers are available on the web at: http://welcome.hp.com/country/us/en/wwcontact.html Free support is limited to bug reports that can be sent to compaq_cxx.bugs@hp.com Send a complete but short example reproducing the problem, including the following: o Compiler and operating system versions o All necessary sources (such as INCLUDE files and module sources) o Data files o Commands used to compile, link and run the program o Expected results and incorrect results obtained Please try to reduce the problem to as small a source as possible, because we may be unable to diagnose large applications. We answer most quickly those problem reports that include a small but complete reproducible example, along with descriptions of the compile and link options used and the exact text of any diagnostic messages or other incorrect results. Reports that include only program fragments or involve very large applications generally will not be accepted. Please note that this is not a "programming consulting service" and that you should have clear evidence of a product problem before contacting us. If you need consulting services, please contact HP Services. 2 CXXLINK To access help on the CXXLINK facility, enter the following command at the DCL command prompt: $ HELP CXXLINK 2 CXXDEMANGLE To access help on the CXXDEMANGLE facility, enter the following command at the DCL command prompt: $ HELP CXXDEMANGLE Status: 200 OK Content-Type: text/plain; charset=ISO-8859-1 Last-Modified: Fri, 24 Jun 2011 18:47:48 GMT Script-Control: X-stream-mode=1 1 CXXDEMANGLE The CXXDEMANGLE command enables you to decode compiler-generated names. To accomplish this, CXXDEMANGLE uses a data file created by the C++ compiler when you compile a program. The data file contains a mapping of symbol names from their encoded to decoded forms. When asked to decode a name that is not the data file, CXXDEMANGLE returns the original name. CXXDEMANGLE provides two interfaces: a command line interface and an interactive interface. o To use the command line interface, enter the CXXDEMANGLE command followed by a comma-separated list of symbol names in their mangled form. CXXDEMANGLE then displays the demangled form of each symbol and exits. The syntax for the command line interface is: CXXDEMANGLE mangled-symbol-name [,...] o To use the interactive interface, enter the CXXDEMANGLE command without specifying a symbol name. CXXDEMANGLE then waits for you to enter a symbol name in its mangled form. When you enter a symbol, CXXDEMANGLE displays the demangled form of the symbol and waits for you to enter another symbol, and so forth. To exit the interactive interface, enter . The syntax for the interactive interface is: CXXDEMANGLE mangled-symbol-name [...] 2 Command_Parameters mangled-symbol-name CXXDEMANGLE accepts symbol names in their mangled form, as they might appear in the output from a CXXLINK/NOEXPAND command. If you specify a mangled symbol name using the command line interface and the symbol contains lowercase letters, you must place the symbol within quotes. For example, $ CXXDEMANGLE "MyFunction__xic". Quotes are not necessary when entering mangled symbol names using the interactive interface. 2 Data File You can specify the location of the data file using the logical name CXX$DEMANGLER_DB. For example, if the data file is in your login directory and is named MYCXXDB.DAT, you would define the CXX$DEMANGLER_DB logical name as follows: $ DEFINE CXX$DEMANGLER_DB SYS$LOGIN:MYCXXDB.DAT If you do not define the CXX$DEMANGLER_DB logical name, CXXDEMANGLE looks for the data file in the repositories specified by the /REPOSITORY qualifier. If you do not specify the /REPOSITORY qualifier, CXXDEMANGLE looks for the data file in the sys$disk:[.cxx_repository] directory. 2 Qualifiers The CXXDEMANGLE command accepts two qualifiers: /REPOSITORY=(repository[,...]) /MANGLE 2 /REPOSITORY=(repository[,...]) Names the repository directories which contain the data files used by CXXDEMANGLE. The /REPOSITORY qualifier is ignored if you define the CXX$DEMANGLER_DB logical name. See Data File for details. 2 /MANGLE Mangles the input string. 2 Customer_feedback Customers with support contracts should seek support for problems through local customer support centers. Customers who do not have support contracts are encouraged to mail problem reports to !-- HTML EXCLUDE START ! compaq_cxx.bugs@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx.bugs@compaq.com !-- HTML INCLUDE STOP Although these reports will certainly be used as a source of input for fixing problems for new releases, we cannot give the reports individual attention. We can take remedial action only on a best-effort basis. If you have questions, suggestions, or comments, please send mail to !-- HTML EXCLUDE START ! compaq_cxx@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx@compaq.com !-- HTML INCLUDE STOP When reporting problems to HP, please provide the following information: o Name and version of compiler (from a listing file) o Name and version of operating system o Smallest possible complete source and commands needed to reproduce the problem o An example of the incorrect results and the desired results Status: 200 OK Content-Type: text/plain; charset=ISO-8859-1 Last-Modified: Fri, 24 Jun 2011 18:47:48 GMT Script-Control: X-stream-mode=1 1 CXXL This is the online help for the C++ Class Library. For help on the C++ Standard Library, type help cxxlstd 2 Overview The DEC C++ Class Library is a set of headers and other files implementing a collection of C++ classes. In the library, these classes are arranged in functionally related groups called packages. For help on the C++ Standard Library, type help cxxlstd 2 Thread_safety Developers of multithreaded applications should note that: o Internal class library data is thread safe; multiple threads can access the DEC C++ Class Library simultaneously without compromising the integrity of the internal data. o The predefined stream objects, cerr, cin, clog, and cout are thread safe. However, you need to provide synchronization around sequences of operations on these objects. See also: help on Predefined_stream_objects_synchronization. o User-defined objects are not thread safe; users must provide synchronization for such objects if they are shared between threads. For more information, see help on the Mutex_package. o The ios class member function sync_with_stdio() is not thread safe; if your application calls this function, the call must come before any threads that use the predefined stream objects: cerr, cin, clog, or cout. o Generation of error messages within the Vector Package is not thread safe; the package uses static data members to handle the current error message and there is no synchronization between threads. HP recommends that you define a single Mutex object to synchronize all use of the Vector Package. o The Task Package is not thread safe; only one task can execute at a time. 2 complex_package The complex package provides ways to perform arithmetic operations, such as initialization, assignment, input, and output, on complex values (that is, numbers with a real part and an imaginary part). Additionally, this package supports operations that are unique to complex values, such as principal argument operations, conjugate operations, and conversions to and from polar coordinates. With the c_exception class and its c_exception function, the complex package also provides a mechanism for reporting and handling complex arithmetic errors. Header: #include 3 Global_Declarations The following declarations are used by the complex package but they are not members of a particular class: typedef int (*cxxl_p_complex_error_t)(c_exception &error_information); static const complex_zero (0, 0); cxxl_p_complex_error_t set_complex_error(cxxl_p_complex_error_t p_complex_error 3 complex This class contains methods to perform complex value operations. These include arithmetic, assignment, and comparison operators for complex values; Cartesian and polar coordinates; mixed-mode arithmetic; and mathematical functions for complex values equivalent to standard mathematical functions. 3 c_exception Objects of this class handle exceptions for complex arithmetic. This includes information on functions, parameters, error types, and default return values. 2 generic_package The generic package provides ways to simulate parameterized types by allowing the instantiation of class declarations using the macro facilities of the DEC C++ preprocessor. You can use the generic package to construct container classes. The actual types of the data members are passed at compile time as parameters to the class when you use the class name. Header: #include To declare a generic type: 1. Define a name for the class and specify the number of type parameters: o To specify one type parameter, use the name2 macro o To specify two type parameters, use the name3 macro For example: #define myclass(mytype) name2(myType, myClass) 2. Define the class body as a macro. For example: #define myclass declare(myParam) class {...} #define myclass implement(myParam) ... 3. Declare the actual class (any valid C++ type). For example: declare(myClass, T) By substituting one or another class, you can declare multiple instances of the generic class template with various component types. For example, depending on the type parameter you use, you can declare such types as list of int, list of strings, or list of lists. 2 iostream_package Classes in the iostream package provide methods to handle input and output streams, including the reading and writing of built-in data types. You can also extend certain methods described here to handle class types. This package includes, among others, the ios and streambuf classes, and the subclasses derived from these base classes. The istream (input stream) class supports input operations(extractions); the ostream (output stream) class supports output operations (insertions). The iostream class derives from both istream and ostream, and supports both extractions and insertions. The following stream objects are predefined: cin An istream_withassign object linked to standard input cout An istream_withassign object linked to standard output cerr An ostream_withassign object linked to standard error that supports unbuffered output clog An ostream_withassign object linked to standard error that supports buffered output To generate output, you apply the insertion operator (<<) to cout. For example: cout << "Hello\n"; Providing input is similar to generating output except that you apply the extraction operator (>>) to cin. For example: int eye, jay; cin >> eye >> jay; If you include these fragments of code in a program, your system expects users to type in two integer values (for eye and jay) from a terminal. The iostream package supplies predefined extraction and insertion operators for all built-in data types, including char*. The iostream package also supports file manipulation. To connect a specific file to your program, instantiate one of the following class types: ifstream For file input ofstream For file output fstream For both input and output To format within character arrays, the iostream package includes the following associated class types: istrstream For fetching characters from an array ostrstream For storing characters into an array strstream For both fetching and storing characters into an array 3 Parameterized_manipulators Each of these manipulators takes a single argument, operates on it as described, and returns it. 4 lock(Mutex &) Locks a recursive mutex 4 resetiosflags(long) Clears, in the stream (istream or ostream), the format bits denoted by the argument. 4 setfill(int) Sets the fill character (istream or ostream) to be the value specified by the argument. 4 setiosflags(long) Turns on, in the stream (istream or ostream), the format bits denoted by the argument. 4 setprecision(int) Sets the precision (istream or ostream) to be the value specified by the argument. 4 setw(int w) Sets the field width of the stream (left-hand operand: ostream or istream) to the value specified by the argument. 4 unlock(Mutex &) unlocks a recursive mutex 3 filebuf This class specializes the streambuf class to use a file as a repository of characters. Writing to the file consumes characters; reading from the file produces characters. Files that allow searches are said to be seekable. When a file is readable and writable, the filebuf object permits character insertion and extraction. Header: #include 3 fstream This class specializes the class iostream to files using a filebuf object to do the input and output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. Header: #include 3 ifstream This class specializes the class istream to files using a filebuf object to do the input. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. Header: #include 3 ios Classes derived from the ios class provide an interface for transferring formatted and unformatted information into and out of streambuf objects. Header: #include 4 Deriving_a_user_class If you derive your own class from the ios class, or from one of its derived classes, the ios sub-object must be properly initialized during instantiation. Specifically, you must ensure that the streambuf pointer within the ios sub-object is valid. To do this, you can specify the ios(streambuf *) constructor as a member initializer for your class constructor. Optionally, you can call the ios::init(streambuf *) member function. 3 iostream This class combines the classes istream and ostream. You use it to carry out bidirectional operations (inserting into and extracting from a single sequence of characters). Header: #include 3 iostream_withassign This class adds an assignment operator and a constructor with no operands to the iostream class. Header: #include 3 istream This class provides facilities for formatted and unformatted extraction from streambuf objects. Header: #include 3 istream_withassign This class adds an assignment operator and a constructor with no operands to the istream class. Header: #include 3 istrstream This class specializes the istream class to perform extractions from arrays of bytes in memory. Header: #include 3 ofstream This class specializes the class ostream to files using a filebuf object to do the output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. Header: #include 3 ostream Objects of this class perform formatted and unformatted insertions into streambuf objects. Header: #include 3 ostream_withassign This class adds an assignment operator and a constructor with no operands to the ostream class. Header: #include 3 ostrstream This class specializes the ostream class to perform insertions into arrays of bytes in memory. Header: #include 3 stdiobuf This class specializes the streambuf class for stdio FILEs. It uses unbuffered mode, which causes all operations to be reflected immediately in the FILE. Header: #include 3 stdiostream This class specializes the ios class for stdio FILEs; it also specializes the ios class to use stdiobuf as its associated streambuf. Header: #include 3 streambuf This class supports buffers into which you can insert (put) or extract (get) characters. It contains only the basic members for manipulating the characters. To implement the functions of this class, use a class derived from the streambuf class. The protected members of this class present an interface to the derived classes organized around the get, put, and reserve areas (arrays of bytes), which are managed cooperatively by the base and derived classes. The reserve area is a sequence of characters with an associated get pointer, put pointer, or both. This area serves mainly as a resource in which to allocate space for the put and get areas. As characters enter and exit the reserve area, the put and get areas change but the reserve area remains fixed. A collection of character pointer values defines the three areas. These pointers infer a boundary condition; therefore, it may be helpful to consider such pointers as pointing just before the byte but they actually point right at it. Classes derived from streambuf vary in their handling of the get and put pointers. The simplest are unidirectional buffers that permit only get and put operations. Such classes serve as producers and consumers of characters. Queue-like buffers (such as strstream and strstreambuf) have a put and a get pointer that move independently of each other. In such buffers, stored characters are queued until later fetched. File-like buffers (such as filebuf) allow both get and put operations but have their get and put pointers linked together, so that when one pointer moves so does the other. To manage the collections of characters in the get and put areas, you can call virtual functions. Services supplied by virtual functions include fetching more characters from an ultimate producer and flushing a collection of characters to an ultimate consumer. Header: #include 3 strstream This class specializes iostream for storing in and fetching from arrays of bytes. It handles all predefined data types, and provides an extensive set of options for performing input and output on these data types. Header: #include 3 strstreambuf Objects of this class let you use an array of bytes (a string of characters) in memory as a streambuf for stream input/output operations on various kinds of data. Mapping between abstract get and put pointers and char* pointers is direct in the sense that a char* is interpreted as pointing immediately ahead of the char it points to. Moving the pointers corresponds to incrementing and decrementing the char* values. To accommodate the need for strings of arbitrary length, this class supports a dynamic mode. When a strstreambuf object is in dynamic mode, space for the character is allocated as needed. When the sequence is extended too far, it is copied to a new array. Header: #include 3 Manipulators Manipulators are supplied to let executing programs insert values into or extract values from a stream to cause some special effect as follows: ios &dec(ios &s) Sets the conversion base format to decimal. ios &hex(ios &s) Sets the conversion base format to hexadecimal. ios &oct(ios &s) Sets the conversion base format to octal. ios &lock(ios &s) Locks a predefined object ios &unlock(ios &s) Unlcks a predefined object istream &ws(istream &i) Extracts (skips) white-space characters. ostream &endl(ostream &o) Ends a line by inserting a new-line character and flushing. ostream &ends(ostream &o) Ends a string by inserting a null (0) character. ostream &flush(ostream &o) Flushes ostreams. 3 IMANIP(TYPE) This class supplies predefined parameterized manipulators and provides macros for user-defined parameterized manipulators for istream objects. Header: #include 3 IOMANIP(TYPE) This class supplies predefined parameterized manipulators and provides macros for user-defined parameterized manipulators for iostream objects. Header: #include 3 OMANIP(TYPE) This class supplies predefined parameterized manipulators and provides macros for user-defined parameterized manipulators for ostream objects. Header: #include 3 SMANIP(TYPE) This class supplies predefined parameterized manipulators and provides macros for user-defined parameterized manipulators for ios objects. Header: #include 3 Predefined_stream_objects_synchronization Two unparameterized locking and unlocking manipulators, lock and unlock, are available for use in synchronizing access to the predefined stream objects: cerr, cin, clog, and cout. If your application needs to lock two or more of these objects at the same time, the application must adhere to this locking order: cin, cerr, clog, cout The unlocking order is not important. When your application calls a member function for a predefined stream object, the member function will typically lock the object for the duration of the call. Therefore, if your application has locked one of the stream objects and then uses another, this use must also adhere to the predefined locking order. For example, your application should not send output to cerr while cout is locked. The locking order necessarily matches the default 'ties' between the stream objects as follows: cin is tied to cout cerr is tied to cout clog is tied to cout cout has no ties Any input/output operation on a stream object causes the iostream Package to flush the object to which it is tied. Thus, an output to cerr flushes cout. 3 User-defined_stream_objects_synchronization Two parameterized locking and unlocking manipulators, lock and unlock, are available for use in synchronizing access to user-defined stream objects. To use these manipulators, you must first define a Mutex object which you then pass to the manipulator. The association of a Mutex object with a stream object is not enforced by the iostream package. This association is enforced only by a program developer. For more information, see help on the Mutex_package. 2 messages_package The Messages package provides a way to retrieve messages stored in a file separate from your program. It consists of a single class, Messages. Objects of this class retrieve the text of messages for a given message set number. A message set number is an OpenVMS message identification code, including a facility code (bits 16 through 27) and a facility-specific bit (bit 15); all other bits should be 0. To process the message file, use the OpenVMS Message Utility (see the OpenVMS Message Utility Manual for details). Link the resulting object code into one of the following: Your program A shareable image that your program is linked against A shareable image that is then specified with the set message command Header: #include 2 Mutex_package The Mutex package provides a way to synchronize access to user-defined objects. It consists of a single class, Mutex, that manages the creation, locking and unlocking of Mutex objects. Construction of a Mutex object creates a recursive mutex that users can lock and unlock using the appropriate member functions or parameterized manipulators. A recursive mutex is a mutex that can be locked many times by the same thread without causing the thread to enter a deadlock state. To completely unlock this kind of mutex, the thread must unlock the mutex the same number of times that the thread locked the mutex. Note that user-defined objects are not automatically thread safe. Users must supply synchronization for such objects if they are shared between threads. Header: #include 2 Objection_package The Objection package provides a way to implement simple error handling in DEC C++. You can use this package to catch run-time errors encountered when using classes, and to change or restore actions associated with such errors. Header: #include 2 Stopwatch_package The Stopwatch package provides ways to measure intervals of program execution time. The package consists of a single class, Stopwatch. Typically, you use this class during the performance-tuning phase of program development. Objects of the Stopwatch class measure program execution time and return the result in floating-point seconds. The class includes the start, stop, and reset functions familiar to users of a mechanical stopwatch. You can time the entire program or select certain portions of the program to time; for example, a specified loop or program module. You can create a different Stopwatch object for each independent program activity, and name each according to the activity you intend to measure. Header: #include 2 String_package The String package consists of the single class, String, which provides ways to assign, concatenate, and compare character strings. This class also provides methods for substring creation and for vector access to a character string. For some applications, services provided by the String class are like those provided by the traditional C string library (strcpy, strcmp, and so forth), but are more efficient and convenient in the context of C++. Overloaded operators provide ways to assign, concatenate, and compare strings. New operators provide simple notations for substring creation and vector access into the string. All comparisons are lexicographic with the ordering dependent on the character set in which the string is encoded. An index value of 0 indicates the first character in a String object. Header: #include 2 task_package The task package provides coroutine support. A coroutine, or task, is a subroutine that can suspend execution to allow other tasks to run. Static data is shared among all tasks; automatic and register data is allocated separately for each task. Only one task can execute at a time, even on a multiprocessor system. Programming with tasks can be particularly appropriate for simulations, real-time process control, or other applications that can be reasonably represented as sets of concurrent activities. This package includes the object and randint classes, and the subclasses derived from these classes plus the histogram class. Also, note the following: o The sched class is intended for use only as a base class. o The task package makes use of other libraries. o The task package is not thread safe. You cannot create tasks simultaneously from different threads. Header: #include 3 Global_Declarations These enums, externs, and typedefs of the task package are used by one or more classes but they are not members of any particular class. 4 Print_Function_Values The following values are used in the verbosity argument to print member functions: 0 Requests a brief report CHAIN Requests information about tasks on the object's remember chain, and about other objects on the object's o_next chain STACK Requests information about the run-time stack VERBOSE Requests detailed information on the class object 4 Queue_Mode_Values The following values are used by the qhead and qtail classes for managing queues: EMODE Generates a run-time error if full on enqueue or empty on dequeue WMODE Suspends task execution if full on enqueue or empty on dequeue ZMODE Returns NULL if full on enqueue or empty on dequeue 4 Exception_Codes The following codes handle exceptions for the classes indicated: E_OLINK = 1 Cannot delete an object with a remembered task (object class) E_ONEXT = 2 Cannot delete an object which is on a list (object class) E_GETEMPTY = 3 Cannot get an object from an empty queue (qhead class) E_PUTOBJ = 4 Cannot put an object into a full queue (qtail class) E_PUTFULL = 5 Cannot put an object into a queue if the object is on another queue (qtail class) E_BACKOBJ = 6 Cannot putback an object into a queue if the object is on another queue (qhead class) E_BACKFULL = 7 Cannot putback an object into a full queue (qhead class) E_SETCLOCK = 8 Cannot set the clock after it has advanced past 0 (sched class) E_CLOCKIDLE = 9 Cannot advance the clock when clock_task is RUNNING or TERMINATED (sched class) E_RESTERM = 10 Cannot resume a TERMINATED task (sched class) E_RESRUN = 11 Cannot resume a RUNNING task (sched class) E_NEGTIME = 12 Cannot delay a negative amount of time (sched class) E_RESOBJ = 13 Cannot resume a task or timer if it is already on another queue (sched class) E_HISTO = 14 Cannot construct a histogram with less than 1 bucket or the left not less than the right (histogram class) E_STACK = 15 Cannot extend stack (task class) E_STORE = 16 Cannot allocate more memory (object, qhead, qtail, and task classes) E_TASKMODE = 17 Cannot create a task with a mode other than DEDICATED or SHARED (task class) E_TASKDEL = 18 Cannot delete a task which is IDLE or RUNNING (task class) E_TASKPRE = 19 Cannot preempt a task which is IDLE or TERMINATED (task class) E_TIMERDEL = 20 Cannot delete a timer which is IDLE or RUNNING (timer class) E_SCHTIME = 21 Cannot execute something at a time which already passed (sched class) E_SCHOBJ = 22 Cannot use class sched other than as a base class (sched class) E_QDEL = 23 Cannot delete a queue which has an object in the queue (qhead and qtail classes) E_RESULT = 24 Cannot call result() on thistask (task class) E_WAIT = 25 Cannot call wait() on thistask (task class) E_FUNCS = 26 Encountered an unexpected exception or access violation E_FRAMES = 27 Not used in DEC C++ E_REGMASK = 28 Not used in DEC C++ E_FUDGE_SIZE = 29 Not used in DEC C++ E_NO_HNDLR = 30 Cannot handle a signal for which there is no handler (Interrupt_handler class) E_BADSIG = 31 Cannot handle a signal with an invalid signal number (Interrupt_handler class) E_LOSTHNDLR = 32 Cannot handle a signal which is not on a stack of them for the given signal (Interrupt_handler class) E_TASKNAMEOVERRUN = 33 Not used in DEC C++ 4 Maximum_stack_size To keep track of the maximum stack size that can be printed by the function task::print(), set the _hwm (high-water marking) data member to a nonzero value before creation of the first task. Declaration: extern int _hwm 3 erand Objects of this class are generators of exponentially distributed random numbers. 3 histogram Objects of this class generate histograms. 3 Interrupt_handler Interrupt handlers let tasks wait for external events (system signals), and allow the declaration of handler functions for these events. You can use classes derived from the Interrupt_handler class to overload the interrupt() function. When the signal is raised, the task system immediately calls the interrupt() function. The task system then schedules its own internal interrupt alerter for execution. Control returns to the task (if any) that was running when the signal was raised. When control returns to the scheduler, the interrupt alerter runs and schedules for execution those tasks that were waiting for the interrupt handler. If the run chain is empty, the scheduler does not cause the program to exit if there are any interrupt handlers that have been created but not yet destroyed. 3 object This class is a base class for many other classes within the task package. You can also use it to derive user classes to be placed in the task package's queues and so forth. All objects derived from the object class can declare the virtual function object::pending(), which the scheduler uses to determine if an object is ready or not. You can provide each kind of object with its own method of determining its state of readiness. Each pending object contains a list (the remember chain) of the waiting task objects. 3 qhead This class provides facilities for taking objects off a queue. A queue is a data structure with an associated list of objects of the object class, or a class derived from the object class in first-in, first-out order. All access to a queue is through either the attached qhead or the attached qtail. You create a queue by creating either a qhead or a qtail. The other end of the queue is created automatically. You can then obtain a pointer to the tail with the qhead::tail function. Objects have definitions of when they are ready and pending (not ready). The qhead objects are ready when the queue is not empty and pending when the queue is empty. 3 qtail This class provides facilities for putting objects into a queue. A queue is a data structure with an associated list of objects of the object class, or a class derived from the object class in first-in, first-out order. All access to a queue is through either the attached qhead or the attached qtail. You create a queue by creating either a qhead or a qtail. The other end of the queue is created automatically. You can then obtain a pointer to the head with the qtail::head function. Objects have definitions of when they are ready and pending (not ready). The qtail objects are ready when the queue is not full and pending when the queue is full. 3 randint Objects of this class generate uniformly distributed random numbers. Each random-number generator object produces a sequence that is independent of other random-number generator objects. 3 sched This class provides facilities for checking on the state of a task, manipulating the simulated clock, canceling a task, and checking on the result of a task. You can create instances of classes derived from the sched class, but not instances of the sched class itself. 3 task All coroutine classes are derived from this class. All work for an object of a given coroutine type occurs within the constructor for that type. The coroutine class must be exactly one level of derivation from the task class. When the object is created, the constructor takes control and runs until halted by one of the following functions: wait() sleep() resultis() When a task executes a blocking function on an object that is ready, the operation succeeds immediately and the task continues running; if the object is pending, the task waits. Control then returns to the scheduler, which selects the next task from the ready list or run chain. When a pending object becomes ready, the system puts any task waiting for that object back on the run chain. A task can be in one of the following states: RUNNING Running or ready to run IDLE Waiting for a pending object TERMINATED Completed; not able to resume running (but you can retrieve the result) 3 timer Objects of this class are timers. When a timer is created its state is RUNNING, and it is scheduled to change its state to TERMINATED after a specified number of time units. When the timer becomes TERMINATED, tasks waiting for it are scheduled to resume execution. 3 urand Objects of this class generate uniformly distributed random integers within a given range from a low to a high value. 2 vector_package The vector package provides ways to define vectors or stacks of objects of any type by using the macro expansion capability of the DEC C++ preprocessor. When used with pointers, the vector package becomes a versatile tool for constructing programs to solve complicated mathematical problems. Header: #include To declare a generic vector: 1. Include the vector.hxx header in your program and declare the vector class as follows: declare(vector, TYPE) TYPE may be any other valid C++ type name. Make sure you define the declare macro in every file that references this new vector data type. 2. Expand the implementation of all function bodies as follows: implement(vector, TYPE) This implement macro must appear once in a program. 3. Declare objects of type vector, TYPE, and use the index operator to reference these objects. The following is an example of declaration and referencing: class MyType {//...//}; declare(vector,MyType); implement(vector,MyType); vector(MyType) vec1(100), vec2(5); MyType x,y; //... if(vec2[4] == y vec1[98]) = x; The TYPE parameter must be an identifier. If it is not a class name, a fundamental type, or a type name, use a typedef to create a name for the type. For example: typedef char * PCHAR; declare (stack,PCHAR); stack(PCHAR) ptrstack; char *p = "Text"; ptrstack.push(p); 3 stack(TYPE) This class provides a generic (parameterized) data abstraction for a fixed-sized stack of objects of some given type. Before a stack can be declared or implemented, the base class, a vector with the same type parameter, must also be declared or implemented. 3 vector(TYPE) This class provides the (parameterized) data abstraction for a fixed-sized vector of objects of some given type. 2 Customer_feedback Customers with support contracts should seek support for problems through local customer support centers. Customers who do not have support contracts are encouraged to mail problem reports to !-- HTML EXCLUDE START ! compaq_cxx.bugs@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx.bugs@compaq.com !-- HTML INCLUDE STOP Although these reports will certainly be used as a source of input for fixing problems for new releases, we cannot give the reports individual attention. We can take remedial action only on a best-effort basis. If you have questions, suggestions, or comments, please send mail to !-- HTML EXCLUDE START ! compaq_cxx@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx@compaq.com !-- HTML INCLUDE STOP When reporting problems to HP, please provide the following information: o Name and version of compiler (from a listing file) o Name and version of operating system o Smallest possible complete source and commands needed to reproduce the problem o An example of the incorrect results and the desired results Status: 200 OK Content-Type: text/plain; charset=ISO-8859-1 Last-Modified: Fri, 24 Jun 2011 18:47:48 GMT Script-Control: X-stream-mode=1 1 CXXLINK The CXXLINK command lets you link your C++ application by completing the automatic template instantiation process and ensuring that the Standard Template Library run-time support and the exception handling run-time support are linked into your application as needed. The syntax is as follows: CXXLINK file-spec [,...] 2 Command_Parameters file-spec [,...] The CXXLINK facility is layered on top of the OpenVMS Linker utility. The CXXLINK command accepts the same parameters and qualifiers as the OpenVMS Linker utility. Refer to the online help for the OpenVMS Linker utility, HELP LINK, for more information. 2 Qualifiers Refer to the online help for the OpenVMS Linker utility, HELP LINK, for information. Additionally, the following qualifiers are accepted by the CXXLINK command: o /[NO]LOG_FILE [=filename] o /MODEL=[ANSI | ARM] o /PREINST o /PRELINK=(option[,option2]) o /REPOSITORY=(writeable-repository[,readonly-repository,...]) o /USE_LINK_INPUT[=filename] o /VERSION 2 Obsolete_Qualifiers The following qualifers should no longer be used. Instead, use the corresponding /PRELINK=option qualifier. 3 /EXPAND /EXPAND (D) /NOEXPAND Controls whether CXXLINK displays unresolved C++ symbols in their mangled or demangled form. By default CXXLINK displays symbols in their demangled form. This qualifier is obsolete and may be removed in a future release to to support new OpenVMS Link Untilty qualifiers. 3 /TEMPLATE_PRELINK /TEMPLATE_PRELINK (D) /NOTEMPLATE_PRELINK Controls whether CXXLINK performs a partial link (no image output) to determine whether any unresolved template symbols need to be added to the LINK command. If you know that your program does not use templates, you can specify /NOTEMPLATE_PRELINK to bypass this partial link and proceed directly to the final link. This qualifier is obsolete and may be removed in a future release to support new OpenVMS Link Untilty qualifiers. Please use /PRELINK=TEMPLATE_PRELINK instead. 2 /LOG_FILE[=filename] /LOG_FILE[=filename] /NOLOG_FILE (D) Turns on verbose or verify mode to write each phase of instantiation to the specified log file. This option is useful as a debugging aid. 2 /MODEL=[ANSI | ARM] /MODEL=ANSI (D) Link with /MODEL=ANSI versions of the C++ libraries. See CXX/MODEL=ANSI for details. 2 /PREINST /PREINST (D) /NOPREINST Forces the standard library template instantiations in the user's repository to be preferred at link time over the ones in the standard library. This is useful, for example, if you want debugging versions of the instantiations. This option is useful only when used in conjunction with CXX/DEFINE=__FORCE_INSTANTATIONS. 2 /PRELINK=(option[,option2]) Specifies one or more prelink options. If multiple options are specified, they must be enclosed in parentheses and separated by commas. You can specify the following options: USE_OBJECT_FILES (D) Tells CXXLINK not to use the CXX$LINK.OLB library found in a repository directory. Instead, CXXLINK looks for the specific object files and adds them to the linker options file. Use of this qualifier also prevents CXXLINK from creating and populating a CXX$LINK.OLB object library in the repository directory. USE_OLB Tells CXXLINK to use the CXX$LINK.OLB found in a repository directory. Specifying this option might improve link-time performance but in some cases could produce unresolved template symbols. TEMPLATE_PRELINK (D) NOTEMPLATE_PRELINK Controls whether CXXLINK bypasses the template instantiation process. By default, CXXLINK performs at least one partial link to determine whether there are any unresolved template symbols that need to be instantiated. If you know that your program does not use templates, then you can specify /PRELINK=NOTEMPLATE_PRELINK to bypass this partial link and proceed directly to the final link. This qualifier has the same effect as specifying /TEMPLATE_PRELINK or /NOTEMPLATE_PRELINK. Because in the future, the OpenVMS Linker Utility might require that /TEMPLATE_PRELINK be removed, it is recommended that users modify their use of CXXLINK to use this new form of the qualifier. ADD_INCLUDE_LIBRARIES (D) NOADD_INCLUDE_LIBRARIES Controls whether, if initial link fails, CXXLINK adds to the linker options file the names of any object libraries specified on the command line using the /INCLUDE= syntax. CXXLINK also checks for any /INCLUDE= library when SYS$INPUT:/OPT is used. CXXLINK does not parse any other linker options file for /INCLUDE= syntax. Because of the order of dependencies between template instantions and object files, the OpenVMS Linker Utility sometimes fails to extract all the required modules from an object library that was specified using /INCLUDE=. To work around the problem CXXLINK provides that library as input to the linker in its linker options file without the /INCLUDE= syntax, thereby allowing the linker to scan that object library one more time for missing symbols. This qualifier should be used only if a CXXLINK user requires more control over which object files are included from a given object library. 2 /REPOSITORY=(writeable-repository[,readonly-repository,...]) Name the repository directories. The first item in the list is considered the writeable repository, and the remaining items (if any) are considered repositories that are read only. If you do not specify the /REPOSITORY qualifier, CXXLINK uses the default respository, SYS$DISK:[.CXX_REPOSITORY]. 2 /USE_LINK_INPUT[=filename] /USE_LINK_INPUT[=filename] /NOUSE_LINK_INPUT (D) By default, CXXLINK creates a temporary .OPT file in the [.cxx_repository] directory. If the [.cxx_repository] directory does not exist, the .OPT file is created in the users current directory. CXXLINK deletes this file. If you specify /USE_LINK_INPUT, CXXLINK saves the option file passed to LINK in a file named CXX_REPOSITORY.OPT in the user's current directory (SYS$DISK:[]CXX_REPOSITORY.OPT). CXXLINK does not delete this file. If you specify /USE_LINK_INPUT=filename CXXLINK saves the option file passed to LINK in the filename specified. Because the temporary file that CXXLINK uses is renamed to the file name specified, "filename" must reside on the same disk as the [.CXX_REPOSITORY] directory. CXXLINK does not delete this file. 2 /VERSION Direct CXXLINK to display its version identification and then exit. 2 Customer_feedback Customers with support contracts should seek support for problems through local customer support centers. Customers who do not have support contracts are encouraged to mail problem reports to !-- HTML EXCLUDE START ! compaq_cxx.bugs@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx.bugs@compaq.com !-- HTML INCLUDE STOP Although these reports will certainly be used as a source of input for fixing problems for new releases, we cannot give the reports individual attention. We can take remedial action only on a best-effort basis. If you have questions, suggestions, or comments, please send mail to !-- HTML EXCLUDE START ! compaq_cxx@compaq.com !-- HTML EXCLUDE STOP !-- HTML INCLUDE START ! ! compaq_cxx@compaq.com !-- HTML INCLUDE STOP When reporting problems to HP, please provide the following information: o Name and version of compiler (from a listing file) o Name and version of operating system o Smallest possible complete source and commands needed to reproduce the problem o An example of the incorrect results and the desired results Status: 200 OK Content-Type: text/plain; charset=ISO-8859-1 Last-Modified: Fri, 24 Jun 2011 18:47:48 GMT Script-Control: X-stream-mode=1 1 CXXLSTD This is the online help for the C++ Standard Library. For help on the Class Library, type help cxxl 2 Overview Name cxxstdlib_intro - Introduction to the HP C++ ANSI Standard Library This page describes the HP C++ ANSI Standard Library. For an overview of the pre-ANSI C++ Class Library, type help cxxl DESCRIPTION The HP C++ ANSI Standard Library is an implementation of the C++ Standard Library. It is comprised of a suite of header files and the run time code needed to implement the following clauses in the C++ Standard: ____________________________________________ Clause Description ____________________________________________ 18 Run time support (new(),exceptions) 21 String Library 22 Localization (locale) Library 23 Container Library 24 Iterator Library 25 Algorithms Library 26 Numerics Library 27 Input/Output (iostream) Library See Also iostream_intro 2 complex Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME complex - C++ complex number library This page describes ANSI complex class. If you would like information on the pre-ANSI complex package,use the command: help cxxl SPECIALIZATIONS complex complex complex SYNOPSIS #include template class complex ; class complex; class complex; class complex; DESCRIPTION complex is a class that supports complex numbers. A complex number has a real part and an imaginary part. The complex class supports equality,comparison and basic arithmetic operations. In addition, mathematical functions such as exponents, logarithms, powers, and square roots are also available. INTERFACE template class complex { public: typedef T value_type; complex (T = 0 , T = 0); template complex (const complex&); T real () const; T imag () const; complex& operator= (const T&); complex& operator+=(const T&); complex& operator-=(const T&); complex& operator*=(const T&); complex& operator/=(const T&); template complex& operator= (const complex&); template complex& operator+= (const complex&); template complex& operator-= (const complex&); template complex& operator*= (const complex&); template complex& operator/= (const complex&); }; // Non-member Operators template complex operator+ (const complex&, const complex&); template complex operator+ (const complex&, T); template complex operator+ (T, const complex&); template complex operator- (const complex&, const complex&); template complex operator- (const complex&, T); template complex operator- (T, const complex&); template complex operator* (const complex&, const complex&); template complex operator* (const complex&, T); template complex operator* (T, const complex&); template complex operator/ (const complex&, const complex&); template complex operator/ (const complex&, T); template complex operator/ (T, const complex&); template complex operator+ (const complex&); template complex operator- (const complex&); template bool operator== (const complex&, const complex&); template bool operator== (const complex&, T); template bool operator== (T, const complex&); template bool operator!= (const complex&, const complex&); template bool operator!= (const complex&, T); template bool operator!= (T, const complex&); template istream& operator>> (istream&, complex&); template ostream& operator<< (ostream&, const complex&); // Values template T real (const complex&); template T imag (const complex&); template T abs (const complex&); template T arg (const complex&); template T norm (const complex&); template complex conj (const complex&); template complex polar (T, T); // Transcendentals template complex cos (const complex&); template complex cosh (const complex&); template complex exp (const complex&); template complex log (const complex&); template complex log10 (const complex&); template complex pow (const complex&, int); template complex pow (const complex&, T); template complex pow (const complex&, const complex&); template complex pow (T, const complex&); template complex sin (const complex&); template complex sinh (const complex&); template complex sqrt (const complex&); template complex tan (const complex&); template complex tanh (const complex&); CONSTRUCTORS complex (const T& re_arg = 0, const T& im_arg = 0); Constructs an object of class complex, initializing re_arg to the real part and im_arg to the imaginary part. ASSIGNMENT OPERATORS template complex (const complex&); Copy constructor. Constructs a complex number from another complex number. complex& operator=(const T& v); Assigns v to the real part of itself, setting the imaginary part to 0. complex& operator+=(const T& v); Adds v to the real part of itself, then returns the result. complex& operator-=(const T& v); Subtracts v from the real part of itself, then returns the result. complex& operator*=(const T& v); Multiplies v by the real part of itself, then returns the result. complex& operator/=(const T& v); Divides v by the real part of itself, then returns the result. template complex operator=(const complex& c); Assigns c to itself. template complex operator+=(const complex& c); Adds c to itself, then returns the result. template complex operator-=(const complex& c); Subtracts c from itself, then returns the result. template complex operator*=(const complex& c); Multiplies itself by c then returns the result. template complex operator/=(const complex& c); Divides itself by c, then returns the result. MEMBER FUNCTIONS T imag() const; Returns the imaginary part of the complex number. T real() const; Returns the real part of the complex number. NON-MEMBER OPERATORS template complex operator+(const complex& lhs,const complex& rhs); template complex operator+(const complex& lhs, T rhs); template complex operator+(T lhs, const complex& rhs); Returns the sum of lhs and rhs. template complex operator-(const complex& lhs,const complex& rhs); template complex operator-(const complex& lhs, T rhs); operator-(T lhs, const complex& rhs); Returns the difference of lhs and rhs. template complex operator*(const complex& lhs,const complex& rhs); template complex operator*(const complex& lhs, T rhs); template complex operator* (T lhs, const complex& rhs); Returns the product of lhs and rhs. template complex operator/(const complex& lhs,const complex& rhs); template complex operator/(const complex& lhs, T rhs); template complex operator/(T lhs, const complex& rhs); Returns the quotient of lhs divided by rhs. template complex operator+(const complex& rhs); Returns rhs. template complex operator-(const complex& lhs); Returns complex(-lhs.real(), -lhs.imag()). template bool operator==(const complex& x, const complex& y); Returns true if the real and imaginary parts of x and y are equal. template bool operator==(const complex& x, T y); Returns true if y is equal to the real part of x and the imaginary part of x is equal to 0. template bool operator==(T x, const complex& y); Returns true if x is equal to the real part of y and the imaginary part of y is equal to 0. template bool operator!=(const complex& x, const complex& y); Returns true if either the real or the imaginary part of x and y are not equal. template bool operator!=(const complex& x, T y); Returns true if y is not equal to the real part of x or the imaginary part of x is not equal to 0. template bool operator!=(T x, const complex& y); Returns true if x is not equal to the real part of y or the imaginary part of y is not equal to 0. template istream& operator>>(istream& is, complex& x); Reads a complex number x into the input stream is. x may be of the form u, (u), or (u,v) where u is the real part and v is the imaginary part. If bad input is encountered, the ios::badbit flag is set. template ostream& operator<<(ostream& os, const complex& x); Returns os << "(" << x.real() << "," << x.imag() << ")". NON-MEMBER FUNCTIONS template T abs(const complex& c); Returns the absolute value or magnitude of c (the square root of the norm). template complex conj(const complex& c); Returns the conjugate of c. template complex cos(const complex& c); Returns the cosine of c. template complex cosh(const complex& c); Returns the hyperbolic cosine of c. template complex exp(const complex& x); Returns e raised to the x power. template T imag(const complex& c) const; Returns the imaginary part of c. template complex log(const complex& x); Returns the natural logarithm of x. This function returns the complex value whose phase angle is greater than -pi and less than pi. template complex log10(const complex& x); Returns the logarithm base 10 of x. template T norm(const complex& c); Returns the squared magnitude of c. (The sum of the squares of the real and imaginary parts.) template complex polar(const T& m, const T& a); Returns the complex value of a complex number whose magnitude is m and phase angle is a, measured in radians. template complex pow(const complex& x, int y); template complex pow(const complex& x, T y); template complex pow(const complex& x, const complex& y); template complex pow(T x, const complex& y); Returns x raised to the y power. template T real(const complex& c); Returns the real part of c. template complex sin(const complex& c); Returns the sine of c. template complex sinh(const complex& c); Returns the hyperbolic sine of c. template complex sqrt(const complex& x); Returns the square root of x. This function returns the complex value whose phase angle is greater than -pi/2 and less than or equal to template complex tan(const complex& x); Returns the tangent of x. template complex tanh(const complex& x); Returns the hyperbolic tangent of x. EXAMPLE // // complex.cpp // #include #include int main() { complex a(1.2, 3.4); complex b(-9.8, -7.6); a += b; a /= sin(b) * cos(a); b *= log(a) + pow(b, a); cout << "a = " << a << ", b = " << b << endl; return 0; } Output : a = (1.42804e-06,-0.0002873), b = (58.2199,69.7354) WARNINGS On compilers that don't support member function templates, the arithmetic operators will not work on any arbitrary type. (They will work only on float, double and long doubles.) You also will only be able to perform binary arithmetic on types that are the same. Compilers that don't support non-converting constructors will permit unsafe downcasts (i.e., long double to double, double to float, long double to float). STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 limits Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME limits Refer to the numeric_limits section of this reference guide. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 numeric_limits Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME numeric_limits - A class for representing information about scalar types. SPECIALIZATIONS numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits numeric_limits SYNOPSIS #include template class numeric_limits ; DESCRIPTION numeric_limits is a class for representing information about scalar types. Specializations are provided for each fundamental type, both floating point and integer, including bool. This class encapsulates information that is contained in the and headers, as well as providing additional information that is not contained in any existing C or C++ header. Not all of the information provided by members is meaningful for all specializations of numeric_limits. Any value which is not meaningful for a particular type is set to 0 or false. INTERFACE template class numeric_limits { public: // General -- meaningful for all specializations. static const bool is_specialized ; static T min (); static T max (); static const int radix ; static const int digits ; static const int digits10 ; static const bool is_signed ; static const bool is_integer ; static const bool is_exact ; static const bool traps ; static const bool is_modulo ; static const bool is_bounded ; // Floating point specific. static T epsilon (); static T round_error (); static const int min_exponent10 ; static const int max_exponent10 ; static const int min_exponent ; static const int max_exponent ; static const bool has_infinity ; static const bool has_quiet_NaN ; static const bool has_signaling_NaN ; static const bool is_iec559 ; static const bool has_denorm ; static const bool tinyness_before ; static const float_round_style round_style ; static T denorm_min (); static T infinity (); static T quiet_NaN (); static T signaling_NaN (); }; enum float_round_style { round_indeterminate = -1, round_toward_zero = 0, round_to_nearest = 1, round_toward_infinity = 2, round_toward_neg_infinity = 3 }; MEMBER FIELDS AND FUNCTIONS static T denorm_min (); Returns the minimum denormalized value. Meaningful for all floating point types. For types that do not allow denormalized values, this method must return the minimum normalized value. static const int digits ; Number of radix digits which can be represented without change. For built-in integer types, digits will usually be the number of non-sign bits in the representation. For floating point types, digits is the number of radix digits in the mantissa. This member is meaningful for all specializations that declare is_bounded to be true. static const int digits10 ; Number of base 10 digits that can be represented without change. Meaningful for all specializations that declare is_bounded to be true. static T epsilon (); Returns the machine epsilon (the difference between 1 and the least value greater than 1 that is representable). This function is meaningful for floating point types only. static const bool has_denorm ; This field is true if the type allows denormalized values (variable number of exponent bits). It is meaningful for floating point types only. static const bool has_infinity ; This field is true if the type has a representation for positive infinity. It is meaningful for floating point types only. This field must be true for any type claiming conformance to IEC 559. static const bool has_quiet_NaN ; This field is true is the type has a representation for a quiet (non-signaling) "Not a Number". It is meaningful for floating point types only and must be true for any type claiming conformance to IEC 559. static const bool has_signaling_NaN ; This field is true if the type has a representation for a signaling "Not a Number". It is meaningful for floating point types only, and must be true for any type claiming conformance to IEC 559. static T infinity (); Returns the representation of positive infinity, if available. This member function is meaningful for only those specializations that declare has_infinity to be true. Required for any type claiming conformance to IEC 559. static const bool is_bounded ; This field is true if the set of values representable by the type is finite. All built-in C types are bounded; this member would be false for arbitrary precision types. static const bool is_exact ; This static member field is true if the type uses an exact representation. All integer types are exact, but not vice versa. For example, rational and fixed-exponent representations are exact but not integer. This member is meaningful for all specializations. static const bool is_iec559 ; This member is true if and only if the type adheres to the IEC 559 standard. It is meaningful for floating point types only. Must be true for any type claiming conformance to IEC 559. static const bool is_integer ; This member is true if the type is integer. This member is meaningful for all specializations. static const bool is_modulo ; This field is true if the type is modulo. Generally, this is false for floating types, true for unsigned integers, and true for signed integers on most machines. A type is modulo if it is possible to add two positive numbers, and have a result that wraps around to a third number, which is less. static const bool is_signed ; This member is true if the type is signed. This member is meaningful for all specializations. static const bool is_specialized ; Indicates whether numeric_limits has been specialized for type T. This flag must be true for all specializations of numeric_limits. In the default numeric_limits template, this flag must be false. static T max (); Returns the maximum finite value. This function is meaningful for all specializations that declare is_bounded to be true. static const int max_exponent ; Maximum positive integer such that the radix raised to that power is in range. This field is meaningful for floating point types only. static const int max_exponent10 ; Maximum positive integer such that 10 raised to that power is in range. This field is meaningful for floating point types only. static T min (); Returns the minimum finite value. For floating point types with denormalization, min()must return the minimum normalized value. The minimum denormalized value is provided by denorm_min(). This function is meaningful for all specializations that declare is_bounded to be true. static const int min_exponent ; Minimum negative integer such that the radix raised to that power is in range. This field is meaningful for floating point types only. static const int min_exponent10 ; Minimum negative integer such that 10 raised to that power is in range. This field is meaningful for floating point types only. static T quiet_NaN (); Returns the representation of a quiet "Not a Number", if available. This function is meaningful only for those specializations that declare has_quiet_NaN to be true. This field is required for any type claiming conformance to IEC 559. static const int radix ; For floating types, specifies the base or radix of the exponent representation (often 2). For integer types, this member must specify the base of the representation. This field is meaningful for all specializations. static T round_error (); Returns the measure of the maximum rounding error. This function is meaningful for floating point types only. static const float_round_style round_style ; The rounding style for the type. Specializations for integer types must return round_toward_zero. This is meaningful for all floating point types. static T signaling_NaN(); Returns the representation of a signaling "Not a Number", if available. This function is meaningful for only those specializations that declare has_signaling_NaN to be true. This function must be meaningful for any type claiming conformance to IEC 559. static const bool tinyness_before ; This member is true if tinyness is detected before rounding. It is meaningful for floating point types only. static const bool traps ; This field is true if trapping is implemented for this type. The traps field is meaningful for all specializations. EXAMPLE // // limits.cpp // #include int main() { numeric_limits float_info; if (float_info.is_specialized && float_info.has_infinity) { // get value of infinity float finfinity=float_info.infinity(); } return 0; } WARNING The specializations for wide chars and bool will only be available if your compiler has implemented them as real types and not simulated them with typedefs. SEE ALSO IEEE Standard for Binary Floating-Point Arithmetic, 345 East 47th Street, New York, NY 10017 Language Independent Arithmetic (LIA-1) STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Containers Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Containers - A standard template library (STL) collection. DESCRIPTION Within the standard template library, collection classes are often described as containers. A container stores a collection of other objects and provides certain basic functionality that supports the use of generic algorithms. Containers come in two basic flavors: sequences, and associative containers. They are further distinguished by the type of iterator they support. A sequence supports a linear arrangement of single elements. vector, list,deque, bitset, and string fall into this category. Associative containers map values onto keys, which provides efficient retrieval of the values based on the keys. The STL provides the map, multimap, set and multiset associative containers. map and multimap store the value and the key separately and allow for fast retrieval of the value, based upon fast retrieval of the key. set and multiset store only keys allowing fast retrieval of the key itself. CONTAINER REQUIREMENTS Containers within the STL must meet the following requirements. Sequences and associative containers must also meet their own separate sets of requirements. The requirements for containers are: + A container allocates all storage for the objects it holds. + A container X of objects of type T provides the following types: X::value_type a T X::reference lvalue of T X::const_reference const lvalue of T X::iterator an iterator type pointing to T. X::iterator cannot be an output iterator. X::const_iterator an iterator type pointing to const T x::iterator cannot be an output iterator. X::difference_type a signed integral type (must be the same as the distance type for X::iterator and X::const_iterator X::size_type an unsigned integral type representing any non- negative value of difference_type X::allocatr_type type of allocator used to obtain storage for elements stored in the container + A container provides a default constructor, a copy constructor, an assignment operator, and a full complement of comparison operators (==, !=, <, >, <=, >=). + A container provides the following member functions: begin() Returns an iterator or a const_iterator pointing to the first element in the collection. end() Returns an iterator or a const_iterator pointing just beyond the last element in the collection. swap(container) Swaps elements between this container and the swap's argument. clear() Deletes all the elements in the container. size() Returns the number of elements in the collection as a size_type. max_size() Returns the largest possible number of elements for this type of container as a size_type. empty() Returns true if the container is empty, false otherwise. get_allocator() Returns the allocator used by this container REVERSIBLE CONTAINERS A container may be reversible. Essentially, a reversible container provides a reverse iterator that allows traversal of the collection in a direction opposite that of the default iterator. A reversible container must meet the following requirements in addition to those listed above: + A reversible container provides the following types: X::reverse_iterator An iterator type pointing to T. X::const_reverse_iterator An iterator type pointing to const T + A reversible container provides the following member functions: rbegin() Returns a reverse_iterator or a const_reverse_iterator pointing past the end of the collection rend() Returns a reverse_iterator or a const_reverse_iterator pointing to the first element in the collection. SEQUENCES In addition to the requirements for containers, the following requirements hold for sequences: + iterator and const_iterator must be forward iterators, bidirectional iterators or random access iterators. + A sequence provides the following constructors: X(n, t) Constructs a container with n copies of t. X(i, j) Constructs a container with elements from the range [i,j). + A sequence provides the following member functions: insert(p,t) Inserts the element t in front of the position identified by the iterator p. insert(p,n,t) Inserts n copies of t in front of the position identified by the iterator p. insert(p,i,j) Inserts elements from the range [i,j) in front of the position identified by the iterator p. erase(q) Erases the element pointed to by the iterator q. erase(q1,q2) Erases the elements in the range [q1,q2). + A sequence may also provide the following member functions if they can be implemented with constant time complexity. front() Returns the element pointed to by begin() back() Returns the element pointed to by end() push_front(x) Inserts the element x at begin() push_back(x) Inserts the element x at end() pop_front() Erases the element at begin() pop_back() Erases the element at end() -1 operator[](n) Returns the element at a.begin() + n ASSOCIATIVE CONTAINERS In addition to the requirements for a container, the following requirements hold for associative containers: + For an associative container iterator and const_iterator must be bidirectional iterators. Associative containers are inherently sorted. Their iterators proceed through the container in the nondescending order of keys (where non-descending order is defined by the comparison object that was used to construct the container). + An associative container provides the following types: X::key_type the type of the Key X::key_compare the type of the comparison to use to put the keys in order X::value_compare the type of the comparison used on values + The default constructor and copy constructor for associative containers use the template parameter comparison class. + An associative container provides the following additional constructors: X(c) Construct an empty container using c as the comparison object X(i,j,c) Constructs a container with elements from the range [i,j) and the comparison object c. X(i, j) Constructs a container with elements from the range [i,j) using the template parameter comparison object. + An associative container provides the following member functions: key_comp() Returns the comparison object used in constructing the associative container. value_comp() Returns the value comparison object used in constructing the associative container. insert(t) Inserts t if and only if there is no element in the container with key equal to the key of t. Returns a pair. The bool component of the returned pair indicates the success or failure of the operation and the iterator component points to the element with key equal to key of t. insert(p,t) If the container does not support redundant key values then this function only inserts t if there is no key present that is equal to the key of t. If the container does support redundant keys then this function always inserts the element t. The iterator p serves as a hint of where to start searching, allowing for some optimization of the insertion. It does not restrict the algorithm from inserting ahead of that location if necessary. insert(i,j) Inserts elements from the range [i,j). erase(k) Erases all elements with key equal to k. Returns number of erased elements. erase(q) Erases the element pointed to by q. erase(q1,q2) Erases the elements in the range [q1,q2). find(k) Returns an iterator pointing to an element with key equal to k or end() if such an element is not found. count(k) Returns the number of elements with key equal to k. lower_bound(k) Returns an iterator pointing to the first element with a key greater than or equal to k. upper_bound(k) Returns an iterator pointing to the first element with a key less than or equal to k. equal_range(k) Returns a pair of iterators such that the first element of the pair is equivalent to lower_bound(k) and the second element equivalent to upper_bound(k). SEE ALSO bitset, deque, list, map, multimap, multiset, priority_queue, queue, set, stack, vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Associative Containers Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Associative_Containers - Associative containers are ordered containers. These containers provide member functions that allow the efficient insertion, retrieval and manipulation of keys. The standard library provides the map, multimap, set and multiset associative containers. map and multimap associate values with the keys and allow for fast retrieval of the value, based upon fast retrieval of the key. set and multiset store only keys, allowing fast retrieval of the key itself. SEE ALSO For more information about associative containers, see the Containers section of this reference guide, or see the section on the specific container. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Bitset Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME bitset - A template class and related functions for storing and manipulating fixed-size sequences of bits. SYNOPSIS #include template class bitset ; DESCRIPTION bitset is a class that describes objects that can store a sequence consisting of a fixed number of bits, N. Each bit represents either the value zero (reset) or one (set) and has a non-negative position pos. ERRORS AND EXCEPTIONS Bitset constructors and member functions may report the following three types of errors -- each associated with a distinct exception: + invalid-argument error or invalid_argument() exception; + out-of-range error or out_of_range() exception; + overflow error or over-flow_error() exception; If exceptions are not supported on your compiler, you will get an assertion failure instead of an exception. INTERFACE template class bitset { public: // bit reference: class reference { friend class bitset; public: ~reference(); reference& operator= (bool); reference& operator= (const reference&); bool operator~() const; operator bool() const; reference& flip(); }; // Constructors bitset (); bitset (unsigned long); explicit bitset (const string&, size_t = 0, size_t = (size_t)-1); bitset (const bitset&); bitset& operator= (const bitset&); // Bitwise Operators and Bitwise Operator Assignment bitset& operator&= (const bitset&); bitset& operator|= (const bitset&); bitset& operator^= (const bitset&); bitset& operator<<= (size_t); bitset& operator>>= (size_t); // Set, Reset, Flip bitset& set (); bitset& set (size_t, int = 1); bitset& reset (); bitset& reset (size_t); bitset operator~() const; bitset& flip (); bitset& flip (size_t); // element access reference operator[] (size_t); unsigned long to_ulong() const; string to_string() const; size_t count() const; size_t size() const; bool operator== (const bitset&) const; bool operator!= (const bitset&) const; bool test (size_t) const; bool any() const; bool none() const; bitset operator<< (size_t) const; bitset operator>> (size_t) const; }; // Non-member operators template bitset operator& (const bitset&, const bitset&); template bitset operator| (const bitset&, const bitset&); template bitset operator^ (const bitset&, const bitset&); template istream& operator>> (istream&, bitset&); template ostream& operator<< (ostream&, const bitset&); CONSTRUCTORS bitset(); Constructs an object of class bitset, initializing all bit values to zero. bitset(unsigned long val); Constructs an object of class bitset, initializing the first M bit values to the corresponding bits in val. M is the smaller of N and the value CHAR_BIT * sizeof(unsigned long). If M < N, remaining bit positions are initialized to zero. Note: CHAR_BIT is defined in . explicit bitset(const string& str, size_t pos = 0, size_t n = (size_t)-1); Determines the effective length rlen of the initializing string as the smaller of n and str.size() - pos. The function throws an invalid_argument exception if any of the rlen characters in str, beginning at position pos,is other than 0 or 1. Otherwise, the function constructs an object of class bitset, initializing the first M bit positions to values determined from the corresponding characters in the string str. M is the smaller of N and rlen. This constructor requires that pos <= str.size(), otherwise it throws an out_of_range exception. bitset(const bitset& rhs); Copy constructor. Creates a copy of rhs. ASSIGNMENT OPERATOR bitset& operator=(const bitset& rhs); Erases all bits in self, then inserts into self a copy of each bit in rhs. Returns a reference to *this. OPERATORS bool operator==(const bitset& rhs) const; Returns true if the value of each bit in *this equals the value of each corresponding bit in rhs. Otherwise returns false. bool operator!=(const bitset& rhs) const; Returns true if the value of any bit in *this is not equal to the value of the corresponding bit in rhs. Otherwise returns false. bitset& operator&=(const bitset& rhs); Clears each bit in *this for which the corresponding bit in rhs is clear and leaves all other bits unchanged. Returns *this. bitset& operator|=(const bitset& rhs); Sets each bit in *this for which the corresponding bit in rhs is set, and leaves all other bits unchanged. Returns *this. bitset& operator^=(const bitset& rhs); Toggles each bit in *this for which the corresponding bit in rhs is set, and leaves all other bits unchanged. Returns *this. bitset& operator<<=(size_t pos); Replaces each bit at position I with 0 if I < pos or with the value of the bit at I - pos if I >= pos. Returns *this. bitset& operator>>=(size_t pos); Replaces each bit at position I with 0 if pos >= N-I or with the value of the bit at position I + pos if pos < N-I. Returns * this. bitset& operator>>(size_t pos) const; Returns bitset(*this) >>= pos. bitset& operator<<(size_t pos) const; Returns bitset(*this) <<= pos. bitset operator~() const; Returns the bitset that is the logical complement of each bit in *this. bitset operator&(const bitset& lhs, const bitset& rhs); lhs gets logical AND of lhs with rhs. bitset operator|(const bitset& lhs, const bitset& rhs); lhs gets logical OR of lhs with rhs. bitset operator^(const bitset& lhs, const bitset& rhs); lhs gets logical XOR of lhs with rhs. template istream& operator>>(istream& is, bitset& x); Extracts up to N characters (single-byte) from is. Stores these characters in a temporary object str of type string, then evaluates the expression x = bitset(str). Characters are extracted and stored until any of the following occurs: - N characters have been extracted and stored - An end-of-file occurs on the input sequence - The next character is neither '0' nor '1'. In this case, the character is not extracted. Returns is. template ostream& operator<<(ostream& os, const bitset& x); Returns os << x.to_string() MEMBER FUNCTIONS bool any() const; Returns true if any bit in *this is set. Otherwise returns false. size_t count() const; Returns a count of the number of bits set in *this. bitset& flip(); Flips all bits in *this, and returns *this. bitset& flip(size_t pos); Flips the bit at position pos in *this and returns *this. Throws an out_of_range exception if pos does not correspond to a valid bit position. bool none() const; Returns true if no bit in *this is set. Otherwise returns false. bitset& reset(); Resets all bits in *this, and returns *this. bitset& reset(size_t pos); Resets the bit at position pos in *this. Throws an out_of_range exception if pos does not correspond to a valid bit position. bitset& set(); Sets all bits in *this, and returns *this. bitset& set(size_t pos, int val = 1); Stores a new value in the bits at position pos in *this. If val is nonzero, the stored value is one, otherwise it is zero. Throws an out_of_range exception if pos does not correspond to a valid bit position. size_t size() const; Returns the template parameter N. bool test(size_t pos) const; Returns true if the bit at position pos is set. Throws an out_of_range exception if pos does not correspond to a valid bit position. string to_string() const; Returns an object of type string, N characters long. Each position in the new string is initialized with a character ('0' for zero and '1' for one) representing the value stored in the corresponding bit position of *this. Character position N-1 corresponds to bit position 0. Subsequent decreasing character positions correspond to increasing bit positions. unsigned long to_ulong() const; Returns the integral value corresponding to the bits in *this. Throws an overflow_error if these bits cannot be represented as type unsigned long. SEE ALSO Containers STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 deque Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME deque - A sequence that supports random access iterators and efficient insertion/deletion at both beginning and end. SYNOPSIS #include template > class deque; DESCRIPTION deque is a type of sequence that supports random access iterators. It supports constant time insert and erase operations at the beginning or the end of the container. Insertion and erase in the middle take linear time. Storage management is handled by the Allocator template parameter. Any type used for the template parameter T must provide the following (where T is the type, t is a value of T and u is a const value of T): Default constructor T() Copy constructors T(t) and T(u) Destructor t.~T() Address of &t and &u yielding T* and const T* respectively Assignment t = a where a is a (possibly const) value of T INTERFACE template > class deque { public: // Types class iterator; class const_iterator; typedef T value_type; typedef Allocator allocator_type; typename reference; typename const_reference; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; // Construct/Copy/Destroy explicit deque (const Allocator& = Allocator()); explicit deque (size_type, const Allocator& = Allocator ()); deque (size_type, const T& value, const Allocator& = Allocator ()); deque (const deque&); template deque (InputIterator, InputIterator, const Allocator& = Allocator ()); ~deque (); deque& operator= (const deque&); template void assign (InputIterator, InputIterator); template void assign (Size); template void assign (Size, const T&); allocator_type get allocator () const; // Iterators 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; // Capacity size_type size () const; size_type max_size () const; void resize (size_type); void resize (size_type, T); bool empty () const; // Element access reference operator[] (size_type); const_reference operator[] (size_type) const; reference at (size_type); const_reference at (size_type) const; reference front (); const_reference front () const; reference back (); const_reference back () const; // Modifiers void push_front (const T&); void push_back (const T&); iterator insert (iterator); iterator insert (iterator, const T&); void insert (iterator, size_type, const T&); template void insert (iterator, InputIterator, InputIterator); void pop_front (); void pop_back (); iterator erase (iterator); iterator erase (iterator, iterator); void swap (deque&); void clear(); }; // Non-member Operators template bool operator== (const deque&, const deque&); template bool operator!= (const deque&, const deque&); template bool operator< (const deque&, const deque&); template bool operator> (const deque&, const deque&); template bool operator<= (const deque&, const deque&); template bool operator>= (const deque&, const deque&); // Specialized Algorithms template voice swap (deque&, deque&); CONSTRUCTORS AND DESTRUCTOR explicit deque(const Allocator& alloc = Allocator()); The default constructor. Creates a deque of zero elements. The deque will use the allocator alloc for all storage management. explicit deque(size_type n, const Allocator& alloc = Allocator()); Creates a list of length n, containing n copies of the default value for type T. Requires that T have a default constructor. The deque will use the allocator alloc for all storage management. deque(size_type n, const T& value, const Allocator& alloc = Allocator()); Creates a list of length n, containing n copies of value. The deque will use the allocator alloc for all storage management. deque(const deque& x); Copy constructor. Creates a copy of x. template deque(InputIterator first, InputIterator last, const Allocator& alloc = Allocator()); Creates a deque of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). The deque will use the allocator alloc for all storage management. ~deque(); The destructor. Releases any allocated memory for self. ALLOCATOR allocator allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin(); Returns a random access iterator that points to the first element. const_iterator begin() const; Returns a constant random access iterator that points to the first element. iterator end(); Returns a random access iterator that points to the past-the-end value. const_iterator end() const; Returns a constant random access iterator that points to the past-the-end value. reverse_iterator rbegin(); Returns a random access reverse_iterator that points to the past-the-end value. const_reverse_iterator rbegin() const; Returns a constant random access reverse iterator that points to the past-the-end value. reverse_iterator rend(); Returns a random access reverse_iterator that points to the first element. const_reverse_iterator rend() const; Returns a constant random access reverse iterator that points to the first element. ASSIGNMENT OPERATOR deque& operator=(const deque& x); Erases all elements in self then inserts into self a copy of each element in x. Returns a reference to self. REFERENCE OPERATORS reference operator[](size_type n); Returns a reference to element n of self. The result can be used as an lvalue. The index n must be between 0 and the size less one. const_reference operator[](size_type n) const; Returns a constant reference to element n of self. The index n must be between 0 and the size() -1. MEMBER FUNCTIONS template void assign(InputIterator first, InputIterator last); Erases all elements contained in self, then inserts new elements from the range [first, last). template void assign(Size n); Erases all elements contained in self, then inserts n instances of the default value of type T. template void assign(Size n, const T& t); Erases all elements contained in self, then inserts n instances of the value of t. reference at(size_type n); Returns a reference to element n of self. The result can be used as an lvalue. The index n must be between 0 and the size() - 1. const_reference at(size_type) const; Returns a constant reference to element n of self. The index n must be between 0 and the size() - 1. reference back(); Returns a reference to the last element. const_reference back() const; Returns a constant reference to the last element. void clear(); Erases all elements from the self. bool empty() const; Returns true if the size of self is zero. reference front(); Returns a reference to the first element. const_reference front() const; Returns a constant reference to the first element. iterator erase(iterator first, iterator last); Deletes the elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. iterator erase(iterator position); Removes the element pointed to by position. Returns an iterator pointing to the element following the deleted element, or end() if there were no elements after the deleted range. iterator insert(iterator position); Inserts a copy of the default value of type T before position. The return value points to the inserted element. Requires that type T have a default constructor. iterator insert(iterator position, const T& x); Inserts x before position. The return value points to the inserted x. void insert(iterator position, size_type n, const T& x); Inserts n copies of x before position. template void insert(iterator position, InputIterator first, InputIterator last); Inserts copies of the elements in the range (first, last] before position. size_type max_size() const; Returns size() of the largest possible deque. void pop_back(); Removes the last element. Note that this function does not return the element. void pop_front(); Removes the first element. Note that this function does not return the element void push_back(const T& x); Appends a copy of x to the end. void push_front(const T& x); Inserts a copy of x at the front. void resize(size_type sz); Alters the size of self. If the new size (sz) is greater than the current size then sz-size() copies of the default value of type T are inserted at the end of the deque. If the new size is smaller than the current capacity, then the deque is truncated by erasing size()-sz elements off the end. Otherwise, no action is taken. Requires that type T have a default constructor. void resize(size_type sz, T c); Alters the size of self. If the new size (sz) is greater than the current size then sz-size() c's are inserted at the end of the deque. If the new size is smaller than the current capacity, then the deque is truncated by erasing size()-sz elements off the end. Otherwise, no action is taken. size_type size() const; Returns the number of elements. void swap(deque& x); Exchanges self with x. NON-MEMBER FUNCTIONS template bool operator==(const deque& x, const deque& y); Equality operator. Returns true if x is the same as y. template bool operator!=(const deque& x, const deque& y); Inequality operator. Returns true if x is not the same as y. template bool operator<(const deque& x, const deque& y); Returns true if the elements contained in x are lexicographically less than the elements contained in y. template bool operator>(const deque& x, const deque& y); Returns true if the elements contained in x are lexico- graphically greater than the elements contained in y. template bool operator<=(const deque& x, const deque& y); Returns true if the elements contained in x are lexico- graphically less than or equal to the elements contained in y. template bool operator>=(const deque& x, const deque& y); Returns true if the elements contained in x are lexico- graphically greater than or equal to the elements con- tained in y. template bool operator<(const deque& x, const deque& y); Returns true if the elements contained in x are lexico- graphically less than the elements contained in y. SPECIALIZED ALGORITHMS template void swap(deque& a, deque& b); Efficiently swaps the contents of a and b. EXAMPLE // // deque.cpp // #include #include deque deck_of_cards; deque current_hand; void initialize_cards(deque& cards) { cards.push_front("aceofspades"); cards.push_front("kingofspades"); cards.push_front("queenofspades"); cards.push_front("jackofspades"); cards.push_front("tenofspades"); // etc. } template void print_current_hand(It start, It2 end) { while (start < end) cout << *start++ << endl; } template void deal_cards(It, It2 end) { for (int i=0;i<5;i++) { current_hand.insert(current_hand.begin(),*end); deck_of_cards.erase(end++); } } void play_poker() { initialize_cards(deck_of_cards); deal_cards(current_hand.begin(),deck_of_cards.begin()); } int main() { play_poker(); print_current_hand(current_hand.begin(),current_hand.end()); return 0; } Output : aceofspades kingofspades queenofspades jackofspades tenofspades WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this is the constructor for deque that takes two templated iterators: template deque (InputIterator, InputIterator); deque also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a deque in the following two ways: int intarray[10]; deque first_deque(intarray, intarray + 10); deque second_deque(first_deque.begin(), first_deque.end()); But not this way: deque long_deque(first_deque.begin(), first_deque.end()); since the long_deque and first_deque are not the same type. Additionally, many compilers do not support default template arguments. If your compiler is one of these, you need to always supply the Allocator template argument. For instance, you'll have to write: deque > instead of: deque STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 list Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME list - A sequence that supports bidirectional iterators SYNOPSIS #include template > class list; DESCRIPTION list is a type of sequence that supports bidirectional iterators. A list allows constant time insert and erase operations anywhere within the sequence, with storage management handled automatically. Constant time random access is not supported. Any type used for the template parameter T must provide the following (where T is the type, t is a value of T and u is a const value of T): Default constructor T() Copy constructors T(t) and T(u) Destructor t.~T() Address of &t and &u yielding T* and const T* respectively Assignment t = a where a is a (possibly const) value of T INTERFACE template > class list { public: // typedefs class iterator; class const_iterator; typename reference; typename const_reference; typename size_type; typename difference_type; typedef T value_type; typedef Allocator allocator_type; typename reverse_iterator; typename const_reverse_iterator; // Construct/Copy/Destroy explicit list (const Allocator& = Allocator()); explicit list (size_type, const Allocator& = Allocator()); list (size_type, const T&, const Allocator& = Allocator()) template list (InputIterator, InputIterator, const Allocator& = Allocator()); list(const list& x); ~list(); list& operator= (const list&); template void assign (InputIterator, InputIterator); template void assign (Size n); template void assign (Size n, const T&); allocator_type get allocator () const; // Iterators 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; // Capacity bool empty () const; size_type size () const; size_type max_size () const; void resize (size_type); void resize (size_type, T); // Element Access reference front (); const_reference front () const; reference back (); const_reference back () const; // Modifiers void push_front (const T&); void pop_front (); void push_back (const T&); void pop_back (); iterator insert (iterator); iterator insert (iterator, const T&); void insert (iterator, size_type, const T&); template void insert (iterator, InputIterator, InputIterator); iterator erase (iterator); iterator erase (iterator, iterator); void swap (list&); void clear (); // Special mutative operations on list void splice (iterator, list&); void splice (iterator, list&, iterator); void splice (iterator, list&, iterator, iterator); void remove (const T&); template void remove_if (Predicate); void unique (); template void unique (BinaryPredicate); void merge (list&); template void merge (list&, Compare); void sort (); template void sort (Compare); void reverse(); }; // Non-member List Operators template bool operator== (const list&, const list&); template bool operator!= (const list&, const list&); template bool operator< (const list&, const list&); template bool operator> (const list&, const list&); template bool operator<= (const list&, const list&); template bool operator>= (const list&, const list&); // Specialized Algorithms template void swap (list&, list&); CONSTRUCTORS AND DESTRUCTORS explicit list(const Allocator& alloc = Allocator()); Creates a list of zero elements. The list will use the allocator alloc for all storage management. explicit list(size_type n, const Allocator& alloc = Allocator()); Creates a list of length n, containing n copies of the default value for type T. Requires that T have a default constructor. The list will use the allocator alloc for all storage management. list(size_type n, const T& value, const Allocator& alloc = Allocator()); Creates a list of length n, containing n copies of value. The list will use the allocator alloc for all storage management. template list(InputIterator first, InputIterator last, const Allocator& alloc = Allocator()); Creates a list of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). The list will use the allocator alloc for all storage management. list(const list& x); Copy constructor. Creates a copy of x. ~list(); The destructor. Releases any allocated memory for this list. ASSIGNMENT OPERATOR list& operator=(const list& x) Erases all elements in self then inserts into self a copy of each element in x. Returns a reference to *this. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin(); Returns a bidirectional iterator that points to the first element. const_iterator begin() const; Returns a constant bidirectional iterator that points to the first element. iterator end(); Returns a bidirectional iterator that points to the past-the-end value. const_iterator end() const; Returns a constant bidirectional iterator that points to the past-the-end value. reverse_iterator rbegin(); Returns a bidirectional iterator that points to the past-the-end value. const_reverse_iterator rbegin() const; Returns a constant bidirectional iterator that points to the past-the-end value. reverse_iterator rend(); Returns a bidirectional iterator that points to the first element. const_reverse_iterator rend() const; Returns a constant bidirectional iterator that points to the first element. MEMBER FUNCTIONS template void assign(InputIterator first, InputIterator last); Erases all elements contained in self, then inserts new elements from the range [first, last). template void assign(Size n); Erases all elements contained in self, then inserts n instances of the default value of t. template void assign(Size n, const T& t); Erases all elements contained in self, then inserts n instances of the value of t. reference back(); Returns a reference to the last element. const_reference back() const; Returns a constant reference to the last element. void clear(); Erases all elements from the list. bool empty() const; Returns true if the size is zero. iterator erase(iterator position); Removes the element pointed to by position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted item was the last one in this list. iterator erase(iterator first, iterator last); Removes the elements in the range (first, last). Returns an iterator pointing to the element following the element following the last deleted element, or end() if there were no elements after the deleted range. reference front(); Returns a reference to the first element. const_reference front() const; Returns a constant reference to the first element. iterator insert(iterator position); Inserts a copy of the default value for type T before position. Returns an iterator that points to the inserted value. Requires that type T have a default constructor. iterator insert(iterator position, const T& x); Inserts x before position. Returns an iterator that points to the inserted x. void insert(iterator position, size_type n, const T& x); Inserts n copies of x before position. template void insert(iterator position, InputIterator first, InputIterator last); Inserts copies of the elements in the range [first, last) before position. size_type max_size() const; Returns size() of the largest possible list. void merge(list& x); Merges a sorted x with a sorted self using operator<. For equal elements in the two lists, elements from self will always precede the elements from x. The merge function leaves x empty. template void merge(list& x, Compare comp); Merges a sorted x with sorted self using a compare function object,comp. For same elements in the two lists, elements from self will always precede the elements from x. The merge function leaves x empty. void pop_back(); Removes the last element. void pop_front(); Removes the first element. void push_back(const T& x); Appends a copy of x to the end of the list. void push_front(const T& x); Appends a copy of x to the front of the list. void remove(const T& value); template void remove_if(Predicate pred); Removes all elements in the list referred by the list iterator i for which *i == value or pred(*i) == true, whichever is applicable. This is a stable operation, the relative order of list items that are not removed is preserved. void resize(size_type sz); Alters the size of self. If the new size ( sz ) is greater than the current size, sz-size() copies of the default value of type T are inserted at the end of the list. If the new size is smaller than the current capacity, then the list is truncated by erasing size()-sz elements off the end. Otherwise, no action is taken. Requires that type T have a default constructor. void resize(size_type sz, T c); Alters the size of self. If the new size ( sz ) is greater than the current size, sz-size() c's are inserted at the end of the list. If the new size is smaller than the current capacity, then the list is truncated by erasing size()-sz elements off the end. Otherwise, no action is taken. void reverse(); Reverses the order of the elements. size_type size() const; Returns the number of elements. void sort(); Sorts self according to the operator<. sort maintains the relative order of equal elements. template void sort(Compare comp); Sorts self according to a comparison function object, comp. This is also a stable sort. void splice(iterator position, list& x); Inserts x before position leaving x empty. void splice(iterator position, list& x, iterator i); Moves the elements pointed to by iterator i in x to self, inserting it before position. The element is removed from x. void splice(iterator position, list& x, iterator first, iterator last); Moves the elements in the range [first, last) in x to self, inserting before position. The elements in the range [first,last) are removed from x. void swap(list & x); Exchanges self with x. void unique(); Erases copies of consecutive repeated elements leaving the first occurrence. template void unique(BinaryPredicate binary_pred); Erases consecutive elements matching a true condition of the binary_pred. The first occurrence is not removed. NON-MEMBER OPERATORS template bool operator==(const list& x, const list& y); Equality operator. Returns true if x is the same as y. template bool operator!=(const list& x, const list& y); Inequality operator. Returns !(x==y). template bool operator<(const list& x, const list& y); Returns true if the sequence defined by the elements contained in x is lexicographically less than the sequence defined by the elements contained in y. template bool operator>(const list& x, const list& y); Returns y < x. template bool operator<=(const list& x, const list& y); Returns !(y < x). template bool operator>=(const list& x, const list& y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(list& a, list& b); Efficiently swaps the contents of a and b. EXAMPLE // // list.cpp // #include #include #include // Print out a list of strings ostream& operator<<(ostream& out, const list& l) { copy(l.begin(), l.end(), ostream_iterator(cout," ")); return out; } int main(void) { // create a list of critters list critters; int i; // insert several critters critters.insert(critters.begin(),"antelope"); critters.insert(critters.begin(),"bear"); critters.insert(critters.begin(),"cat"); // print out the list cout << critters << endl; // Change cat to cougar *find(critters.begin(),critters.end(),"cat") = "cougar"; cout << critters << endl; // put a zebra at the beginning // an ocelot ahead of antelope // and a rat at the end critters.push_front("zebra"); critters.insert(find(critters.begin(),critters.end(), "antelope"),"ocelot"); critters.push_back("rat"); cout << critters << endl; // sort the list (Use list's sort function since the // generic algorithm requires a random access iterator // and list only provides bidirectional) critters.sort(); cout << critters << endl; // now let's erase half of the critters int half = critters.size() >> 1; for(i = 0; i < half; ++i) { critters.erase(critters.begin()); } cout << critters << endl; return 0; } Output : cat bear antelope cougar bear antelope zebra cougar bear ocelot antelope rat antelope bear cougar ocelot rat zebra ocelot rat zebra WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for list that takes two templated iterators: template list (InputIterator, InputIterator, const Allocator& = Allocator()); list also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature, we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a list in the following two ways: int intarray[10]; list first_list(intarray,intarray + 10); list second_list(first_list.begin(),first_list.end()); But not this way: list long_list(first_list.begin(),first_list.end()); since the long_list and first_list are not the same type. Additionally, list provides a merge function of this type. template void merge (list&, Compare); This function allows you to specify a compare function object to be used in merging two lists. In this case, we were unable to provide a substitute function in addition to the merge that uses the operator< as the default. Thus, if your compiler does not support member function templates, all list mergers will use operator<. Also, many compilers do not support default template arguments. If your compiler is one of these, you need to always supply the Allocator template argument. For instance, you'll have to write: list > instead of: list SEE ALSO allocator, Containers, Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 map Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME map - An associative container providing access to non-key values using unique keys. A map supports bidirectional iterators. SYNOPSIS #include template class Allocator = allocator > class map; DESCRIPTION map provides fast access to stored values of type T which are indexed by unique keys of type Key. The default operation for key comparison is the < operator. map provides bidirectional iterators that point to an instance of pair where x is the key and y is the stored value associated with that key. The definition of map provides a typedef to this pair called value_type. The types used for both the template parameters Key and T must provide the following (where T is the type, t is a value of T and u is a const value of T): Copy constructors - T(t) and T(u) Destructor - t.~T() Address of - &t and &u yielding T* and const T* respectively Assignment - t = a where a is a (possibly const) value of T The type used for the Compare template parameter must satisfy the requirements for binary functions. INTERFACE template class Allocator = allocator > class map { public: // types typedef Key key_type; typedef T mapped_type; typedef pair value_type; typedef Compare key_compare; typedef Allocator allocator_type; typename reference; typename const_reference; typename iterator; typename const_iterator; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; class value_compare : public binary_function { friend class map; public : bool operator() (const value_type&, const value_type&) const; }; // Construct/Copy/Destroy explicit map (const Compare& = Compare(), const Allocator& = Allocator ()); template map (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator ()); map (const map&); ~map(); map& operator= (const map&); allocator_type get_allocator () const; // Iterators 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; // Capacity bool empty() const; size_type size() const; size_type max_size() const; // Element Access mapped_type& operator[] (const key_type&); const mapped_type& operator[] (const key_type&) const; // Modifiers pair insert (const value_type&); iterator insert (iterator, const value_type&); template void insert (InputIterator, InputIterator); iterator erase (iterator); size_type erase (const key_type&); iterator erase (iterator, iterator); void swap (map&); // Observers key_compare key_comp() const; value_compare value_comp() const; // Map operations iterator find (const key_value&); const_iterator find (const key_value&) const; size_type count (const key_type&) const; iterator lower_bound (const key_type&); const_iterator lower_bound (const key_type&) const; iterator upper_bound (const key_type&); const_iterator upper_bound (const key_type&) const; pair equal_range (const key_type&); pair equal_range (const key_type&) const; }; // Non-member Map Operators template bool operator== (const map&, const map&); template bool operator!= (const map&, const map&); template bool operator< (const map&, const map&); template bool operator> (const map&, const map&); template bool operator<= (const map&, const map&); template bool operator>= (const map&, const map&); // Specialized Algorithms template void swap (map<*Key,T,Compare,Allocator>&, map&); CONSTRUCTORS AND DESTRUCTORS explicit map(const Compare& comp = Compare(), const Allocator& alloc = Allocator()); Default constructor. Constructs an empty map that will use the relation comp to order keys, if it is supplied. The map will use the allocator alloc for all storage management. template map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& alloc = Allocator()); Constructs a map containing values in the range [first, last). Creation of the new map is only guaranteed to succeed if the iterators first and last return values of type pair and all values of Key in the range[first, last) are unique. The map will use the relation comp to order keys, and the allocator alloc for all storage management. map(const map& x); Copy constructor. Creates a new map by copying all pairs of key and value from x. ~map(); The destructor. Releases any allocated memory for this map. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin() ; Returns an iterator pointing to the first element stored in the map. "First" is defined by the map's comparison operator, Compare. const_iterator begin() const; Returns a const_iterator pointing to the first element stored in the map. iterator end() ; Returns an iterator pointing to the last element stored in the map, i.e., the off-the-end value. const_iterator end() const; Returns a const_iterator pointing to the last element stored in the map. reverse_iterator rbegin(); Returns a reverse_iterator pointing to the first element stored in the map. "First" is defined by the map's comparison operator, Compare. const_reverse_iterator rbegin() const; Returns a const_reverse_iterator pointing to the first element stored in the map. reverse_iterator rend() ; Returns a reverse_iterator pointing to the last element stored in the map, i.e., the off-the-end value. const_reverse_iterator rend() const; Returns a const_reverse_iterator pointing to the last element stored in the map. MEMBER OPERATORS map& operator=(const map& x); Assignment. Replaces the contents of *this with a copy of the map x. mapped_type& operator[](const key_type& x); If an element with the key x exists in the map, then a reference to its associated value will be returned. Otherwise the pair x,T() will be inserted into the map and a reference to the default object T() will be returned. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS void clear(); Erases all elements from the self. size_type count(const key_type& x) const; Returns a 1 if a value with the key x exists in the map, otherwise returns a 0. bool empty() const; Returns true if the map is empty, false otherwise. pair equal_range (const key_type& x); Returns the pair, (lower_bound(x), upper_bound(x)). pair equal_range(const key_type& x) const; Returns the pair, (lower_bound(x), upper_bound(x)). iterator erase(iterator position); Deletes the map element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted item was the last one in this list. iterator erase(iterator first, iterator last); Providing the iterators first and last point to the same map and last is reachable from first, all elements in the range (first, last) will be deleted from the map. Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. size_type erase(const key_type& x); Deletes the element with the key value x from the map, if one exists. Returns 1 if x existed in the map, 0 otherwise. iterator find(const key_type& x); Searches the map for a pair with the key value x and returns an iterator to that pair if it is found. If such a pair is not found the value end() is returned. const_iterator find(const key_type& x) const; Same as find above but returns a const_iterator. pair insert(const value_type& x); iterator insert(iterator position, const value_type& x); If a value_type with the same key as x is not present in the map, then x is inserted into the map. Otherwise, the pair is not inserted. A position may be supplied as a hint regarding where to do the insertion. If the insertion may be done right after position then it takes amortized constant time. Otherwise it will take O(log N) time. template void insert(InputIterator first, InputIterator last); Copies of each element in the range [first, last) which possess a unique key, one not already in the map, will be inserted into the map. The iterators first and last must return values of type pair. This operation takes approximately O(N*log(size()+N)) time. key_compare key_comp() const; Returns a function object capable of comparing key values using the comparison operation, Compare, of the current map. iterator lower_bound(const key_type& x); Returns a reference to the first entry with a key greater than or equal to x. const_iterator lower_bound(const key_type& x) const; Same as lower_bound above but returns a const_iterator. size_type max_size() const; Returns the maximum possible size of the map. This size is only constrained by the number of unique keys which can be represented by the type Key. size_type size() const; Returns the number of elements in the map. void swap(map& x); Swaps the contents of the map x with the current map, *this. iterator upper_bound(const key_type& x); Returns a reference to the first entry with a key less than or equal to x. const_iterator upper_bound(const key_type& x) const; Same as upper_bound above but returns a const_iterator. value_compare value_comp() const; Returns a function object capable of comparing pair values using the comparison operation, Compare, of the current map. This function is identical to key_comp for sets. NON-MEMBER OPERATORS template bool operator==(const map& x, const map& y); Returns true if all elements in x are element-wise equal to all elements in y, using (T::operator==). Otherwise it returns false. template bool operator!=(const map& x, const map& y); Returns !(x==y). template bool operator<(const map& x, const map& y); Returns true if x is lexicographically less than y. Otherwise, it returns false. template bool operator>(const map& x, const map& y); Returns y < x. template bool operator<=(const map& x, const map& y); Returns !(y < x). template bool operator>=(const map& x, const map& y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(map& a, map& b); Efficiently swaps the contents of a and b. EXAMPLE // // map.cpp // #include #include #include typedef map > months_type; // Print out a pair template ostream& operator<<(ostream& out, const pair & p) { cout << p.first << " has " << p.second << " days"; return out; } // Print out a map ostream& operator<<(ostream& out, const months_type & l) { copy(l.begin(),l.end(), ostream_iterator (cout,"0)); return out; } int main(void) { // create a map of months and the number of days // in the month months_type months; typedef months_type::value_type value_type; // Put the months in the multimap months.insert(value_type(string("January"), 31)); months.insert(value_type(string("February"), 28)); months.insert(value_type(string("February"), 29)); months.insert(value_type(string("March"), 31)); months.insert(value_type(string("April"), 30)); months.insert(value_type(string("May"), 31)); months.insert(value_type(string("June"), 30)); months.insert(value_type(string("July"), 31)); months.insert(value_type(string("August"), 31)); months.insert(value_type(string("September"), 30)); months.insert(value_type(string("October"), 31)); months.insert(value_type(string("November"), 30)); months.insert(value_type(string("December"), 31)); // print out the months // Second February is not present cout << months << endl; // Find the Number of days in June months_type::iterator p = months.find(string("June")); // print out the number of days in June if (p != months.end()) cout << endl << *p << endl; return 0; } Output : April has 30 days August has 31 days December has 31 days February has 28 days January has 31 days July has 31 days June has 30 days March has 31 days May has 31 days November has 30 days October has 31 days September has 30 days WARNING Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for map that takes two templated iterators: template map (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); map also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature, we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates, you can construct a map in the following two ways: map >::value_type intarray[10]; map > first_map(intarray, intarray + 10); map > second_map(first_map.begin(), first_map.end()); But not this way: map > long_map(first_map.begin(), first_map.end()); Since the long_map and first_map are not the same type. Also, many compilers do not support default template arguments. If your compiler is one of these, you need to always supply the Compare template argument and the Allocator template argument. For instance, you'll have to write: map, allocator > instead of: map SEE ALSO allocator, Containers, Iterators, multimap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 multimap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME multimap - An associative container providing access to non-key values using keys. multimap keys are not required to be unique. A multimap supports bidirectional iterators. SYNOPSIS #include template , class Allocator = allocator > class multimap ; DESCRIPTION multimap provides fast access to stored values of type T which are indexed by keys of type Key. The default operation for key comparison is the < operator. Unlike map, multimap allows insertion of duplicate keys. multimap provides bidirectional iterators which point to an instance of pair where x is the key and y is the stored value associated with that key. The definition of multimap provides a typedef to this pair called value_type. The types used for both the template parameters Key and T must provide the following (where T is the type, t is a value of T and u is a const value of T): Copy constructors - T(t) and T(u) Destructor - t.~T() Address of - &t and &u yielding T* and const T* respectively Assignment - t = a where a is a (possibly const) value of T The type used for the Compare template parameter must satisfy the requirements for binary functions. INTERFACE template , class Allocator = allocator > class multimap { public: // types typedef Key key_type; typedef T mapped_type; typedef pair value_type; typedef Compare key_compare; typedef Allocator allocator_type; typename reference; typename const_reference; typename iterator; typename const_iterator; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; class value_compare : public binary_function { friend class multimap; public : bool operator() (const value_type&, const value_type&) const; }; // Construct/Copy/Destroy explicit multimap (const Compare& = Compare(), const Allocator& = Allocator()); template multimap (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); multimap (const multimap&); ~multimap (); multimap& operator= (const multimap&); // Iterators 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; // Capacity bool empty () const; size_type size () const; size_type max_size () const; // Modifiers iterator insert (const value_type&); iterator insert (iterator, const value_type&); template void insert (InputIterator, InputIterator); iterator erase (iterator); size_type erase (const key_type&); iterator erase (iterator, iterator); void swap (multimap&); // Observers key_compare key_comp () const; value_compare value_comp () const; // Multimap operations iterator find (const key_type&); const_iterator find (const key_type&) const; size_type count (const key_type&) const; iterator lower_bound (const key_type&); const_iterator lower_bound (const key_type&) const; iterator upper_bound (const key_type&); const_iterator upper_bound (const key_type&) const; pair equal_range (const key_type&); pair equal_range (const key_type&) const; }; // Non-member Operators template bool operator== (const multimap&, const multimap&); template bool operator!= (const multimap&, const multimap&); template bool operator< (const multimap&, const multimap&); template bool operator> (const multimap&, const multimap&); template bool operator<= (const multimap&, const multimap&); template bool operator>= (const multimap&, const multimap&); // Specialized Algorithms template void swap (multimap&, multimap&; CONSTRUCTORS AND DESTRUCTORS explicit multimap(const Compare& comp = Compare(), const Allocator& alloc = Allocator()); Default constructor. Constructs an empty multimap that will use the optional relation comp to order keys and the allocator alloc for all storage management. template multimap(InputIterator first, InputIterator last, const Compare& comp = Compare() const Allocator& alloc = Allocator()); Constructs a multimap containing values in the range [first,last). Creation of the new multimap is only guaranteed to succeed if the iterators first and last return values of type pair. multimap(const multimap& x); Copy constructor. Creates a new multimap by copying all pairs of key and value from x. ~multimap(); The destructor. Releases any allocated memory for this multimap. ASSIGNMENT OPERATOR multimap& operator=(const multimap& x); Replaces the contents of *this with a copy of the multimap x. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin() ; Returns a bidirectional iterator pointing to the first element stored in the multimap. "First" is defined by the multimap's comparison operator, Compare. const_iterator begin() const; Returns a const_iterator pointing to the first element stored in the multimap. "First" is defined by the multimap's comparison operator,Compare. iterator end() ; Returns a bidirectional iterator pointing to the last element stored in the multimap, i.e. the off-the-end value. const_iterator end() const; Returns a const_iterator pointing to the last element stored in the multimap. reverse_iterator rbegin() ; Returns a reverse_iterator pointing to the first element stored in the multimap. "First" is defined by the multimap's comparison operator, Compare. const_reverse_iterator rbegin() const; Returns a const_reverse_iterator pointing to the first element stored in the multimap. reverse_iterator rend() ; Returns a reverse_iterator pointing to the last element stored in the multimap, i.e., the off-the-end value. const_reverse_iterator rend() const; Returns a const_reverse_iterator pointing to the last element stored in the multimap. MEMBER FUNCTIONS void clear(); Erases all elements from the self. size_type count(const key_type& x) const; Returns the number of elements in the multimap with the key value x. bool empty() const; Returns true if the multimap is empty, false otherwise. pair equal_range(const key_type& x); pair equal_range(const key_type& x) const; Returns the pair (lower_bound(x), upper_bound(x)). iterator erase(iterator first, iterator last); Providing the iterators first and last point to the same multimap and last is reachable from first, all elements in the range (first, last) will be deleted from the multimap. Returns an iterator pointing to the element following the last deleted element, or end(), if there were no elements after the deleted range. iterator erase(iterator position); Deletes the multimap element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end(), if the deleted item was the last one in this list. size_type erase(const key_type& x); Deletes the elements with the key value x from the map, if any exist. Returns the number of deleted elements, or 0 otherwise. iterator find(const key_type& x); Searches the multimap for a pair with the key value x and returns an iterator to that pair if it is found. If such a pair is not found the value end() is returned. const_iterator find(const key_type& x) const; Same as find above but returns a const_iterator. iterator insert(const value_type& x); iterator insert(iterator position, const value_type& x); x is inserted into the multimap. A position may be supplied as a hint regarding where to do the insertion. If the insertion may be done right after position then it takes amortized constant time. Otherwise it will take O(log N) time. template void insert(InputIterator first, InputIterator last); Copies of each element in the range [first, last) will be inserted into the multimap. The iterators first and last must return values of type pair. This operation takes approximately O(N*log(size()+N)) time. key_compare key_comp() const; Returns a function object capable of comparing key values using the comparison operation, Compare, of the current multimap. iterator lower_bound(const key_type& x); Returns an iterator to the first multimap element whose key is greater than or equal to x. If no such element exists then end() is returned. const_iterator lower_bound(const key_type& x) const; Same as lower_bound above but returns a const_iterator. size_type max_size() const; Returns the maximum possible size of the multimap. size_type size() const; Returns the number of elements in the multimap. void swap(multimap& x); Swaps the contents of the multimap x with the current multimap, *this. iterator upper_bound(const key_type& x); Returns an iterator to the first element whose key is less than or equal to x. If no such element exists, then end() is returned. const_iterator upper_bound(const key_type& x) const; Same as upper_bound above but returns a const_iterator. value_compare value_comp() const; Returns a function object capable of comparing value_types (key,value pairs) using the comparison operation, Compare, of the current multimap. NON-MEMBER OPERATORS bool operator==(const multimap& x, const multimap& y); Returns true if all elements in x are element-wise equal to all elements in y, using (T::operator==). Otherwise it returns false. bool operator!=(const multimap& x, const multimap& y); Returns !(x==y). bool operator<(const multimap& x, const multimap& y); Returns true if x is lexicographically less than y. Otherwise, it returns false. bool operator>(const multimap& x, const multimap& y); Returns y < x. bool operator<=(const multimap& x, const multimap& y); Returns !(y < x). bool operator>=(const multimap& x, const multimap& y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(multimap& a, multimap& b); Efficiently swaps the contents of a and b. EXAMPLE // // multimap.cpp // #include #include #include typedef multimap > months_type; // Print out a pair template ostream& operator<<(ostream& out, const pair& p) { cout << p.second << " has " << p.first << " days"; return out; } // Print out a multimap ostream& operator<<(ostream& out, months_type l) { copy(l.begin(),l.end(), ostream_iterator (cout,"0)); return out; } int main(void) { // create a multimap of months and the number of // days in the month months_type months; typedef months_type::value_type value_type; // Put the months in the multimap months.insert(value_type(31, string("January"))); months.insert(value_type(28, string("February"))); months.insert(value_type(31, string("March"))); months.insert(value_type(30, string("April"))); months.insert(value_type(31, string("May"))); months.insert(value_type(30, string("June"))); months.insert(value_type(31, string("July"))); months.insert(value_type(31, string("August"))); months.insert(value_type(30, string("September"))); months.insert(value_type(31, string("October"))); months.insert(value_type(30, string("November"))); months.insert(value_type(31, string("December"))); // print out the months cout << "All months of the year" << endl << months << endl; // Find the Months with 30 days pair p = months.equal_range(30); // print out the 30 day months cout << endl << "Months with 30 days" << endl; copy(p.first,p.second, ostream_iterator(cout,"0)); return 0; } Output : All months of the year February has 28 days April has 30 days June has 30 days September has 30 days November has 30 days January has 31 days March has 31 days May has 31 days July has 31 days August has 31 days October has 31 days December has 31 days Months with 30 days April has 30 days June has 30 days September has 30 days November has 30 days WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for multimap that takes two templated iterators: template multimap (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); multimap also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a multimap in the following two ways: multimap::value_type intarray[10]; multimap first_map(intarry, intarray + 10); multimap second_multimap(first_multimap.begin(), first_multimap.end()); but not this way: multimap long_multimap(first_multimap.begin(),first_multimap.end()); since the long_multimap and first_multimap are not the same type. Also, many compilers do not support default template arguments. If your compiler is one of these you need to always supply the Compare template argument and the Allocator template argument. For instance you'll have to write: multimap, allocator > instead of: multimap SEE ALSO allocator, Containers, Iterators, map STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 multiset Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME multiset - An associative container providing fast access to stored key values. Storage of duplicate keys is allowed. A multiset supports bidirectional iterators. SYNOPSIS #include template , class Allocator = allocator > class multiset; DESCRIPTION multiset provides fast access to stored key values. The default operation for key comparison is the < operator. Insertion of duplicate keys is allowed with a multiset. multiset provides bidirectional iterators which point to a stored key. Any type used for the template parameter Key must provide the following (where T is the type, t is a value of T and u is a const value of T): Copy constructors T(t) and T(u) Destructor t.~T() Address of &t and &u yielding T* and const T* respectively Assignment t = a where a is a (possibly const) value of T The type used for the Compare template parameter must satisfy the requirements for binary functions. INTERFACE template , class Allocator = allocator > class multiset { public: // typedefs typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef Allocator allocator_type; typename reference; typename const_reference; typename iterator; typename const_iterator; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; // Construct/Copy/Destroy explicit multiset (const Compare& = Compare(), const Allocator& = Allocator()); template multiset (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); multiset (const multiset&); ~multiset (); multiset& operator= (const multiset&); // Iterators 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; // Capacity bool empty () const; size_type size () const; size_type max_size () const; // Modifiers iterator insert (const value_type&); iterator insert (iterator, const value_type&); template void insert (InputIterator, InputIterator); iterator erase (iterator); size_type erase (const key_type&); iterator erase (iterator, iterator); void swap (multiset&); void clear (); // Observers key_compare key_comp () const; value_compare value_comp () const; // Multiset operations iterator find (const key_type&) const; size_type count (const key_type&) const; iterator lower_bound (const key_type&) const; iterator upper_bound (const key_type&) const; pair equal_range (const key_type&) const; }; // Non-member Operators template bool operator== (const multiset&, const multiset&); template bool operator!= (const multiset&, const multiset&); template bool operator< (const multiset&, const multiset&); template bool operator> (const multiset&, const multiset&); template bool operator<= (const multiset&, const multiset&); template bool operator>= (const multiset&, const multiset&); // Specialized Algorithms template void swap ( multiset&, multiset&); CONSTRUCTOR AND DESTRUCTOR explicit multiset(const Compare& comp = Compare(), const Allocator& alloc = Allocator()); Default constructor. Constructs an empty multiset which will use the optional relation comp to order keys, if it is supplied, and the allocator alloc for all storage management. template multiset(InputIterator first, InputIterator last, const Compare& = Compare(), const Allocator& = Allocator()); Constructs a multiset containing values in the range [first, last). multiset(const multiset& x); Copy constructor. Creates a new multiset by copying all key values from x. ~multiset(); The destructor. Releases any allocated memory for this multiset. ASSIGNMENT OPERATOR multiset& operator=(const multiset& x); Replaces the contents of *this with a copy of the contents of x. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin(); Returns an iterator pointing to the first element stored in the multiset. "First" is defined by the multiset's comparison operator, Compare. const_iterator begin(); Returns a const_iterator pointing to the first element stored in the multiset. iterator end(); Returns an iterator pointing to the last element stored in the multiset, i.e., the off-the-end value. const_iterator end(); Returns a const_iterator pointing to the last element stored in the multiset, i.e., the off-the-end value. reverse_iterator rbegin(); Returns a reverse_iterator pointing to the first element stored in the multiset. "First" is defined by the multiset's comparison operator, Compare. const_reverse_iterator rbegin(); Returns a const_reverse_iterator pointing to the first element stored in the multiset. reverse_iterator rend(); Returns a reverse_iterator pointing to the last element stored in the multiset, i.e., the off-the-end value. const_reverse_iterator rend(); Returns a const_reverse_iterator pointing to the last element stored in the multiset, i.e., the off-the-end value. MEMBER FUNCTIONS void clear(); Erases all elements from the self. size_type count(const key_type& x) const; Returns the number of elements in the multiset with the key value x. bool empty() const; Returns true if the multiset is empty, false otherwise. pair equal_range(const key_type& x)const; Returns the pair (lower_bound(x), upper_bound(x)). size_type erase(const key_type& x); Deletes all elements with the key value x from the multiset, if any exist. Returns the number of deleted elements. iterator erase(iterator position); Deletes the multiset element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted item was the last one in this list. iterator erase(iterator first, iterator last); Providing the iterators first and last point to the same multiset and last is reachable from first, all elements in the range (first, last) will be deleted from the multiset. Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. iterator find(const key_type& x) const; Searches the multiset for a key value x and returns an iterator to that key if it is found. If such a value is not found the iterator end() is returned. iterator insert(const value_type& x); iterator insert(iterator position, const value_type& x); x is inserted into the multiset. A position may be supplied as a hint regarding where to do the insertion. If the insertion may be done right after position, then it takes amortized constant time. Otherwise, it will take O(log N) time. template void insert(InputIterator first, InputIterator last); Copies of each element in the range [first, last) will be inserted into the multiset. This insert takes approximately O(N*log(size()+N)) time. key_compare key_comp() const; Returns a function object capable of comparing key values using the comparison operation, Compare, of the current multiset. iterator lower_bound(const key_type& x) const; Returns an iterator to the first element whose key is greater than or equal to x. If no such element exists, end() is returned. size_type max_size() const; Returns the maximum possible size of the multiset size_type. size_type size() const; Returns the number of elements in the multiset. void swap(multiset& x); Swaps the contents of the multiset x with the current multiset, *this. iterator upper_bound(const key_type& x) const; Returns an iterator to the first element whose key is smaller than or equal to x. If no such element exists then end() is returned. value_compare value_comp() const; Returns a function object capable of comparing key values using the comparison operation, Compare, of the current multiset. NON-MEMBER OPERATORS template operator==(const multiset& x, const multiset& y); Returns true if all elements in x are element-wise equal to all elements in y, using (T::operator==). Otherwise it returns false. template operator!=(const multiset& x, const multiset& y); Returns !(x==y). template operator<(const multiset& x, const multiset& y); Returns true if x is lexicographically less than y. Otherwise, it returns false. template operator>(const multiset& x, const multiset& y); Returns y < x. template operator<=(const multiset& x, const multiset& y); Returns !(y < x). template operator>=(const multiset& x, const multiset& y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(multiset& a, multiset&b); Efficiently swaps the contents of a and b. EXAMPLE // // multiset.cpp // #include #include typedef multiset, allocator> set_type; ostream& operator<<(ostream& out, const set_type& s) { copy(s.begin(),s.end(), ostream_iterator(cout," ")); return out; } int main(void) { // create a multiset of ints set_type si; int i; for (int j = 0; j < 2; j++) { for(i = 0; i < 10; ++i) { // insert values with a hint si.insert(si.begin(), i); } } // print out the multiset cout << si << endl; // Make another int multiset and an empty multiset set_type si2, siResult; for (i = 0; i < 10; i++) si2.insert(i+5); cout << si2 << endl; // Try a couple of set algorithms set_union(si.begin(),si.end(),si2.begin(),si2.end(), inserter(siResult,siResult.begin())); cout << "Union:" << endl << siResult << endl; siResult.erase(siResult.begin(),siResult.end()); set_intersection(si.begin(),si.end(), si2.begin(),si2.end(), inserter(siResult,siResult.begin())); cout << "Intersection:" << endl << siResult << endl; return 0; } Output: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 5 6 7 8 9 10 11 12 13 14 Union: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 13 14 Intersection: 5 6 7 8 9 WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for multiset, which takes two templated iterators: template multiset (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); multiset also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature, we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on). You can also use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates, you can construct a multiset in the following two ways: int intarray[10]; multiset first_multiset(intarray, intarray +10); multiset second_multiset(first_multiset.begin(), first_multiset.end()); but not this way: multiset long_multiset(first_multiset.begin(),first_multiset.end()); since the long_multiset and first_multiset are not the same type. Also, many compilers do not support default template arguments. If your compiler is one of these you need to always supply the Compare template argument and the Allocator template argument. For instance, you'll have to write: multiset, allocator > instead of: multiset SEE ALSO allocator, Containers, Iterators, set STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 priority_queue Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME priority_queue - A container adapter which behaves like a priority queue. Items are popped from the queue are in order with respect to a "priority." SYNOPSIS #include template , class Compare = less > class priority_queue; DESCRIPTION priority_queue is a container adaptor which allows a container to act as a priority queue. This means that the item with the highest priority, as determined by either the default comparison operator (operator <) or the comparison Compare, is brought to the front of the queue whenever anything is pushed onto or popped off the queue. priority_queue adapts any container that provides front(), push_back() and pop_back(). In particular, deque and vector can be used. INTERFACE template , class Compare = less > class priority_queue { public: // typedefs typedef typename Container::value_type value_type; typedef typename Container::size_type size_type; typedef typename allocator_type allocator_type; // Construct explicit priority_queue (const Compare& = Compare(), const allocator_type&=allocator_type()); template priority_queue (InputIterator first, InputIterator last, const Compare& = Compare(), const allocator_type& = allocator_type()); allocator_type get_allocator() const; bool empty () const; size_type size () const; const value_type& top () const; void push (const value_type&); void pop(); }; CONSTRUCTORS explicit priority_queue (const Compare& x = Compare(), const allocator_type& alloc = allocator_type()); Default constructor. Constructs a priority queue that uses Container for its underlying implementation, x as its standard for determining priority, and the allocator alloc for all storage management. template priority_queue (InputIterator first, InputIterator last, const Compare& x = Compare(), const allocator_type& alloc = allocator_type()); Constructs a new priority queue and places into it every entity in the range [first, last). The priority_queue will use x for determining the priority, and the allocator alloc for all storage management. ALLOCATOR allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS bool empty () const; Returns true if the priority_queue is empty, false otherwise. void pop(); Removes the item with the highest priority from the queue. void push (const value_type& x); Adds x to the queue. size_type size () const; Returns the number of elements in the priority_queue. const value_type& top () const; Returns a constant reference to the element in the queue with the highest priority. EXAMPLE // // p_queue.cpp // #include #include #include #include #include int main(void) { // Make a priority queue of int using a vector container priority_queue, less > pq; // Push a couple of values pq.push(1); pq.push(2); // Pop a couple of values and examine the ends cout << pq.top() << endl; pq.pop(); cout << pq.top() << endl; pq.pop(); // Make a priority queue of strings using a deque container priority_queue, less > pqs; // Push on a few strings then pop them back off int i; for (i = 0; i < 10; i++) { pqs.push(string(i+1,'a')); cout << pqs.top() << endl; } for (i = 0; i < 10; i++) { cout << pqs.top() << endl; pqs.pop(); } // Make a priority queue of strings using a deque // container, and greater as the compare operation priority_queue, greater > pgqs; // Push on a few strings then pop them back off for (i = 0; i < 10; i++) { pgqs.push(string(i+1,'a')); cout << pgqs.top() << endl; } for (i = 0; i < 10; i++) { cout << pgqs.top() << endl; pgqs.pop(); } return 0; } Output : 2 1 a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa aaaaaaaaa aaaaaaaa aaaaaaa aaaaaa aaaaa aaaa aaa aa a a a a a a a a a a a a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa WARNING If your compiler does not support default template parameters, you must always provide a Container template parameter, and a Compare template parameter when declaring an instance of priority_queue. For example, you would not be able to write, priority_queue var; Instead, you would have to write, priority_queue, less::value_type> > var; SEE ALSO Containers, queue STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 queue Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME queue - A container adaptor that behaves like a queue (first in, first out). This page describes ANSI queue class. If you would like information on the HP C++ task queue class, use the command: help cxxl SYNOPSIS #include template > class queue ; DESCRIPTION The queue container adaptor lets a container function as a queue. In a queue, items are pushed into the back of the container and removed from the front. The first items pushed into the queue are the first items to be popped off of the queue (first in, first out, or "FIFO"). queue can adapt any container that supports the front(), back(), push_back() and pop_front() operations. In particular, deque and list can be used. INTERFACE template > class queue { public: // typedefs typedef typename Container::value_type value_type; typedef typename Container::size_type size_type; typedef typename Container::allocator_type allocator_type; // Construct/Copy/Destroy explicit queue (const allocator_type& = allocator_type()); allocator_type get_allocator () const; // Accessors bool empty () const; size_type size () const; value_type& front (); const value_type& front () const; value_type& back (); const value_type& back () const; void push (const value_type&); void pop (); }; // Non-member Operators template bool operator== (const queue&, const queue&); template bool operator!= (const queue&, const queue&); template bool operator< (const queue&, const queue&); template bool operator> (const queue&, const queue&); template bool operator<= (const queue&, const queue&); template bool operator>= (const queue&, const queue&); CONSTRUCTORS explicit queue (const allocator_type& alloc= allocator_type()); Creates a queue of zero elements. The queue will use the allocator alloc for all storage management. ALLOCATOR allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS value_type& back (); Returns a reference to the item at the back of the queue (the last item pushed into the queue). const value_type& back() const; Returns a constant reference to the item at the back of the queue as a const_value_type. bool empty () const; Returns true if the queue is empty, otherwise false. value_type& front (); Returns a reference to the item at the front of the queue. This will be the first item pushed onto the queue unless pop() has been called since then. const value_type& front () const; Returns a constant reference to the item at the front of the queue as a const_value_type. void pop (); Removes the item at the front of the queue. void push (const value_type& x); Pushes x onto the back of the queue. size_type size () const; Returns the number of elements on the queue. NON-MEMBER OPERATORS template bool operator== (const queue& x, const queue& y); Equality operator. Returns true if x is the same as y. template bool operator!= (const queue& x, const queue& y); Inequality operator. Returns !(x==y). template bool operator< (const queue& x, const queue& y); Returns true if the queue defined by the elements contained in x is lexicographically less than the queue defined by the elements contained in y. template bool operator> (const queue& x, const queue& y); Returns y < x. template bool operator< (const queue& x, const queue& y); Returns !(y < x). template bool operator< (const queue& x, const queue& y); Returns !(x < y). EXAMPLE // // queue.cpp // #include #include #include #include #include int main(void) { // Make a queue using a list container queue> q; // Push a couple of values on then pop them off q.push(1); q.push(2); cout << q.front() << endl; q.pop(); cout << q.front() << endl; q.pop(); // Make a queue of strings using a deque container queue> qs; // Push on a few strings then pop them back off int i; for (i = 0; i < 10; i++) { qs.push(string(i+1,'a')); cout << qs.front() << endl; } for (i = 0; i < 10; i++) { cout << qs.front() << endl; qs.pop(); } return 0; } Output : 1 2 a a a a a a a a a a a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa WARNINGS If your compiler does not support default template parameters, you must always provide a Container template parameter. For example you would not be able to write: queue var; rather, you would have to write, queue > var; SEE ALSO allocator, Containers, priority_queue STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 set Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME set - An associative container that supports unique keys. A set supports bidirectional iterators. SYNOPSIS #include template , class Allocator = allocator > class set ; DESCRIPTION set is an associative container that supports unique keys and provides for fast retrieval of the keys. A set contains at most one of any key value. The keys are sorted using Compare. Since a set maintains a total order on its elements, you cannot alter the key values directly. Instead, you must insert new elements with an insert_iterator. Any type used for the template parameter Key must provide the following (where T is the type, t is a value of T and u is a const value of T): Copy constructors T(t) and T(u) Destructor t.~T() Address of &t and &u yielding T* and const T* respectively Assignment t = a where a is a (possibly const) value of T The type used for the Compare template parameter must satisfy the requirements for binary functions. INTERFACE template , class Allocator = allocator > class set { public: // types typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef Allocator allocator_type; typename reference; typename const_reference; typename iterator; typename const_iterator; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; // Construct/Copy/Destroy explicit set (const Compare& = Compare(), const Allocator& = Allocator ()); template set (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator ()); set (const set&); ~set (); set& operator= (const set &); allocator_type get_allocator () const; // Iterators 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; // Capacity bool empty () const; size_type size () const; size_type max_size () const; // Modifiers pair insert (const value_type&); iterator insert (iterator, const value_type&); template void insert (InputIterator, InputIterator); iterator erase (iterator); size_type erase (const key_type&); iterator erase (iterator, iterator); void swap (set&); void clear (); // Observers key_compare key_comp () const; value_compare value_comp () const; // Set operations size_type count (const key_type&) const; pair equal_range (const key_type&) const; iterator find (const key_type&) const; iterator lower_bound (const key_type&) const; iterator upper_bound (const key_type&) const }; // Non-member Operators template bool operator== (const set&, const set&); template bool operator!= (const set&, const set&); template bool operator< (const set&, const set&); template bool operator> (const set&, const set&); template bool operator<= (const set&, const set&); template bool operator>= (const set&, const set&); // Specialized Algorithms template void swap (set &, set &); CONSTRUCTORS AND DESTRUCTORS explicit set(const Compare& comp = Compare(), const Allocator& alloc = Allocator()); The default constructor. Creates a set of zero elements. If the function object comp is supplied, it is used to compare elements of the set. Otherwise, the default function object in the template argument is used. The template argument defaults to less (<). The allocator alloc is used for all storage management. template set(InputIterator first, InputIterator last, const Compare& comp = Compare() const Allocator& alloc = Allocator()); Creates a set of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). If the function object comp is supplied, it is used to compare elements of the set. Otherwise, the default function object in the template argument is used. The template argument defaults to less (<). Uses the allocator alloc for all storage management. set(const set& x); Copy constructor. Creates a copy of x. ~set(); The destructor. Releases any allocated memory for self. ASSIGNMENT OPERATOR set& operator=(const set& x); Assignment operator. Self will share an implementation with x. Returns a reference to self. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. ITERATORS iterator begin(); Returns an iterator that points to the first element in self. const_iterator begin() const; Returns a const_iterator that points to the first element in self. iterator end(); Returns an iterator that points to the past-the-end value. const_iterator end() const; Returns a const_iterator that points to the past-the-end value. reverse_iterator rbegin(); Returns a reverse_iterator that points to the past-the-end value. const_reverse_iterator rbegin() const; Returns a const_reverse_iterator that points to the past-the-end value. reverse_iterator rend(); Returns a reverse_iterator that points to the first element. const_reverse_iterator rend() const; Returns a const_reverse_iterator that points to the first element. MEMBER FUNCTIONS void clear(); Erases all elements from the set. size_type count(const key_type& x) const; Returns the number of elements equal to x. Since a set supports unique keys, count will always return 1 or 0. bool empty() const; Returns true if the size is zero. pair equal_range(const key_type& x) const; Returns pair(lower_bound(x),upper_bound(x)). The equal_range function indicates the valid range for insertion of x into the set. size_type erase(const key_type& x); Deletes all the elements matching x. Returns the number of elements erased. Since a set supports unique keys, erase will always return 1 or 0. iterator erase(iterator position); Deletes the map element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted item was the last one in this list. iterator erase(iterator first, iterator last); Deletes the elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. iterator find(const key_value& x) const; Returns an iterator that points to the element equal to x. If there is no such element, the iterator points to the past-the-end value. pair insert(const value_type& x); Inserts x into self according to the comparison function object. The template's default comparison function object is less (<). If the insertion succeeds, it returns a pair composed of the iterator position where the insertion took place, and true. Otherwise, the pair contains the end value, and false. iterator insert(iterator position, const value_type& x); x is inserted into the set. A position may be supplied as a hint regarding where to do the insertion. If the insertion may be done right after position then it takes amortized constant time. Otherwise it will take 0 (log N) time. The return value points to the inserted x. template void insert(InputIterator first, InputIterator last); Inserts copies of the elements in the range [first, last]. key_compare key_comp() const; Returns the comparison function object for the set. iterator lower_bound(const key_type& x) const; Returns an iterator that points to the first element that is greater than or equal to x. If there is no such element, the iterator points to the past-the-end value. size_type max_size() const; Returns size of the largest possible set. size_type size() const; Returns the number of elements. void swap(set& x); Exchanges self with x. iterator upper_bound(const key_type& x) const Returns an iterator that points to the first element that is greater than or equal to x. If there is no such element, the iterator points to the past-the-end value. value_compare value_comp() const; Returns the set's comparison object. This is identical to the function key_comp(). NON-MEMBER OPERATORS template bool operator==(const set& x, const set& y); Equality operator. Returns true if x is the same as y. template bool operator!=(const set& x, const set& y); Inequality operator. Returns !(x==y). template bool operator<(const set & x, const set & y); Returns true if the elements contained in x are lexico- graphically less than the elements contained in y. template bool operator>(const set & x, const set & y); Returns y < x. template bool operator<=(const set & x, const set & y); Returns !(y < x). template bool operator>=(const set & x, const set & y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(set & a, set & b); Efficiently swaps the contents of a and b. EXAMPLE // // set.cpp // #include #include typedef set, allocator > set_type; ostream& operator<<(ostream& out, const set_type& s) { copy(s.begin(), s.end(), ostream_iterator(cout," ")); return out; } int main(void) { // create a set of doubles set_type sd; int i; for(i = 0; i < 10; ++i) { // insert values sd.insert(i); } // print out the set cout << sd << endl << endl; // now let's erase half of the elements in the set int half = sd.size() >> 1; set_type::iterator sdi = sd.begin(); advance(sdi,half); sd.erase(sd.begin(),sdi); // print it out again cout << sd << endl << endl; // Make another set and an empty result set set_type sd2, sdResult; for (i = 1; i < 9; i++) sd2.insert(i+5); cout << sd2 << endl; // Try a couple of set algorithms set_union(sd.begin(),sd.end(),sd2.begin(),sd2.end(), inserter(sdResult,sdResult.begin())); cout << "Union:" << endl << sdResult << endl; sdResult.erase(sdResult.begin(),sdResult.end()); set_intersection(sd.begin(),sd.end(), sd2.begin(),sd2.end(), inserter(sdResult,sdResult.begin())); cout << "Intersection:" << endl << sdResult << endl; return 0; } Output : 0 1 2 3 4 5 6 7 8 9 5 6 7 8 9 6 7 8 9 10 11 12 13 Union: 5 6 7 8 9 10 11 12 13 Intersection: 6 7 8 9 WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for set that takes two templated iterators: template set (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); set also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature, we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a set in the following two ways: int intarray[10]; set first_set(intarray, intarray + 10); set second_set(first_set.begin(), first_set.end()); but not this way: set long_set(first_set.begin(), first_set.end()); since the long_set and first_set are not the same type. Also, many compilers do not support default template arguments. If your compiler is one of these you need to always supply the Compare template argument, and the Allocator template argument. For instance, you need to write : set, allocator > instead of : set SEE ALSO allocator, bidirectional_iterator, Cont ainer, lexicographical_compare STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Sequences Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Sequences - A sequence is a container that organizes a set of objects, all the same type, into a linear arrangement. vector, list, deque, and string fall into this category. Sequences offer different complexity trade-offs. vector offers fast inserts and deletes from the end of the container. deque is useful when insertions and deletions will take place at the beginning or end of the sequence. Use list when there are frequent insertions and deletions from the middle of the sequence. SEE ALSO For more information about sequences and their requirements, see the Containers section of this reference guide, or see the section on the specific container. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 stack Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME stack - A container adapter which behaves like a stack (last in, first out). SYNOPSIS #include template > class stack ; DESCRIPTION The stack container adapter causes a container to behave like a "last in, first out" (LIFO) stack. The last item that was put ("pushed") onto the stack is the first item removed ("popped" off). The stack can adapt to any container that provides the operations, back(), push_back(), and pop_back(). In particular, deque , list , and vector can be used. INTERFACE template > class stack { public: // typedefs typedef typename Container::value_type value_type; typedef typename Container::size_type size_type; typedef typename Container::allocator_type allocator_type // Construct explicit stack (const allocator_type& = allocator_type()); allocator_type get_allocator () const; // Accessors bool empty () const; size_type size () const; value_type& top (); const value_type& top () const; void push (const value_type&); void pop (); }; // Non-member Operators template bool operator== (const stack&, const stack&); template bool operator!= (const stack&, const stack&); template bool operator< (const stack&, const stack&); template bool operator> (const stack&, const stack&); template bool operator<= (const stack&, const stack&); template bool operator>= (const stack&, const stack&); CONSTRUCTOR explicit stack(const allocator_type& alloc = allocator_taype()); Constructs an empty stack. The stack will use the allocator alloc for all storage management. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS bool empty() const; Returns true if the stack is empty, otherwise false. void pop(); Removes the item at the top of the stack. void push(const value_type& x); Pushes x onto the stack. size_type size() const; Returns the number of elements on the stack. value_type& top(); Returns a reference to the item at the top of the stack. This will be the last item pushed onto the stack unless pop() has been called since then. const value_type& top() const; Returns a constant reference to the item at the top of the stack as a const value_type. NON-MEMBER OPERATORS template bool operator==(const stack& x, const stack& y); Equality operator. Returns true if x is the same as y. template bool operator!=(const stack& x, const stack& y); Inequality operator. Returns !(x==y). template bool operator<(const stack& x, const stack& y); Returns true if the stack defined by the elements contained in x is lexicographically less than the stack defined by the elements of y. template bool operator>(const stack& x, const stack& y); Returns y < x. template bool operator<=(const stack& x, const stack& y); Returns !(y < x). template bool operator>=(const stack& x, const stack& y); Returns !(x < y). EXAMPLE // // stack.cpp // #include #include #include #include #include int main(void) { // Make a stack using a vector container stack > s; // Push a couple of values on the stack s.push(1); s.push(2); cout << s.top() << endl; // Now pop them off s.pop(); cout << s.top() << endl; s.pop(); // Make a stack of strings using a deque stack > ss; // Push a bunch of strings on then pop them off int i; for (i = 0; i < 10; i++) { ss.push(string(i+1,'a')); cout << ss.top() << endl; } for (i = 0; i < 10; i++) { cout << ss.top() << endl; ss.pop(); } return 0; } Output : 2 1 a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaa aaaaaaaa aaaaaaa aaaaaa aaaaa aaaa aaa aa a WARNINGS If your compiler does not support template parameter defaults, you are required to supply a template parameter for Container. For example: You would not be able to write, stack var; Instead, you would have to write, stack > var; SEE ALSO allocator, Containers, deque, list, vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 vector Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME vector - Sequence that supports random access iterators. This page describes the ANSI vector class. If you would like information on the pre-ANSI vector class, use the command: help cxxl SYNOPSIS #include template > class vector ; DESCRIPTION vector is a type of sequence that supports random access iterators. In addition, it supports amortized constant time insert and erase operations at the end. Insert and erase in the middle take linear time. Storage management is handled automatically. In vector, iterator is a random access iterator referring to T. const_iterator is a constant random access iterator that returns a const T& when being dereferenced. A constructor for iterator and const_iterator is guaranteed. size_type is an unsigned integral type. difference_type is a signed integral type. Any type used for the template parameter T must provide the following (where T is the type, t is a value of T and u is a const value of T): Default constructor T() Copy constructors T(t) and T(u) Destructor t.~T() Address of &t and &u yielding T* and const T* respectively Assignment t = a where a is a (possibly const) value of T SPECIAL CASE Vectors of bit values (boolean 1/0 values) are handled as a special case by the standard library, so that they can be efficiently packed several elements to a word. The operations for a boolean vector, vector, are a superset of those for an ordinary vector, only the implementation is more efficient. Two member functions are available to the boolean vector data type. One is flip(), which inverts all the bits of the vector. Boolean vectors also return as reference an internal value that also supports the flip() member function. The other vector-specific member function is a second form of the swap() function INTERFACE template > class vector { public: // Types typedef T value_type; typedef Allocator allocator_type; typename reference; typename const_reference; typename iterator; typename const_iterator; typename size_type; typename difference_type; typename reverse_iterator; typename const_reverse_iterator; // Construct/Copy/Destroy explicit vector (const Allocator& = Allocator()); explicit vector (size_type, const Allocator& = Allocator ()); vector (size_type, const T&, const Allocator& = Allocator()); vector (const vector&); template vector (InputIterator, InputIterator, const Allocator& = Allocator ()); ~vector (); vector& operator= (const vector&); template void assign (InputIterator first, InputIterator last); template void assign (Size n); template void assign (Size n, const TT&); allocator_type get_allocator () const; // Iterators 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; // Capacity size_type size () const; size_type max_size () const; void resize (size_type); void resize (size_type, T); size_type capacity () const; bool empty () const; void reserve (size_type); // Element Access reference operator[] (size_type); const_reference operator[] (size_type) const; reference at (size_type); const_reference at (size_type) const; reference front (); const_reference front () const; reference back (); const_reference back () const; // Modifiers void push_back (const T&); void pop_back (); iterator insert (iterator); iterator insert (iterator, const T&); void insert (iterator, size_type, const T&); template void insert (iterator, InputIterator, InputIterator); iterator erase (iterator); iterator erase (iterator, iterator); void swap (vector&); }; // Non-member Operators template bool operator== (const vector&, const vector &); template bool operator!= (const vector&, const vector &); template bool operator< (const vector&, const vector&); template bool operator> (const vector&, const vector&); template bool operator<= (const vector&, const vector&); template bool operator>= (const vector&, const vector&); // Specialized Algorithms template void swap (const vector&, const vector&); CONSTRUCTORS AND DESTRUCTORS explicit vector(const Allocator& alloc = Allocator()); The default constructor. Creates a vector of length zero. The vector will use the allocator alloc for all storage management. explicit vector(size_type n, const Allocator& alloc = Allocator()); Creates a vector of length n, containing n copies of the default value for type T. Requires that T have a default constructor. The vector will use the allocator alloc for all storage management. vector(size_type n, const T& value, const Allocator& alloc = Allocator()); Creates a vector of length n, containing n copies of value. The vector will use the allocator alloc for all storage management. vector(const vector& x); Creates a copy of x. template vector(InputIterator first, InputIterator last, const Allocator& alloc = Allocator()); Creates a vector of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). The vector will use the allocator alloc for all storage management. ~vector(); The destructor. Releases any allocated memory for this vector. ITERATORS iterator begin(); Returns a random access iterator that points to the first element. const_iterator begin() const; Returns a random access const_iterator that points to the first element. iterator end(); Returns a random access iterator that points to the past-the-end value. const_iterator end() const; Returns a random access const_iterator that points to the past-the-end value. reverse_iterator rbegin(); Returns a random access reverse_iterator that points to the past-the-end value. const_reverse_iterator rbegin() const; Returns a random access const_reverse_iterator that points to the past-the-end value. reverse_iterator rend(); Returns a random access reverse_iterator that points to the first element. const_reverse_iterator rend() const; Returns a random access const_reverse_iterator that points to the first element. ASSIGNMENT OPERATOR vector& operator=(const vector& x); Erases all elements in self then inserts into self a copy of each element in x. Returns a reference to self. ALLOCATOR allocator_type get_allocator() const; Returns a copy of the allocator used by self for storage management. REFERENCE OPERATORS reference operator[](size_type n); a reference to element n of self. The result can be used as an lvalue. The index n must be between 0 and the size less one. const_reference operator[](size_type n) const; Returns a constant reference to element n of self. The index n must be between 0 and the size less one. MEMBER FUNCTIONS template void assign(InputIterator first, InputIterator last); Erases all elements contained in self, then inserts new elements from the range [first, last). template void assign(Size n, const T& t); Erases all elements contained in self, then inserts n instances of the default value of type T. template void assign(Size n, const T& t); Erases all elements contained in self, then inserts n instances of the value of t. reference at(size_type n); Returns a reference to element n of self. The result can be used as an lvalue. The index n must be between 0 and the size less one. const_reference at(size_type) const; Returns a constant reference to element n of self. The index n must be between 0 and the size less one. reference back(); Returns a reference to the last element. const_reference back() const; Returns a constant reference to the last element. size_type capacity() const; Returns the size of the allocated storage, as the number of elements that can be stored. void clear() ; Deletes all elements from the vector. bool empty() const; Returns true if the size is zero. iterator erase(iterator position); Deletes the vector element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted element was the last one in this vector. iterator erase(iterator first, iterator last); Deletes the vector elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements in the deleted range. void flip(); Flips all the bits in the vector. This member function is only defined for vector. reference front(); Returns a reference to the first element. const_reference front() const; Returns a constant reference to the first element. iterator insert(iterator position); Inserts x before position. The return value points to the inserted x. iterator insert(iterator position, const T& x); Inserts x before position. The return value points to the inserted x. void insert(iterator position, size_type n, const T& x); Inserts n copies of x before position. template void insert(iterator position, InputIterator first, InputIterator last); Inserts copies of the elements in the range [first, last] before position. size_type max_size() const; Returns size() of the largest possible vector. void pop_back(); Removes the last element of self. void push_back(const T& x); Inserts a copy of x to the end of self. void reserve(size_type n); Increases the capacity of self in anticipation of adding new elements. reserve itself does not add any new elements. After a call to reserve, capacity() is greater than or equal to n and subsequent insertions will not cause a reallocation until the size of the vector exceeds n. Real location does not occur if n is less than capacity(). If reallocation does occur, then all iterators and references pointing to elements in the vector are invalidated. reserve takes at most linear time in the size of self. void resize(size_type sz); Alters the size of self. If the new size (sz) is greater than the current size, then sz-size() instances of the default value of type T are inserted at the end of the vector. If the new size is smaller than the current capacity, then the vector is truncated by erasing size()-sz elements off the end. If sz is equal to capacity then no action is taken. void resize(size_type sz, T c); Alters the size of self. If the new size (sz) is greater than the current size, then sz-size() c's are inserted at the end of the vector. If the new size is smaller than the current capacity, then the vector is truncated by erasing size()-sz elements off the end. If sz is equal to capacity then no action is taken. size_type size() const; Returns the number of elements. void swap(vector& x); Exchanges self with x, by swapping all elements. void swap(reference x, reference y); Swaps the values of x and y. This is a member function of vector only. NON-MEMBER OPERATORS template bool operator==(const vector& x, const vector& y); Returns true if x is the same as y. template bool operator!=(const vector& x, const vector& y); Returns !(x==y). template bool operator<(const vector& x, const vector& y); Returns true if the elements contained in x are lexico- graphically less than the elements contained in y. template bool operator>(const vector& x, const vector& y); Returns y < x. template bool operator<=(const vector& x, const vector& y); Returns !(y < x). template bool operator>=(const vector& x, const vector& y); Returns !(x < y). SPECIALIZED ALGORITHMS template void swap(vector & a, vector & b); Efficiently swaps the contents of a and b. EXAMPLE // // vector.cpp // #include #include ostream& operator<< (ostream& out, const vector& v) { copy(v.begin(), v.end(), ostream_iterator(out," ")); return out; } int main(void) { // create a vector of doubles vector vi; int i; for(i = 0; i < 10; ++i) { // insert values before the beginning vi.insert(vi.begin(), i); } // print out the vector cout << vi << endl; // now let's erase half of the elements int half = vi.size() >> 1; for(i = 0; i < half; ++i) { vi.erase(vi.begin()); } // print ir out again cout << vi << endl; return 0; } Output : 9 8 7 6 5 4 3 2 1 0 4 3 2 1 0 WARNINGS Member function templates are used in all containers provided by the Standard C++ Library. An example of this feature is the constructor for vector that takes two templated iterators: template vector (InputIterator, InputIterator, const Allocator = Allocator()); vector also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments. For compilers that do not support this feature we provide substitute functions that allow you to use an iterator obtained from the same type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a vector in the following two ways: int intarray[10]; vector first_vector(intarray, intarray + 10); vector second_vector(first_vector.begin(), first_vector.end()); but not this way: vector long_vector(first_vector.begin(),first_vector.end()); since the long_vector and first_vector are not the same type. Additionally, if your compiler does not support default template parameters, you will need to supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO allocator, Containers, Iterators, lexicographical_compare STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Algorithms Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Algorithms - Generic algorithms for performing various operations on containers and sequences. SYNOPSIS #include The synopsis of each algorithm appears in its entry in the reference guide. DESCRIPTION The Standard C++ Library provides a very flexible framework for applying generic algorithms to containers. The library also provides a rich set of these algorithms for searching, sorting, merging, transforming, scanning, and much more. Each algorithm can be applied to a variety of containers, including those defined by a user of the library. The following design features make algorithms generic: + Generic algorithms access the collection through iterators + Algorithms are templatized on iterator types + Each algorithm is designed to require the least number of services from the iterators it uses In addition to requiring certain iterator capabilities, algorithms may require a container to be in a specific state. For example, some algorithms can only work on previously sorted containers. Because most algorithms rely on iterators to gain access to data, they can be grouped according to the type of iterator they require, as is done in the Algorithms by Iterator section below. They can also be grouped according to the type of operation they perform. ALGORITHMS BY MUTATING/NON-MUTATING FUNCTION The broadest categorization groups algorithms into two main types: mutating and non-mutating. Algorithms that alter (or mutate) the contents of a container fall into the mutating group. All others are considered non-mutating. For example, both fill and sort are mutating algorithms, while find and for_each are non-mutating. Non-mutating operations accumulate find_end max element adjacent_find find_first_of min binary_search find_if min_element count_min for_each mismatch count_if includes nth_element equal lexicographical_compare search equal_range lower_bound search_n find max Mutating operations copy remove_if copy_backward replace fill replace_copy fill_n replace_copy_if generate replace_if generate_n reverse inplace_merge reverse_copy iter_swap rotate make_heap rotate_copy merge set_difference nth_element set_symmetric_difference next_permutation set_intersection partial_sort set_union partial_sort_copy sort partition sort_heap prev_permutation stable_partition push_heap stable_sort pop_heap swap random_shuffle swap_ranges remove transform remove_copy unique remove_copy_if unique_copy Note that the library provides both in place and copy versions of many algorithms, such as replace and replace_copy. The library also provides versions of algorithms that allow the use of default comparators and comparators supplied by the user. Often these functions are overloaded, but in some cases (where overloading proved impractical or impossible) the names differ (e.g., replace, which will use equality to determine replacement, and replace_if, which accesses a user provided compare function). ALGORITHMS BY OPERATION We can further distinguish algorithms by the kind of operations they perform. The following lists all algorithms by loosely grouping them into similar operations. Initializing operations fill generate fill_n generate_n Search operations adjacent_find find_end search_n count find_if count_if find_first_of find search Binary search operations (Elements must be sorted) binary_search lower_bound equal_range upper_bound Compare operations equal mismatch lexicographical_compare Copy operations copy copy_backward Transforming operations partition reverse random_shuffle reverse_copy replace rotate replace_copy rotate_copy replace_copy_if stable_partition replace_if transform Swap operations swap swap_ranges Scanning operations accumulate for_each Remove operations remove remove_if remove_copy unique remove_copy_if unique_copy Sorting operations nth_element sort partial_sort stable_sort partial_sort_copy Merge operations (Elements must be sorted) inplace_merge merge Set operations (Elements must be sorted) includes set_symmetric_difference set_difference set_union set_intersection Heap operations make_heap push_heap pop_heap sort_heap Minimum and maximum max min max_element min_element Permutation generators next_permutation prev_permutation ALGORITHMS BY CATEGORY Each algorithm requires certain kinds of iterators (for a description of the iterators and their capabilities see the Iterator entry in this manual). The following set of lists groups the algorithms according to the types of iterators they require. Algorithms that use no iterators: max min swap Algorithms that require only input iterators: accumulate find mismatch count find_if count_if includes equal inner_product for_each lexicographical_compare Algorithms that require only output iterators: fill_n generate_n Algorithms that read from input iterators and write to output iterators: adjacent_difference replace_copy transform copy replace_copy_if unique_copy merge set_difference partial_sum set_intersedtion remove_copy set_symmetric_difference remove_copy_if set_union Algorithms that require forward iterators: adjacent_find iter_swap replace_if binary_search lower_bound rotate equal_range max_element search fill min_element search_n find_end remove swap_ranges find_first_of remove_if unique generate replace upper_bound Algorithms that read from forward iterators and write to output iterators: rotate_copy Algorithms that require bidirectional iterators copy_backward partition inplace_merge prev_permutation next_permutation reverse stable_permutation Algorithms that read from bidirectional iterators and write to output iterators: reverse_copy Algorithms that require random access iterators: make_heap pop_heap sort nth_element push_heap sort_heap partial_sort random_shuffle stable_sort Algorithms that read from input iterators and write to random access iterators: partial_sort_copy COMPLEXITY The complexity for each of these algorithms is given in the manual page for that algorithm. SEE ALSO Manual pages for each of the algorithms named in the lists above. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 accumulate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME accumulate - Accumulate all elements within a range into a single value. SYNOPSIS #include template T accumulate (InputIterator first, InputIterator last, T init); template T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); DESCRIPTION accumulate applies a binary operation to init and each value in the range [first,last). The result of each operation is returned in init. This process aggregates the result of performing the operation on every element of the sequence into a single value. Accumulation is done by initializing the accumulator acc with the initial value init and then modifying it with acc = acc + *i or acc = binary_op(acc, *i) for every iterator i in the range [first, last) in order. If the sequence is empty, accumulate returns init. COMPLEXITY accumulate performs exactly last-first applications of the binary operation (operator+ by default). EXAMPLE // // accum.cpp // #include //for accumulate #include //for vector #include //for times #include int main() { // //Typedef for vector iterators // typedef vector::iterator iterator; // //Initialize a vector using an array of ints // int d1[10] = {1,2,3,4,5,6,7,8,9,10}; vector v1(d1, d1+10); // //Accumulate sums and products // int sum = accumulate(v1.begin(), v1.end(), 0); int prod = accumulate(v1.begin(), v1.end(), 1, times()); // //Output the results // cout << "For the series: "; for(iterator i = v1.begin(); i != v1.end(); i++) cout << *i << " "; cout << " where N = 10." << endl; cout << "The sum = (N*N + N)/2 = " << sum << endl; cout << "The product = N! = " << prod << endl; return 0; } Output : For the series: 1 2 3 4 5 6 7 8 9 10 where N = 10. The sum = (N*N + N)/2 = 55 The product = N! = 3628800 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 adjacent_difference Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME adjacent_difference - Outputs a sequence of the differences between each adjacent pair of elements in a range. SYNOPSIS #include template OutputIterator adjacent_difference (InputIterator first, InputIterator last, OutputIterator result); template OutputIterator adjacent_difference (InputIterator first, InputIterator last, OutputIterator result, BinaryOperation bin_op); DESCRIPTION Informally, adjacent_difference fills a sequence with the differences between successive elements in a container. The result is a sequence in which the first element is equal to the first element of the sequence being processed, and the remaining elements are equal to the calculated differences between adjacent elements. For instance, applying adjacent_difference to {1,2,3,5} will produce a result of {1,1,1,2}. By default, subtraction is used to compute the difference, but you can supply any binary operator. The binary operator is then applied to adjacent elements. For example, by supplying the plus (+) operator, the result of applying adjacent_difference to {1,2,3,5} is the sequence {1,3,5,8}. Formally, adjacent_difference assigns to every element referred to by iterator i in the range [result + 1, result + (last - first)) a value equal to the appropriate one of the following: *(first + (i - result)) - *(first + (i - result) - 1) or binary_op (*(first + (i - result)), *(first + (i - result) - 1)) result is assigned the value of *first. adjacent_difference returns result + (last - first). result can be equal to first. This allows you to place the results of applying adjacent_difference into the original sequence. COMPLEXITY This algorithm performs exactly (last-first) - 1 applications of the default operation (-) or binary_op. EXAMPLE // // adj_diff.cpp // #include //For adjacent_difference #include //For vector #include //For times #include int main() { // //Initialize a vector of ints from an array // int arr[10] = {1,1,2,3,5,8,13,21,34,55}; vector v(arr,arr+10); // //Two uninitialized vectors for storing results // vector diffs(10), prods(10); // //Calculate difference(s) using default operator (minus) // adjacent_difference(v.begin(),v.end(),diffs.begin()); // //Calculate difference(s) using the times operator // adjacent_difference(v.begin(), v.end(), prods.begin(), times()); // //Output the results // cout << "For the vector: " << endl << " "; copy(v.begin(),v.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "The differences between adjacent elements are: " << endl << " "; copy(diffs.begin(),diffs.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "The products of adjacent elements are: " << endl << " "; copy(prods.begin(),prods.end(), ostream_iterator(cout," ")); cout << endl; return 0; Output : For the vector: 1 1 2 3 5 8 13 21 34 55 The differences between adjacent elements are: 1 0 1 1 2 3 5 8 13 21 The products of adjacent elements are: 1 1 2 6 15 40 104 273 714 1870 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 adjacent_find Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME adjacent_find - Find the first adjacent pair of elements in a sequence that are equivalent. SYNOPSIS #include template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last); template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred); DESCRIPTION There are two versions of the adjacent_find algorithm. The first finds equal adjacent elements in the sequence defined by iterators first and last and returns an iterator i pointing to the first of the equal elements. The second version lets you specify your own binary function to test for a condition. It returns an iterator i pointing to the first of the pair of elements that meet the conditions of the binary function. In other words, adjacent_find returns the first iterator i such that both i and i + 1 are in the range [first, last) for which one of the following conditions holds: *i == *(i + 1) or pred(*i,*(i + 1)) == true If adjacent_find does not find a match, it returns last. COMPLEXITY adjacent_find performs exactly find(first,last,value) - first applications of the corresponding predicate. EXAMPLE // // find.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 10); // Try find iterator it1 = find(v1.begin(),v1.end(),3); // Try find_if iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // Try both adjacent_find variants iterator it3 = adjacent_find(v1.begin(),v1.end()); iterator it4 = adjacent_find(v1.begin(),v1.end(),equal_to()); // Output results cout << *it1 << " " << *it2 << " " << *it3 << " " << *it4 << endl; return 0; } Output : 3 3 2 2 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO find STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 advance Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME advance - Move an iterator forward or backward (if available) by a certain distance. SYNOPSIS #include template void advance (InputIterator& i, Distance n); DESCRIPTION The advance template function allows an iterator to be advanced through a container by some arbitrary distance. For bidirectional and random access iterators, this distance may be negative. This function uses operator+ and operator- for random access iterators, which provides a constant time implementation. For input, forward, and bidirectional iterators, advance uses operator++ to provide linear time implementations. advance also uses operator-- with bidirectional iterators to provide linear time implementations of negative distances. If n is positive, advance increments iterator reference i by n. For negative n, advance decrements reference i. Remember that advance accepts a negative argument n for random access and bidirectional iterators only. EXAMPLE // // advance.cpp // #include #include #include int main() { // //Initialize a list using an array // int arr[6] = {3,4,5,6,7,8}; list l(arr,arr+6); // //Declare a list iterator, s.b. a ForwardIterator // list::iterator itr = l.begin(); // //Output the original list // cout << "For the list: "; copy(l.begin(),l.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "When the iterator is initialized to l.begin()," << endl << "it points to " << *itr << endl << endl; // // operator+ is not available for a ForwardIterator, // so use advance. // advance(itr, 4); cout << "After advance(itr,4), the iterator points to " << *itr << endl; return 0; } Output : For the list: 3 4 5 6 7 8 When the iterator is initialized to l.begin(), it points to 3 After advance(itr,4), the iterator points to 7 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO sequence, random_iterator, distance STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 binary_search Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME binary_search - Performs a binary search for a value on a container. SYNOPSIS #include template bool binary_search(ForwardIterator first, ForwardIterator last, const T& value); template bool binary_search(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); DESCRIPTION The binary_search algorithm, like other related algorithms (equal_range, lower_bound and upper_bound) performs a binary search on ordered containers. All binary search algorithms have two versions. The first version uses the less than operator (operator<) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version allows you to include a function object of type Compare, which it assumes was the function used to sort the sequence. The function object must be a binary predicate. The binary_search algorithm returns true if a sequence contains an element equivalent to the argument value. The first version of binary_search returns true if the sequence contains at least one element that is equal to the search value. The second version of the binary_search algorithm returns true if the sequence contains at least one element that satisfies the conditions of the comparison function. Formally, binary_search returns true if there is an iterator i in the range [first, last) that satisfies the corresponding conditions: !(*i < value) && !(value < *i) or comp(*i, value) == false && comp(value, *i) == false COMPLEXITY binary_search performs at most log(last - first) + 2 comparisons. EXAMPLE // // b_search.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // // Set up a vector // vector v1(d1,d1 + 10); // // Try binary_search variants // sort(v1.begin(),v1.end()); bool b1 = binary_search(v1.begin(),v1.end(),3); bool b2 = binary_search(v1.begin(),v1.end(),11,less()); // // Output results // cout << "In the vector: "; copy(v1.begin(),v1.end(), ostream_iterator(cout," ")); cout << endl << "The number 3 was " << (b1 ? "FOUND" : "NOT FOUND"); cout << endl << "The number 11 was " << (b2 ? "FOUND" : "NOT FOUND") << endl; return 0; } Output : In the vector: 0 1 2 2 2 2 3 4 6 7 The number 3 was FOUND The number 11 was NOT FOUND WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of: vector SEE ALSO equal_range, lower_bound, upper_bound STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME copy, copy_backward - Copies a range of elements SYNOPSIS #include template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result); template BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result); DESCRIPTION The copy algorithm copies values from the range specified by [first , last) to the range that specified by [result, result + (last - first)). copy can be used to copy values from one container to another, or to copy values from one location in a container to another location in the same container, as long as result is not within the range [first-last). copy returns result + (last - first). For each non-negative integer n < (last - first), copy assigns *(first + n) to *(result + n). The result of copy is undefined if result is in the range [first, last). Unless result is an insert iterator, copy assumes that at least as many elements follow result as are in the range [first, last). The copy_backward algorithm copies elements in the range specified by [first, last) into the range specified by [result - (last - first), result), starting from the end of the sequence (last-1) and progressing to the front (first). Note that copy_backward does not reverse the order of the elements, it simply reverses the order of transfer. copy_backward returns result - (last - first). You should use copy_backward instead of copy when last is in the range [result - (last - first), result). For each positive integer n <= (last - first), copy_backward assigns *(last - n) to *(result - n). The result of copy_backward is undefined if result is in the range [first, last). Unless result is an insert iterator, copy_backward assumes that there are at least as many elements ahead of result as are in the range [first, last). COMPLEXITY Both copy and copy_backward perform exactly last - first assignments. EXAMPLE // // stdlib/examples/manual.copyex.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; int d2[4] = {5,6,7,8}; // Set up three vectors // vector v1(d1,d1 + 4), v2(d2,d2 + 4), v3(d2,d2 + 4); // // Set up one empty vector // vector v4; // // Copy v1 to v2 // copy(v1.begin(),v1.end(),v2.begin()); // // Copy backwards v1 to v3 // copy_backward(v1.begin(),v1.end(),v3.end()); // // Use insert iterator to copy into empty vector // copy(v1.begin(),v1.end(),back_inserter(v4)); // // Copy all four to cout // ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.end(),out); cout << endl; return 0; } Output : 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 copy_backward Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME copy, copy_backward - Copies a range of elements SYNOPSIS #include template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result); template BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result); DESCRIPTION The copy algorithm copies values from the range specified by [first , last) to the range that specified by [result, result + (last - first)). copy can be used to copy values from one container to another, or to copy values from one location in a container to another location in the same container, as long as result is not within the range [first-last). copy returns result + (last - first). For each non-negative integer n < (last - first), copy assigns *(first + n) to *(result + n). The result of copy is undefined if result is in the range [first, last). Unless result is an insert iterator, copy assumes that at least as many elements follow result as are in the range [first, last). The copy_backward algorithm copies elements in the range specified by [first, last) into the range specified by [result - (last - first), result), starting from the end of the sequence (last-1) and progressing to the front (first). Note that copy_backward does not reverse the order of the elements, it simply reverses the order of transfer. copy_backward returns result - (last - first). You should use copy_backward instead of copy when last is in the range [result - (last - first), result). For each positive integer n <= (last - first), copy_backward assigns *(last - n) to *(result - n). The result of copy_backward is undefined if result is in the range [first, last). Unless result is an insert iterator, copy_backward assumes that there are at least as many elements ahead of result as are in the range [first,last). COMPLEXITY Both copy and copy_backward perform exactly last - first assignments. // EXAMPLE // stdlib/examples/manual.copyex.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; int d2[4] = {5,6,7,8}; // Set up three vectors // vector v1(d1,d1 + 4), v2(d2,d2 + 4), v3(d2,d2 + 4); // // Set up one empty vector // vector v4; // // Copy v1 to v2 // copy(v1.begin(),v1.end(),v2.begin()); // // Copy backwards v1 to v3 // copy_backward(v1.begin(),v1.end(),v3.end()); // // Use insert iterator to copy into empty vector // copy(v1.begin(),v1.end(),back_inserter(v4)); // // Copy all four to cout // ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.end(),out); cout << endl; return 0; } Output : 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 count Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME count, count_if - Count the number of elements in a container that satisfy a given condition. SYNOPSIS #include template iterator_trait::distance_type count(InputIterator first, InputIterator last, const T& value); template void count(InputIterator first, InputIterator last, const T& value, Size& n); template iterator_trait::distance_type count_if(InputIterator first, InputIterator last, Predicate pred); template void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n); DESCRIPTION The count algorithm compares value to elements in the sequence defined by iterators first and last. The first version of count return the number of matches. The second version increments a counting value n each time it finds a match. i.e., count returns (or adds to n) the number of iterators i in the range [first, last) for which the following condition holds: *i == value COMPLEXITY The count_if algorithm lets you specify a predicate, and returns the number of times an element in the sequence satisfies the predicate (or increments n that number of times). That is, count_if returns (or adds to n) the number of iterators i in the range [first, last) for which the following condition holds: pred(*i) == true. Both count and count_if perform exactly last-first applications of the corresponding predicate. EXAMPLE // // count.cpp // // Does not demonstrate the partial specialization versions // of count and count_if // #include #include #include int main() { int sequence[10] = {1,2,3,4,5,5,7,8,9,10}; int i=0,j=0,k=0; // // Set up a vector // vector v(sequence,sequence + 10); count(v.begin(),v.end(),5,i); // Count fives count(v.begin(),v.end(),6,j); // Count sixes // // Count all less than 8 // I=2, j=0 // count_if(v.begin(),v.end(),bind2nd(less(),8),k); // k = 7 cout << i << " " << j << " " << k << endl; return 0; } Output : 2 0 7 WARNINGS If your compiler does not support partial specialization then the first version of both count and count_if (the one that returns the count) will not be available. If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 count_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME count, count_if - Count the number of elements in a container that satisfy a given condition. SYNOPSIS #include template iterator_trait::distance_type count(InputIterator first, InputIterator last, const T& value); template void count(InputIterator first, InputIterator last, const T& value, Size& n); template iterator_trait::distance_type count_if(InputIterator first, InputIterator last, Predicate pred); template void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n); DESCRIPTION The count algorithm compares value to elements in the sequence defined by iterators first and last. The first version of count return the number of matches. The second version increments a counting value n each time it finds a match. i.e., count returns (or adds to n) the number of iterators i in the range [first, last) for which the following condition holds: *i == value COMPLEXITY The count_if algorithm lets you specify a predicate, and returns the number of times an element in the sequence satisfies the predicate (or increments n that number of times). That is, count_if returns (or adds to n) the number of iterators i in the range [first, last) for which the following condition holds: pred(*i) == true. Both count and count_if perform exactly last-first applications of the corresponding predicate. EXAMPLE // // count.cpp // // Does not demonstrate the partial specialization versions // of count and count_if // #include #include #include int main() { int sequence[10] = {1,2,3,4,5,5,7,8,9,10}; int i=0,j=0,k=0; // // Set up a vector // vector v(sequence,sequence + 10); count(v.begin(),v.end(),5,i); // Count fives count(v.begin(),v.end(),6,j); // Count sixes // // Count all less than 8 // I=2, j=0 // count_if(v.begin(),v.end(),bind2nd(less(),8),k); // k = 7 cout << i << " " << j << " " << k << endl; return 0; } Output : 2 0 7 WARNINGS If your compiler does not support partial specialization then the first version of both count and count_if (the one that returns the count) will not be available. If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 compare Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME compare - A binary function or a function object that returns true or false. compare objects are typically passed as template parameters, and used for ordering elements within a container. SEE ALSO binary_function, function object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 distance Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME distance - Computes the distance between two iterators SYNOPSIS #include template iterator_traits::distance_type distance (ForwardIterator first, ForwardIterator last); template void distance (ForwardIterator first, ForwardIterator last, Distance& n); DESCRIPTION The distance template function computes the distance between two iterator. The first version returns that value, while the second version increments n by that value. The last iterator must be reachable from the first iterator. Note that the second version of this function is obsolete. It is provided for backward compatibility and to support compilers that do not provide partial specialization. As you may have already deduced, the first version of the function is not available with compilers that do not support partial specialization since it depends on iterator_traits, which itself depends on that particular language feature. EXAMPLE // // distance.cpp // #include #include #include int main() { // //Initialize a vector using an array // int arr[6] = {3,4,5,6,7,8}; vector v(arr,arr+6); // //Declare a list iterator, s.b. a ForwardIterator // vector::iterator itr = v.begin()+3; // //Output the original vector // cout << "For the vector: "; copy(v.begin(),v.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "When the iterator is initialized to point to " << *itr << endl; // // Use of distance // vector::difference_type dist = 0; distance(v.begin(), itr, dist); cout << "The distance between the beginning and itr is " << dist << endl; return 0; } Output : For the vector: 3 4 5 6 7 8 When the iterator is initialized to point to 6 The distance between the beginning and itr is 3 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector Also, if your compiler does not support partial specialization then you will not be able to use the version of distance that returns the distance. Instead you'll have to use the version that increments a reference parameter. SEE ALSO sequence, random_iterator STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 distance_type Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME distance_type - Determine the type of distance used by an iterator. This function is now obsolete. It is retained in order to provide backward compatibility and support compilers that do not provide partial specialization. SYNOPSIS #include template inline Distance* distance_type (const input_iterator&) template inline Distance* distance_type (const forward_iterator&) template inline Distance* distance_type (const bidirectional_iterator&) template inline Distance* distance_type (const random_access_iterator&) template inline ptrdiff_t* distance_type (const T*) DESCRIPTION The distance_type family of function templates return a pointer to a value that is of the same type as that used to represent a distance between two iterators. The first four of these take an iterator of a particular type and return a pointer to a default value of the distance_type for that iterator. The T* form of the function returns ptrdiff_t*. Generic algorithms use this function to create local variables of the correct type. The distance_type functions are typically used like this: template void foo(Iterator first, Iterator last) { __foo(begin,end,distance_type(first)); } template void __foo(Iterator first,Iterator last, Distance*> { Distance d = Distance(); distance(first,last,d); } The auxiliary function template allows the algorithm to extract a distance type from the first iterator and then use that type to perform some useful work. SEE ALSO Other iterator primitives: value_type, iterator_category, distance, advance STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 equal Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME equal - Compares two ranges for equality. SYNOPSIS #include template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred); DESCRIPTION The equal algorithm does a pairwise comparison of all of the elements in one range with all of the elements in another range to see if they match. The first version of equal uses the equal operator (==) as the comparison function, and the second version allows you to specify a binary predicate as the comparison function. The first version returns true if all of the corresponding elements are equal to each other. The second version of equal returns true if for each pair of elements in the two ranges, the result of applying the binary predicate is true. In other words, equal returns true if both of the following are true: 1. There are at least as many elements in the second range as in the first; 2. For every iterator i in the range [first1, last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)) or binary_pred(*i, *(first2 + (i - first1))) == true Otherwise, equal returns false. This algorithm assumes that there are at least as many elements available after first2 as there are in the range [first1, last1). COMPLEXITY equal performs at most last1-first1 comparisons or applications of the predicate. EXAMPLE // // equal.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; int d2[4] = {1,2,4,3}; // // Set up two vectors // vector v1(d1+0, d1 + 4), v2(d2+0, d2 + 4); // Check for equality bool b1 = equal(v1.begin(),v1.end(),v2.begin()); bool b2 = equal(v1.begin(),v1.end(), v2.begin(),equal_to()); // Both b1 and b2 are false cout << (b1 ? "TRUE" : "FALSE") << " " << (b2 ? "TRUE" : "FALSE") << endl; return 0; } Output : FALSE FALSE WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 equal_range Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME equal_range - Find the largest subrange in a collection into which a given value can be inserted without violating the ordering of the collection. SYNOPSIS #include template pair equal_range(ForwardIterator first, ForwardIterator last, const T& value); template pair equal_range(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); DESCRIPTION The equal_range algorithm performs a binary search on an ordered container to determine where the element value can be inserted without violating the container's ordering. The library provides two versions of the algorithm. The first version uses the less than operator (operator <) to search for the valid insertion range, and assumes that the sequence was sorted using the less than operator. The second version allows you to specify a function object of type Compare, and assumes that Compare was the function used to sort the sequence. The function object must be a binary predicate. equal_range returns a pair of iterators, i and j that define a range containing elements equivalent to value, i.e., the first and last valid insertion points for value. If value is not an element in the container, i and j are equal. Otherwise, i will point to the first element not "less" than value, and j will point to the first element greater than value. In the second version, "less" is defined by the comparison object. Formally, equal_range returns a subrange [i, j) such that value can be inserted at any iterator k within the range. Depending upon the version of the algorithm used, k must satisfy one of the following conditions: !(*k < value) && !(value < *k) or comp(*k,value) == false && comp(value, *k) == false The range [first,last) is assumed to be sorted. COMPLEXITY equal_range performs at most 2 * log(last - first) + 1 comparisons. EXAMPLE // // eqlrange.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[11] = {0,1,2,2,3,4,2,2,2,6,7}; // // Set up a vector // vector v1(d1+0, d1 + 11); // // Try equal_range variants // pair p1 = equal_range(v1.begin(),v1.end(),3); // p1 = (v1.begin() + 4,v1.begin() + 5) pair p2 = equal_range(v1.begin(),v1.end(),2,less()); // p2 = (v1.begin() + 4,v1.begin() + 5) // Output results cout << endl << "The equal range for 3 is: " << "( " << *p1.first << " , " << *p1.second << " ) " << endl << endl; cout << endl << "The equal range for 2 is: " << "( " << *p2.first << " , " << *p2.second << " ) " << endl; return 0; } Output : The equal range for 3 is: ( 3 , 4 ) The equal range for 2 is: ( 2 , 3 ) WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > SEE ALSO instead of: vector binary_function, lower_bound, upper_bound STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 equal_to Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME equal_to - Binary function object that returns true if its first argument equals its second SYNOPSIS #include template struct equal_to; DESCRIPTION equal_to is a binary function object. Its operator() returns true if x is equal to y. You can pass an equal_to object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. equal_to would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), equal_to()); After this call to transform, vecResult(n) will contain a "1" if vec1(n) was equal to vec2(n) or a "0" if vec1(n) was not equal to vec2(n). INTERFACE template struct equal_to : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; SEE ALSO bool operator() (const T&, const T&) const; }; binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 fill Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME fill, fill_n - Initializes a range with a given value. SYNOPSIS #include template void fill(ForwardIterator first, ForwardIterator last, const T& value); template void fill_n(OutputIterator first, Size n, const T& value); DESCRIPTION The fill and fill_n algorithms are used to assign a value to the elements in a sequence. fill assigns the value to all the elements designated by iterators in the range [first, last). The fill_n algorithm assigns the value to all the elements designated by iterators in the range [first, first + n). fill_n assumes that there are at least n elements following first, unless first is an insert iterator. COMPLEXITY fill makes exactly last - first assignments, and fill_n makes exactly n assignments. EXAMPLE // // fill.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; // // Set up two vectors // vector v1(d1,d1 + 4), v2(d1,d1 + 4); // // Set up one empty vector // vector v3; // // Fill all of v1 with 9 // fill(v1.begin(),v1.end(),9); // // Fill first 3 of v2 with 7 // fill_n(v2.begin(),3,7); // // Use insert iterator to fill v3 with 5 11's // fill_n(back_inserter(v3),5,11); // // Copy all three to cout // ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; // // Fill cout with 3 5's // fill_n(ostream_iterator(cout," "),3,5); cout << endl; return 0; } Output : 9 9 9 9 7 7 7 4 11 11 11 11 11 5 5 5 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 fill_n Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME fill, fill_n - Initializes a range with a given value. SYNOPSIS #include template void fill(ForwardIterator first, ForwardIterator last, const T& value); template void fill_n(OutputIterator first, Size n, const T& value); DESCRIPTION The fill and fill_n algorithms are used to assign a value to the elements in a sequence. fill assigns the value to all the elements designated by iterators in the range [first, last). The fill_n algorithm assigns the value to all the elements designated by iterators in the range [first, first + n). fill_n assumes that there are at least n elements following first, unless first is an insert iterator. COMPLEXITY fill makes exactly last - first assignments, and fill_n makes exactly n assignments. EXAMPLE // // fill.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; // // Set up two vectors // vector v1(d1,d1 + 4), v2(d1,d1 + 4); // // Set up one empty vector // vector v3; // // Fill all of v1 with 9 // fill(v1.begin(),v1.end(),9); // // Fill first 3 of v2 with 7 // fill_n(v2.begin(),3,7); // // Use insert iterator to fill v3 with 5 11's // fill_n(back_inserter(v3),5,11); // // Copy all three to cout // ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; // // Fill cout with 3 5's // fill_n(ostream_iterator(cout," "),3,5); cout << endl; return 0; } Output : 9 9 9 9 7 7 7 4 11 11 11 11 11 5 5 5 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 find Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME find - Find an occurrence of value in a sequence SYNOPSIS #include template InputIterator find(InputIterator first, InputIterator last, const T& value); DESCRIPTION The find algorithm lets you search for the first occurrence of a particular value in a sequence. find returns the first iterator i in the range [first, last) for which the following condition holds: *i == value. If find does not find a match for value, it returns the iterator last. COMPLEXITY find performs at most last-first comparisons. EXAMPLE // // find.cpp // #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 10); // Try find iterator it1 = find(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4; // Try find_if iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // it2 = v1.begin() + 4 // Try both adjacent_find variants iterator it3 = adjacent_find(v1.begin(),v1.end()); // it3 = v1.begin() +2 iterator it4 = adjacent_find(v1.begin(),v1.end(),equal_to()); // v4 = v1.begin() + 2 // Output results cout << *it1 << " " << *it2 << " " << *it3 << " " << *it4 << endl; return 0; } Output : 3 3 2 2 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO adjacent_find, find_first_of, find_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 find_end Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME find_end - Finds the last occurrence of a sub-sequence in a sequence. SYNOPSIS #include template ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); DESCRIPTION The find_end algorithm finds the last occurrence of a sub-sequence, indicated by [first2, last2), in a sequence, [first1,last1). The algorithm returns an iterator pointing to the first element of the found subsequence, or last1 if no match is found. More precisely, the find_end algorithm returns the last iterator i in the range [first1, last1 - (last2-first2)) such that for any non-negative integer n < (last2-first2), the following corresponding conditions hold: *(i+n) == *(first2+n), pred(*(i+n),*(first2+n)) == true. Or returns last1 if no such iterator is found. Two versions of the algorithm exist. The first uses the equality operator as the default binary predicate, and the second allows you to specify a binary predicate. COMPLEXITY At most (last2-first2)*(last1-first1-(last2-first2)+1) applications of the corresponding predicate are done. EXAMPLE // // find_end.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,6,5,3,2,2,6,5,7}; int d2[4] = {6,5,0,0} // // Set up two vectors. // vector v1(d1+0, d1+10), v2(d2+0, d2+2); // // Try both find_first_of variants. // iterator it1 = find_first_of (v1.begin(), v1.end(), v2.begin(), v2.end()); iterator it2 = find_first_of (v1.begin(), v1.end(), v2.begin(), v2.end(), equal_to()); // // Try both find_end variants. // iterator it3 = find_end (v1.begin(), v1.end(), v2.begin(), v2.end()); iterator it4 = find_end (v1.begin(), v1.end(), v2.begin(), v2.end(), equal_to()); // // Output results of find_first_of. // Iterator now points to the first element that matches one of // a set of values // cout << "For the vectors: "; copy (v1.begin(), v1.end(), ostream_iterator(cout," ")); cout << " and "; copy (v2.begin(), v2.end(), ostream_iterator(cout," ")); cout<< endl ,, endl << "both versions of find_first_of point to: " << *it1 << endl << "with first_of address = " << it1 << endl ; // //Output results of find_end. // Iterator now points to the first element of the last find //sub-sequence. // cout << endl << endl << "both versions of find_end point to: " << *it3 << endl << "with find_end address = " << it3 << endl ; return 0; } Output : For the vectors: 0 1 6 5 3 2 2 6 5 7 and 6 5 both versions of find_first_of point to: 6 with first_of address = 0x100005c0 both versions of find_end point to: 6 with find_end address = 0x100005d4 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Algorithms, find, find_if, adjacent_find STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 find_first_of Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME find_first_of - Finds the first occurrence of any value from one sequence in another sequence. SYNOPSIS #include template ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); DESCRIPTION The find_first_of algorithm finds a the first occurrence of a value from a sequence, specified by first2, last2, in a sequence specified by first1, last1. The algorithm returns an iterator in the range [first1, last1) that points to the first matching element. If the first sequence [first1, last1) does not contain any of the values in the second sequence, find_first_of returns last1. In other words, find_first_of returns the first iterator i in the [first1, last1)such that for some integer j in the range [first2, last2):the following conditions hold: *i == *j, pred(*i,*j) == true. Or find_first_of returns last1 if no such iterator is found. COMPLEXITY Two versions of the algorithm exist. The first uses the equality operator as the default binary predicate, and the second allows you to specify a binary predicate. At most (last1 - first1)*(last2 - first2) applications of the corresponding predicate are done. EXAMPLE // // find_f_o.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; int d2[2] = {6,4}; // // Set up two vectors // vector v1(d1,d1 + 10), v2(d2,d2 + 2); // // Try both find_first_of variants // iterator it1 = find_first_of(v1.begin(),v1.end(),v2.begin(),v2.end()); find_first_of(v1.begin(),v1.end(),v2.begin(),v2.end(), equal_to()); // // Output results // cout << "For the vectors: "; copy(v1.begin(),v1.end(), ostream_iterator(cout," " )); cout << " and "; copy(v2.begin(),v2.end(), ostream_iterator(cout," " )); cout << endl << endl << "both versions of find_first_of point to: " << *it1; return 0; } Output : For the vectors: 0 1 2 2 3 4 2 2 6 7 and 6 4 both versions of find_first_of point to: 4 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Algorithms, adjacent_find, find, find_if, find_next, find_end STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 find_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME find_if - Find an occurrence of value in a sequence that satisfies a specifed predicate. SYNOPSIS #include template InputIterator find_if(InputIterator first, InputIterator last, Predicate pred); DESCRIPTION The find_if algorithm allows you to search for the first element in a sequence that satisfies a particular condition. The sequence is defined by iterators first and last, while the condition is defined by the third argument: a predicate function that returns a boolean value. find_if returns the first iterator i in the range [first, last) for which the following condition holds: pred(*i) == true. If no such iterator is found, find_if returns last. COMPLEXITY find_if performs at most last-first applications of the corresponding predicate. EXAMPLE // // find.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 10); // Try find iterator it1 = find(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4; // Try find_if iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // it2 = v1.begin() + 4 // Try both adjacent_find variants iterator it3 = adjacent_find(v1.begin(),v1.end()); // it3 = v1.begin() +2 iterator it4 = adjacent_find(v1.begin(),v1.end(),equal_to()); // v4 = v1.begin() + 2 // Output results cout << *it1 << " " << *it2 << " " << *it3 << " " << *it4 << endl; return 0; } Output : 3 3 2 2 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO adjacent_find, Algorithms, find, find_end, find_first_of STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 for_each Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME for_each - Applies a function to each element in a range. SYNOPSIS #include template void for_each(InputIterator first, InputIterator last, Function f); DESCRIPTION The for_each algorithm applies function f to all members of the sequence in the range [first, last), where first and last are iterators that define the sequence. Since this a non-mutating algorithm, the function f cannot make any modifications to the sequence, but it can achieve results through side effects (such as copying or printing). If f returns a result, the result is ignored. COMPLEXITY The function f is applied exactly last - first times. EXAMPLE // // for_each.cpp // #include #include #include // Function class that outputs its argument times x template class out_times_x : private unary_function { private: Arg multiplier; public: out_times_x(const Arg& x) : multiplier(x) { } void operator()(const Arg& x) { cout << x * multiplier << " " << endl; } }; int main() { int sequence[5] = {1,2,3,4,5}; // Set up a vector vector v(sequence,sequence + 5); // Setup a function object out_times_x f2(2); for_each(v.begin(),v.end(),f2); // Apply function return 0; } Output : 2 4 6 8 10 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Algorithms, function object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 generate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME generate, generate_n - Initialize a container with values produced by a value-generator class. SYNOPSIS #include template void generate(ForwardIterator first, ForwardIterator last, Generator gen); template void generate_n(OutputIterator first, Size n, Generator gen); DESCRIPTION A value-generator function returns a value each time it is invoked. The algorithms generate and generate_n initialize (or reinitialize) a sequence by assigning the return value of the generator function gen to all the elements designated by iterators in the range [first, last) or [first, first + n). The function gen takes no arguments. (gen can be a function or a class with an operator () defined that takes no arguments.) generate_n assumes that there are at least n elements following first, unless first is an insert iterator. COMPLEXITY The generate and generate_n algorithms invoke gen and assign its return value exactly last - first (or n) times. EXAMPLE // // generate.cpp // #include #include #include // Value generator simply doubles the current value // and returns it template class generate_val { private: T val_; public: generate_val(const T& val) : val_(val) {} T& operator()() { val_ += val_; return val_; } }; int main() { int d1[4] = {1,2,3,4}; generate_val gen(1); // Set up two vectors vector v1(d1,d1 + 4), v2(d1,d1 + 4); // Set up one empty vector vector v3; // Generate values for all of v1 generate(v1.begin(),v1.end(),gen); // Generate values for first 3 of v2 generate_n(v2.begin(),3,gen); // Use insert iterator to generate 5 values for v3 generate_n(back_inserter(v3),5,gen); // Copy all three to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; // Generate 3 values for cout generate_n(ostream_iterator(cout," "),3,gen); cout << endl; return 0; } Output : 2 4 8 16 2 4 8 4 2 4 8 16 32 2 4 8 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of : vector SEE ALSO function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 generate_n Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME generate, generate_n - Initialize a container with values produced by a value-generator class. SYNOPSIS #include template void generate(ForwardIterator first, ForwardIterator last, Generator gen); template void generate_n(OutputIterator first, Size n, Generator gen); DESCRIPTION A value-generator function returns a value each time it is invoked. The algorithms generate and generate_n initialize (or reinitialize) a sequence by assigning the return value of the generator function gen to all the elements designated by iterators in the range [first, last) or [first, first + n). The function gen takes no arguments. (gen can be a function or a class with an operator () defined that takes no arguments.) generate_n assumes that there are at least n elements following first, unless first is an insert iterator. COMPLEXITY The generate and generate_n algorithms invoke gen and assign its return value exactly last - first (or n) times. EXAMPLE // // generate.cpp // #include #include #include // Value generator simply doubles the current value // and returns it template class generate_val { private: T val_; public: generate_val(const T& val) : val_(val) {} T& operator()() { val_ += val_; return val_; } }; int main() { int d1[4] = {1,2,3,4}; generate_val gen(1); // Set up two vectors vector v1(d1,d1 + 4), v2(d1,d1 + 4); // Set up one empty vector vector v3; // Generate values for all of v1 generate(v1.begin(),v1.end(),gen); // Generate values for first 3 of v2 generate_n(v2.begin(),3,gen); // Use insert iterator to generate 5 values for v3 generate_n(back_inserter(v3),5,gen); // Copy all three to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; // Generate 3 values for cout generate_n(ostream_iterator(cout," "),3,gen); cout << endl; return 0; } Output : 2 4 8 16 2 4 8 4 2 4 8 16 32 2 4 8 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of : vector SEE ALSO function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 greater Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME greater - Binary function object that returns true if its first argument is greater than its second. SYNOPSIS #include template struct greater : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; DESCRIPTION greater is a binary function object. Its operator() returns true if x is greater than y. You can pass a greater object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result of the function. greater would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), greater()); WARNINGS After this call to transform, vecResult(n) will contain a "1" if vec1(n) was greater than vec2(n) or a "0" if vec1(n) was less than or equal to vec2(n). If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of vector SEE ALSO function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 greater_equal Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME greater_equal - Binary function object that returns true if its first argument is greater than or equal to its second SYNOPSIS #include template struct greater_equal ; : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; DESCRIPTION greater_equal is a binary function object. Its operator() returns true if x is greater than or equal to y. You can pass a greater_equal object to any algorithm that requires a binary function. For example, the sort algorithm can accept a binary function as an alternate comparison object to sort a sequence. greater_equal would be used in that algorithm in the following manner: vector vec1; sort(vec1.begin(), vec1.end(),greater_equal()); After this call to sort, vec1 will be sorted in descending order. WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of vector SEE ALSO function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Heap_Operations Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Heap_Operations See the entries for make_heap, pop_heap, push_heap and sort_heap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 includes Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME includes - Basic set operation for sorted sequences. SYNOPSIS #include template bool includes (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); template bool includes (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp); DESCRIPTION The includes algorithm compares two sorted sequences and returns true if every element in the range [first2, last2) is contained in the range [first1, last1). It returns false otherwise. include assumes that the sequences are sorted using the default comparison operator less than (<), unless an alternative comparison operator (comp) is provided. COMPLEXITY At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. EXAMPLE // // includes.cpp // #include #include #include int main() { //Initialize some sets int a1[10] = {1,2,3,4,5,6,7,8,9,10}; int a2[6] = {2,4,6,8,10,12}; int a3[4] = {3,5,7,8}; set > all(a1, a1+10), even(a2, a2+6), small(a3,a3+4); //Demonstrate includes cout << "The set: "; copy(all.begin(),all.end(), ostream_iterator(cout," ")); bool answer = includes(all.begin(), all.end(), small.begin(), small.end()); cout << endl << (answer ? "INCLUDES " : "DOES NOT INCLUDE "); copy(small.begin(),small.end(), ostream_iterator(cout," ")); answer = includes(all.begin(), all.end(), even.begin(), even.end()); cout << ", and" << endl << (answer ? "INCLUDES" : "DOES NOT INCLUDE "); copy(even.begin(),even.end(), ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : The set: 1 2 3 4 5 6 7 8 9 10 INCLUDES 3 5 7 8 , and DOES NOT INCLUDE 2 4 6 8 10 12 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : set, allocator > instead of set SEE ALSO set, set_union, set_intersection, set_difference, set_symmetric_difference STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 inner_product Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME inner_product - Computes the inner product A X B of two ranges A and B. SYNOPSIS #include template T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); template T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); DESCRIPTION There are two versions of inner_product. The first computes an inner product using the default multiplication and addition operators, while the second allows you to specify binary operations to use in place of the default operations. The first version of the function computes its result by initializing the accumulator acc with the initial value init and then modifying it with: acc = acc + ((*i1) * (*i2)) for every iterator i1 in the range [first1, last1) and iterator i2 in the range [first2, first2 + (last1 - first1)). The algorithm returns acc. The second version of the function initializes acc with init, then computes the result: acc = binary_op1(acc, binary_op2(*i1, *i2)) for every iterator i1 in the range [first1, last1) and iterator i2 in the range [first2, first2 + (last1 - first1)). COMPLEXITY The inner_product algorithm computes exactly (last1 - first1) applications of either: acc + (*i1) * (*i2) or binary_op1(acc, binary_op2(*i1, *i2)). EXAMPLE // // inr_prod.cpp // #include //For inner_product #include //For list #include //For vectors #include //For plus and minus #include int main() { //Initialize a list and an int using arrays of ints int a1[3] = {6, -3, -2}; int a2[3] = {-2, -3, -2}; list l(a1, a1+3); vector v(a2, a2+3); //Calculate the inner product of the two sets of values int inner_prod = inner_product(l.begin(), l.end(), v.begin(), 0); //Calculate a wacky inner product using the same values int wacky = inner_product(l.begin(), l.end(), v.begin(), 0, plus(), minus()); //Print the output cout << "For the two sets of numbers: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << " and "; copy(l.begin(),l.end(),ostream_iterator(cout," ")); cout << "," << endl << endl; cout << "The inner product is: " << inner_prod << endl; cout << "The wacky result is: " << wacky << endl; return 0; } Output : For the two sets of numbers: -2 -3 -2 and 6 -3 -2 , The inner product is: 1 The wacky result is: 8 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : list > and vector > instead of list and vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 inplace_merge Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME inplace_merge - Merge two sorted sequences into one. SYNOPSIS #include template void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last); template void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp); DESCRIPTION The inplace_merge algorithm merges two sorted consecutive ranges [first, middle) and [middle, last), and puts the result of the merge into the range [first, last). The merge is stable, that is, if the two ranges contain equivalent elements, the elements from the first range always precede the elements from the second. There are two versions of the inplace_merge algorithm. The first version uses the less than operator (operator<) as the default for comparison, and the second version accepts a third argument that specifies a comparison operator. COMPLEXITY When enough additional memory is available, inplace_merge does at most (last - first) - 1 comparisons. If no additional memory is available, an algorithm with O(NlogN) complexity (where N is equal to last-first) may be used. EXAMPLE // // merge.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; int d2[8] = {11,13,15,17,12,14,16,18}; // Set up two vectors vector v1(d1,d1 + 4), v2(d1,d1 + 4); // Set up four destination vectors vector v3(d2,d2 + 8),v4(d2,d2 + 8), v5(d2,d2 + 8),v6(d2,d2 + 8); // Set up one empty vector vector v7; // Merge v1 with v2 merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin()); // Now use comparator merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v4.begin(), less()); // In place merge v5 vector::iterator mid = v5.begin(); advance(mid,4); inplace_merge(v5.begin(),mid,v5.end()); // Now use a comparator on v6 mid = v6.begin(); advance(mid,4); inplace_merge(v6.begin(),mid,v6.end(),less()); // Merge v1 and v2 to empty vector using insert iterator merge(v1.begin(),v1.end(),v2.begin(),v2.end(), back_inserter(v7)); // Copy all cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.end(),out); cout << endl; copy(v5.begin(),v5.end(),out); cout << endl; copy(v6.begin(),v6.end(),out); cout << endl; copy(v7.begin(),v7.end(),out); cout << endl; // Merge v1 and v2 to cout merge(v1.begin(),v1.end(),v2.begin(),v2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output: 1 2 3 4 1 2 3 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 11 12 13 14 15 16 17 18 11 12 13 14 15 16 17 18 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of vector SEE ALSO merge STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 iter_swap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME iter_swap - Exchange values pointed at in two locations SYNOPSIS #include template void iter_swap (ForwardIterator1, ForwardIterator2); DESCRIPTION The iter_swap algorithm exchanges the values pointed at by the two iterators a and b. EXAMPLE #include #include #include int main () { int d1[] = {6, 7, 8, 9, 10, 1, 2, 3, 4, 5}; // // Set up a vector. // vector v(d1+0, d1+10); // // Output original vector. // cout << "For the vector: "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); // // Swap the first five elements with the last five elements. // swap_ranges(v.begin(), v.begin()+5, v.begin()+5); // // Output result. // cout << endl << endl << "Swapping the first 5 elements with the last 5 gives: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); // // Now an example of iter_swap -- swap first and last elements. // iter_swap(v.begin(), v.end()-1); // // Output result. // cout << endl << endl << "Swapping the first and last elements gives: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : For the vector: 6 7 8 9 10 1 2 3 4 5 Swapping the first five elements with the last five gives: 1 2 3 4 5 6 7 8 9 10 Swapping the first and last elements gives: 10 2 3 4 5 6 7 8 9 1 WARNING If your compiler does not support default template parameters, then you will need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of : vector SEE ALSO Iterators, swap, swap_ranges STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 lexicographical_compare Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME lexicographical_compare - Compares two ranges lexicographically. SYNOPSIS #include template bool lexicographical_compare(InputIterator1 first, InputIterator2 last1, InputIterator2 first2, InputIterator last2); template bool lexicographical_compare(InputIterator1 first, InputIterator2 last1, InputIterator2 first2, InputIterator last2, Compare comp); DESCRIPTION The lexicographical_compare functions compare each element in the range [first1, last1) to the corresponding element in the range [first2, last2) using iterators i and j. The first version of the algorithm uses operator< as the default comparison operator. It immediately returns true if it encounters any pair in which *i is less than *j, and immediately returns false if *j is less than *i. If the algorithm reaches the end of the first sequence before reaching the end of the second sequence, it also returns true. The second version of the function takes an argument comp that defines a comparison function that is used in place of the default operator<. The lexicographical_compare functions can be used with all the datatypes provided by the standard library. COMPLEXITY lexicographical_compare performs at most min((last1 - first1), (last2 - first2)) applications of the comparison function. EXAMPLE // // lex_comp.cpp // #include #include #include int main(void) { int d1[5] = {1,3,5,32,64}; int d2[5] = {1,3,2,43,56}; // set up vector vector v1(d1,d1 + 5), v2(d2,d2 + 5); // Is v1 less than v2 (I think not) bool b1 = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end()); // Is v2 less than v1 (yup, sure is) bool b2 = lexicographical_compare(v2.begin(), v2.end(), v1.begin(), v1.end(), less()); cout << (b1 ? "TRUE" : "FALSE") << " " << (b2 ? "TRUE" : "FALSE") << endl; return 0; } Output: FALSE TRUE WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of : vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 lower_bound Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME lower_bound - Determine the first valid position for an element in a sorted container. SYNOPSIS template ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value); template ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); DESCRIPTION The lower_bound algorithm compares a supplied value to elements in a sorted container and returns the first position in the container that value can occupy without violating the container's ordering. There are two versions of the algorithm. The first uses the less than operator (operator<) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version lets you include a function object of type Compare, and assumes that Compare is the function used to sort the sequence. The function object must be a binary predicate. lower_bound's return value is the iterator for the first element in the container that is greater than or equal to value, or, when the comparison operator is used, the first element that does not satisfy the comparison function. Formally, the algorithm returns an iterator i in the range [first, last) such that for any iterator j in the range [first, i) the following corresponding conditions hold: *j < value or comp(*j, value) == true COMPLEXITY lower_bound performs at most log(last - first) + 1 comparisons. EXAMPLE // // ul_bound.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[11] = {0,1,2,2,3,4,2,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 11); // Try lower_bound variants iterator it1 = lower_bound(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4 iterator it2 = lower_bound(v1.begin(),v1.end(),2,less()); // it2 = v1.begin() + 4 // Try upper_bound variants iterator it3 = upper_bound(v1.begin(),v1.end(),3); // it3 = vector + 5 iterator it4 = upper_bound(v1.begin(),v1.end(),2,less()); // it4 = v1.begin() + 5 cout << endl << endl << "The upper and lower bounds of 3: ( " << *it1 << " , " << *it3 << " ]" << endl; cout << endl << endl << "The upper and lower bounds of 2: ( " << *it2 << " , " << *it4 << " ]" << endl; return 0; } Output : The upper and lower bounds of 3: ( 3 , 4 ] The upper and lower bounds of 2: ( 2 , 3 ] WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO upper_bound, equal_range STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 make_heap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME make_heap - Creates a heap. SYNOPSIS #include template void make_heap(RandomAccessIterator first, RandomAccessIterator last); template void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm, or a new element can be added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The heap algorithms use less than (operator<) as the default comparison. In all of the algorithms, an alternate comparison operator can be specified. The first version of the make_heap algorithm arranges the elements in the range [first, last) into a heap using less than (operator<) to perform comparisons. The second version uses the comparison operator comp to perform the comparisons. Since the only requirements for a heap are the two listed above, make_heap is not required to do anything within the range (first, last - 1). COMPLEXITY This algorithm makes at most 3 * (last - first) comparisons. EXAMPLE // // heap_ops.cpp // #include #include #include int main(void) { int d1[4] = {1,2,3,4}; int d2[4] = {1,3,2,4}; // Set up two vectors vector v1(d1,d1 + 4), v2(d2,d2 + 4); // Make heaps make_heap(v1.begin(),v1.end()); make_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Note that x, y and z represent the remaining // values in the container (other than 4). // The definition of the heap and heap operations // does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now sort those heaps sort_heap(v1.begin(),v1.end()); sort_heap(v2.begin(),v2.end(),less()); // v1 = v2 = (1,2,3,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; return 0; } Output : 4 2 3 1 4 3 2 1 3 2 1 4 3 1 2 4 4 3 1 2 4 3 2 1 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO pop_heap, push_heap and sort_heap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 max Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME max - Find and return the maximum of a pair of values SYNOPSIS #include template const T& max(const T&, const T&); template const T& max(const T&, const T&, Compare); DESCRIPTION The max algorithm determines and returns the maximum of a pair of values. The optional argument Compare defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library. max returns the first argument when the arguments are equal. EXAMPLE // // max.cpp // #include #include #include int main(void) { double d1 = 10.0, d2 = 20.0; // Find minimum double val1 = min(d1, d2); // val1 = 10.0 // the greater comparator returns the greater of the // two values. double val2 = min(d1, d2, greater()); // val2 = 20.0; // Find maximum double val3 = max(d1, d2); // val3 = 20.0; // the less comparator returns the smaller of the two values. // Note that, like every comparison in the STL, max is // defined in terms of the < operator, so using less here // is the same as using the max algorithm with a default // comparator. double val4 = max(d1, d2, less()); // val4 = 20 cout << val1 << " " << val2 << " " << val3 << " " << val4 << endl; return 0; } Output : 10 20 20 20 SEE ALSO max_element, min, min_element STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 max_element Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME max_element - Finds maximum value in a range. SYNOPSIS #include template ForwardIterator max_element(ForwardIterator first, ForwardIterator last); template ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare comp); DESCRIPTION The max_element algorithm returns an iterator that denotes the maximum element in a sequence. If the sequence contains more than one copy of the element, the iterator points to its first occurrence. The optional argument comp defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library. Algorithm max_element returns the first iterator i in the range [first, last) such that for any iterator j in the same range the following corresponding conditions hold: !(*i < *j) or comp(*i, *j) == false. COMPLEXITY Exactly max((last - first) - 1, 0) applications of the corresponding comparisons are done for max_element. EXAMPLE // // max_elem.cpp // #include #include #include int main(void) { typedef vector::iterator iterator; int d1[5] = {1,3,5,32,64}; // set up vector vector v1(d1,d1 + 5); // find the largest element in the vector iterator it1 = max_element(v1.begin(), v1.end()); // it1 = v1.begin() + 4 // find the largest element in the range from // the beginning of the vector to the 2nd to last iterator it2 = max_element(v1.begin(), v1.end()-1, less()); // it2 = v1.begin() + 3 // find the smallest element iterator it3 = min_element(v1.begin(), v1.end()); // it3 = v1.begin() // find the smallest value in the range from // the beginning of the vector plus 1 to the end iterator it4 = min_element(v1.begin()+1, v1.end(), less()); // it4 = v1.begin() + 1 cout << *it1 << " " << *it2 << " " << *it3 << " " << *it4 << endl; return 0; } Output : 64 32 1 3 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO max, min, min_element STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 merge Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME merge - Merge two sorted sequences into a third sequence. SYNOPSIS #include template OutputIterator merge(InputIterator first1, InputIterator1 last1, InputIterator2 first2, InputIterator last2, OutputIterator result); template OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator last2, OutputIterator result, Compare comp); DESCRIPTION The merge algorithm merges two sorted sequences, specified by [first1, last1) and [first2, last2), into the sequence specified by [result, result + (last1 - first1) + (last2 - first2)). The first version of the merge algorithm uses the less than operator (<) to compare elements in the two sequences. The second version uses the comparison function provided by the function call. If a comparison function is provided, merge assumes that both sequences were sorted using that comparison function. The merge is stable. This means that if the two original sequences contain equivalent elements, the elements from the first sequence will always precede the matching elements from the second in the resulting sequence. The size of the result of a merge is equal to the sum of the sizes of the two argument sequences. merge returns an iterator that points to the end of the resulting sequence, i.e., result + (last1 - first1) + (last2 -first2). The result of merge is undefined if the resulting range overlaps with either of the original ranges. merge assumes that there are at least (last1 - first1) + (last2 - first2) elements following result, unless result has been adapted by an insert iterator. COMPLEXITY For merge at most (last - first1) + (last2 - first2) - 1 comparisons are performed. EXAMPLE // // merge.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; int d2[8] = {11,13,15,17,12,14,16,18}; // Set up two vectors vector v1(d1,d1 + 4), v2(d1,d1 + 4); // Set up four destination vectors vector v3(d2,d2 + 8),v4(d2,d2 + 8), v5(d2,d2 + 8),v6(d2,d2 + 8); // Set up one empty vector vector v7; // Merge v1 with v2 merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin()); // Now use comparator merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v4.begin(), less()); // In place merge v5 vector::iterator mid = v5.begin(); advance(mid,4); inplace_merge(v5.begin(),mid,v5.end()); // Now use a comparator on v6 mid = v6.begin(); advance(mid,4); inplace_merge(v6.begin(),mid,v6.end(),less()); // Merge v1 and v2 to empty vector using insert iterator merge(v1.begin(),v1.end(),v2.begin(),v2.end(), back_inserter(v7)); // Copy all cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.end(),out); cout << endl; copy(v5.begin(),v5.end(),out); cout << endl; copy(v6.begin(),v6.end(),out); cout << endl; copy(v7.begin(),v7.end(),out); cout << endl; // Merge v1 and v2 to cout merge(v1.begin(),v1.end(),v2.begin(),v2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : 1 2 3 4 1 2 3 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 11 12 13 14 15 16 17 18 11 12 13 14 15 16 17 18 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Containers, inplace_merge STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 min Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME min - Find and return the minimum of a pair of values SYNOPSIS #include template const T& min(const T&, const T&); template const T& min(const T& a, const T&, Compare); DESCRIPTION The min algorithm determines and returns the minimum of a pair of values. In the second version of the algorithm, the optional argument Compare defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library. min returns the first argument when the two arguments are equal. EXAMPLE // // max.cpp // #include #include int main(void) { double d1 = 10.0, d2 = 20.0; // Find minimum double val1 = min(d1, d2); // val1 = 10.0 // the greater comparator returns the greater of the // two values. double val2 = min(d1, d2, greater()); // val2 = 20.0; // Find maximum double val3 = max(d1, d2); // val3 = 20.0; // the less comparator returns the smaller of the // two values. // Note that, like every comparison in the STL, max is // defined in terms of the < operator, so using less here // is the same as using the max algorithm with a default // comparator. double val4 = max(d1, d2, less()); // val4 = 20 cout << val1 << " " << val2 << " " << val3 << " " << val4 << endl; return 0; } Output : 10 20 20 20 SEE ALSO max, max_element, min_element STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 min_element Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME min_element - Finds the minimum value in a range. SYNOPSIS #include template ForwardIterator min_element(ForwardIterator first, ForwardIterator last); template InputIterator min_element(ForwardIterator first, ForwardIterator last, Compare comp); DESCRIPTION The min_element algorithm returns an iterator that denotes the minimum element in a sequence. If the sequence contains more than one copy of the minimum element, the iterator points to the first occurrence of the element. In the second version of the function, the optional argument comp defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library. Algorithm min_element returns the first iterator i in the range [first, last) such that for any iterator j in the range same range, the following corresponding conditions hold: !(*j < *i) or comp(*j, *i) == false. COMPLEXITY min_element performs exactly max((last - first) - 1, 0) applications of the corresponding comparisons. EXAMPLE // // max_elem.cpp // #include #include #include int main(void) { typedef vector::iterator iterator; int d1[5] = {1,3,5,32,64}; // set up vector vector v1(d1,d1 + 5); // find the largest element in the vector iterator it1 = max_element(v1.begin(), v1.end()); // it1 = v1.begin() + 4 // find the largest element in the range from // the beginning of the vector to the 2nd to last iterator it2 = max_element(v1.begin(), v1.end()-1, less()); // it2 = v1.begin() + 3 // find the smallest element iterator it3 = min_element(v1.begin(), v1.end()); // it3 = v1.begin() // find the smallest value in the range from // the beginning of the vector plus 1 to the end iterator it4 = min_element(v1.begin()+1, v1.end(), less()); // it4 = v1.begin() + 1 cout << *it1 << " " << *it2 << " " << *it3 << " " << *it4 << endl; return 0; } Output : 64 32 1 3 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO max, max_element, min STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 mismatch Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME mismatch - Compares elements from two sequences and returns the first two elements that don't match each other. SYNOPSIS #include template pair mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template pair mismatch(InputIterator first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred); DESCRIPTION The mismatch algorithm compares members of two sequences and returns two iterators (i and j) that point to the first location in each sequence where the sequences differ from each other. Notice that the algorithm denotes both a starting position and an ending position for the first sequence, but denotes only a starting position for the second sequence. mismatch assumes that the second sequence has at least as many members as the first sequence. If the two sequences are identical, mismatch returns a pair of iterators that point to the end of the first sequence and the corresponding location at which the comparison stopped in the second sequence. The first version of mismatch checks members of a sequence for equality, while the second version lets you specify a comparison function. The comparison function must be a binary predicate. The iterators i and j returned by mismatch are defined as follows: j == first2 + (i - first1) and i is the first iterator in the range [first1, last1) for which the appropriate one of the following conditions hold: !(*i == *(first2 + (i - first1))) or binary_pred(*i, *(first2 + (i - first1))) == false If all of the members in the two sequences match, mismatch returns a pair of last1 and first2 + (last1 - first1). COMPLEXITY At most last1 - first1 applications of the corresponding predicate are done. EXAMPLE // // mismatch.cpp // #include #include #include int main(void) { typedef vector::iterator iterator; int d1[4] = {1,2,3,4}; int d2[4] = {1,3,2,4}; // Set up two vectors vector vi1(d1,d1 + 4), vi2(d2,d2 + 4); // p1 will contain two iterators that point to the // first pair of elements that are different between // the two vectors pair p1 = mismatch(vi1.begin(), vi1.end(), vi2.begin()); // find the first two elements such that an element in the // first vector is greater than the element in the second // vector. pair p2 = mismatch(vi1.begin(), vi1.end(), vi2.begin(), less_equal()); // Output results cout << *p1.first << ", " << *p1.second << endl; cout << *p2.first << ", " << *p2.second << endl; return 0; } Output : 2, 3 3, 2 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 next_permutation Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME next_permutation - Generate successive permutations of a sequence based on an ordering function. SYNOPSIS #include template bool next_permutation (BidirectionalIterator first, BidirectionalIterator last); template bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, Compare comp); DESCRIPTION The permutation-generating algorithms (next_permutation and prev_permutation) assume that the set of all permutations of the elements in a sequence is lexicographically sorted with respect to operator< or comp. So, for example, if a sequence includes the integers 1 2 3, that sequence has six permutations, which, in order from first to last are: 1 2 3 , 1 3 2, 2 1 3, 2 3 1, 3 1 2, and 3 2 1. The next_permutation algorithm takes a sequence defined by the range [first, last) and transforms it into its next permutation, if possible. If such a permutation does exist, the algorithm completes the transformation and returns true. If the permutation does not exist, next_permutation returns false, and transforms the permutation into its "first" permutation (according to the lexicographical ordering defined by either operator<, the default used in the first version of the algorithm, or comp, which is user-supplied in the second version of the algorithm.) For example, if the sequence defined by [first, last) contains the integers 3 2 1 (in that order), there is not a "next permutation." Therefore, the algorithm transforms the sequence into its first permutation (1 2 3) and returns false. COMPLEXITY At most (last - first)/2 swaps are performed. EXAMPLE // // permute.cpp // #include //for accumulate #include //for vector #include //for less #include int main() { //Initialize a vector using an array of ints int a1[] = {0,0,0,0,1,0,0,0,0,0}; char a2[] = "abcdefghji"; //Create the initial set and copies for permuting vector m1(a1, a1+10); vector prev_m1((size_t)10), next_m1((size_t)10); vector m2(a2, a2+10); vector prev_m2((size_t)10), next_m2((size_t)10); copy(m1.begin(), m1.end(), prev_m1.begin()); copy(m1.begin(), m1.end(), next_m1.begin()); copy(m2.begin(), m2.end(), prev_m2.begin()); copy(m2.begin(), m2.end(), next_m2.begin()); //Create permutations prev_permutation(prev_m1.begin(), prev_m1.end(),less()); next_permutation(next_m1.begin(), next_m1.end(),less()); prev_permutation(prev_m2.begin(), prev_m2.end(),less()); next_permutation(next_m2.begin(), next_m2.end(),less()); //Output results cout << "Example 1: " << endl << " "; cout << "Original values: "; copy(m1.begin(),m1.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous permutation: "; copy(prev_m1.begin(),prev_m1.end(), ostream_iterator(cout," ")); cout << endl<< " "; cout << "Next Permutation: "; copy(next_m1.begin(),next_m1.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "Example 2: " << endl << " "; cout << "Original values: "; copy(m2.begin(),m2.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous Permutation: "; copy(prev_m2.begin(),prev_m2.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Next Permutation: "; copy(next_m2.begin(),next_m2.end(), ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : Example 1: Original values: 0 0 0 0 1 0 0 0 0 0 Previous permutation: 0 0 0 0 0 1 0 0 0 0 Next Permutation: 0 0 0 1 0 0 0 0 0 0 Example 2: Original values: a b c d e f g h j i Previous Permutation: a b c d e f g h i j Next Permutation: a b c d e f g i h j WARNING If your compiler does not support default template parameters, the you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO prev_permutation STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 nth_element Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME nth_element - Rearranges a collection so that all elements lower in sorted order than the nth element come before it and all elements higher in sorter order than the nth element come after it. SYNOPSIS #include template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); template void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp); DESCRIPTION The nth_element algorithm rearranges a collection according to either the default comparison operator (>) or the provided comparison operator. After the algorithm applies, three things are true: + The element that would be in the nth position if the collection were completely sorted is in the nth position + All elements prior to the nth position would precede that position in an ordered collection + All elements following the nth position would follow that position in an ordered collection That is, for any iterator i in the range [first, nth) and any iterator j in the range [nth, last) it holds that !(*i > *j) or comp(*i, *j) == false. Note that the elements that precede or follow the nth position are not necessarily sorted relative to each other. The nth_element algorithm does not sort the entire collection. COMPLEXITY The algorithm is linear, on average, where N is the size of the range [first, last). EXAMPLE // // nthelem.cpp // #include #include #include template void quik_sort(RandomAccessIterator start, RandomAccessIterator end) { size_t dist = 0; distance(start, end, dist); //Stop condition for recursion if(dist > 2) { //Use nth_element to do all the work for quik_sort nth_element(start, start+(dist/2), end); //Recursive calls to each remaining unsorted portion quik_sort(start, start+(dist/2-1)); quik_sort(start+(dist/2+1), end); } if(dist == 2 && *end < *start) swap(start, end); } int main() { //Initialize a vector using an array of ints int arr[10] = {37, 12, 2, -5, 14, 1, 0, -1, 14, 32}; vector v(arr, arr+10); //Print the initial vector cout << "The unsorted values are: " << endl << " "; vector::iterator i; for(i = v.begin(); i != v.end(); i++) cout << *i << ", "; cout << endl << endl; //Use the new sort algorithm quik_sort(v.begin(), v.end()); //Output the sorted vector cout << "The sorted values are: " << endl << " "; for(i = v.begin(); i != v.end(); i++) cout << *i << ", "; cout << endl << endl; return 0; } Output : The unsorted values are: 37, 12, 2, -5, 14, 1, 0, -1, 14, 32, The sorted values are: -5, -1, 0, 1, 2, 12, 14, 14, 32, 37, WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO Algorithms STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 partial_sort Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME partial_sort - Templated algorithm for sorting collections of entities. SYNOPSIS #include template void partial_sort (RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last); template void partial_sort (RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp); DESCRIPTION The partial_sort algorithm takes the range [first,last) and places the first middle - first values into sorted order. The result is that the range [first, middle)is sorted like it would be if the entire range [first,last) were sorted. The remaining elements in the range (those in [middle, last)) are not in any defined order. The first version of the algorithm uses less than (operator<) as the comparison operator for the sort. The second version uses the comparison function comp. COMPLEXITY partial_sort does approximately (last - first) * log(middle-first) comparisons. EXAMPLE // // partsort.cpp // #include #include #include int main() { int d1[20] = {17, 3, 5, -4, 1, 12, -10, -1, 14, 7, -6, 8, 15, -11, 2, -2, 18, 4, -3, 0}; // // Set up a vector. // vector v1(d1+0, d1+20); // // Output original vector. // cout << "For the vector: "; copy(v1.begin(), v1.end(), ostream_iterator(cout," ")); // // Partial sort the first seven elements. // partial_sort(v1.begin(), v1.begin()+7, v1.end()); // // Output result. // cout << endl << endl << "A partial_sort of seven elements gives: " << endl << " "; copy(v1.begin(), v1.end(), ostream_iterator(cout," ")); cout << endl; // // A vector of ten elements. // vector v2(10, 0); // // Sort the last ten elements in v1 into v2. // partial_sort_copy(v1.begin()+10, v1.end(), v2.begin(), v2.end()); // // Output result. // cout << endl << "A partial_sort_copy of the last ten elements gives: " << endl << " "; copy(v2.begin(), v2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : For the vector: 17 3 5 -4 1 12 -10 -1 14 7 -6 8 15 -11 2 -2 18 4 -3 0 A partial_sort of seven elements gives: -11 -10 -6 -4 -3 -2 -1 17 14 12 7 8 15 5 3 2 18 4 1 0 A partial_sort_copy of the last ten elements gives: 0 1 2 3 4 5 7 8 15 18 WARNING If your compiler does not support default template parameters, then you need to always provide the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO sort, stable_sort, partial_sort_copy STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 partial_sort_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME partial_sort_copy - Templated algorithm for sorting collections of entities. SYNOPSIS #include template void partial_sort_copy (InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last); template void partial_sort_copy (InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, Compare comp); DESCRIPTION The partial_sort_copy algorithm places the smaller of last - first and result_last - result_first sorted elements from the range [first, last) into the range beginning at result_first. (i.e., the range: [result_first, result_first+min(last - first, result_last - result_first)). Basically, the effect is as if the range [first,last) were placed in a temporary buffer, sorted and then as many elements as possible were copied into the range [result_first, result_last). The first version of the algorithm uses less than (operator<) as the comparison operator for the sort. The second version uses the comparison function comp. COMPLEXITY partial_sort_copy does approximately (last-first) * log(min(last-first, result_last-result_first)) comparisons. EXAMPLE // // partsort.cpp // #include #include #include int main() { int d1[20] = {17, 3, 5, -4, 1, 12, -10, -1, 14, 7, -6, 8, 15, -11, 2, -2, 18, 4, -3, 0}; // // Set up a vector. // vector v1(d1+0, d1+20); // // Output original vector. // cout << "For the vector: "; copy(v1.begin(), v1.end(), ostream_iterator(cout," ")); // // Partial sort the first seven elements. // partial_sort(v1.begin(), v1.begin()+7, v1.end()); // // Output result. // cout << endl << endl << "A partial_sort of 7 elements gives: " << endl << " "; copy(v1.begin(), v1.end(), ostream_iterator(cout," ")); cout << endl; // // A vector of ten elements. // vector v2(10, 0); // // Sort the last ten elements in v1 into v2. // partial_sort_copy(v1.begin()+10, v1.end(), v2.begin(), v2.end()); // // Output result. // cout << endl << "A partial_sort_copy of the last ten elements gives: " << endl << " "; copy(v2.begin(), v2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : For the vector: 17 3 5 -4 1 12 -10 -1 14 7 -6 8 15 -11 2 -2 18 4 -3 0 A partial_sort of seven elements gives: -11 -10 -6 -4 -3 -2 -1 17 14 12 7 8 15 5 3 2 18 4 1 0 A partial_sort_copy of the last ten elements gives: 0 1 2 3 4 5 7 8 15 18 WARNING If your compiler does not support default template parameters, then you need to always provide the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO sort_ stable_sort, partial_sort STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 partial_sum Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME partial_sum - Calculates successive partial sums of a range of values. SYNOPSIS #include template OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result); template OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); DESCRIPTION The partial_sum algorithm creates a new sequence in which every element is formed by adding all the values of the previous elements, or, in the second form of the algorithm, applying the operation binary_op successively on every previous element. That is, partial_sum assigns to every iterator i in the range [result, result + (last - first)) a value equal to: ((...(*first + *(first + 1)) + ... ) + *(first + (i - result))) or, in the second version of the algorithm: binary_op(binary_op(..., binary_op (*first, *(first + 1)),...),*(first + (i - result))) For instance, applying partial_sum to (1,2,3,4,) will yield (1,3,6,10). The partial_sum algorithm returns result + (last - first). If result is equal to first, the elements of the new sequence successively replace the elements in the original sequence, effectively turning partial_sum into an inplace transformation. COMPLEXITY Exactly (last - first) - 1 applications of the default + operator or binary_op are performed. EXAMPLE // // partsum.cpp // #include //for accumulate #include //for vector #include //for times #include int main() { //Initialize a vector using an array of ints int d1[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(d1, d1+10); //Create an empty vectors to store results vector sums((size_t)10), prods((size_t)10); //Compute partial_sums and partial_products partial_sum(v.begin(), v.end(), sums.begin()); partial_sum(v.begin(), v.end(), prods.begin(), times()); //Output the results cout << "For the series: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; cout << "The partial sums: " << endl << " " ; copy(sums.begin(),sums.end(), ostream_iterator(cout," ")); cout <<" should each equal (N*N + N)/2" << endl << endl; cout << "The partial products: " << endl << " "; copy(prods.begin(),prods.end(), ostream_iterator(cout," ")); cout << " should each equal N!" << endl; return 0; } Output : For the series: 1 2 3 4 5 6 7 8 9 10 The partial sums: 1 3 6 10 15 21 28 36 45 55 should each equal (N*N + N)/2 The partial products: 1 2 6 24 120 720 5040 40320 362880 3628800 should each equal N! WARNING If your compiler does not support default template parameters, then you need to always provide the Allocator template argument. For instance, you will need to write : vector > instead of : vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 partition Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME partition - Places all of the entities that satisfy the given predicate before all of the entities that do not. SYNOPSIS #include template BidirectionalIterator partition (BidirectionalIterator first, BidirectionalIterator last, Predicate pred); DESCRIPTION The partition algorithm places all the elements in the range [first, last) that satisfy pred before all the elements that do not satisfy pred. It returns an iterator that is one past the end of the group of elements that satisfy pred. In other words, partition returns i such that for any itera- tor j in the range[first, i), pred(*j) == true, and, for any iterator k in the range [i, last), pred(*j) == false. Note that partition does not necessarily maintain the relative order of the elements that match and elements that do not match the predicate. Use the algorithm stable_partition if relative order is important. COMPLEXITY The partition algorithm does at most (last - first)/2 swaps, and applies the predicate exactly last - first times. EXAMPLE // // prtition.cpp // #include #include #include #include // // Create a new predicate from unary_function. // template class is_even : public unary_function { public: bool operator()(const Arg& arg1) { return (arg1 % 2) == 0; } }; int main () { // // Initialize a deque with an array of integers. // int init[10] = { 1,2,3,4,5,6,7,8,9,10 }; deque d1(init+0, init+10); deque d2(init+0, init+10); // // Print out the original values. // cout << "Unpartitioned values: " << ""; copy(d1.begin(), d1.end(), ostream_iterator(cout," ")); cout << endl; // // A partition of the deque according to even/oddness. // partition(d2.begin(), d2.end(), is_even()); // // Output result of partition. // cout << "Partitioned values: " << ""; copy(d2.begin(), d2.end(), ostream_iterator(cout," ")); cout << endl; // // A stable partition of the deque according to even/oddness. // stable_partition(d1.begin(), d1.end(), is_even()); // // Output result of partition. // cout << "Stable partitioned values: " << ""; copy(d1.begin(), d1.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : Unpartitioned values: 1 2 3 4 5 6 7 8 9 10 Partitioned values: 10 2 8 4 6 5 7 3 9 1 Stable partitioned values: 2 4 6 8 10 1 3 5 7 9 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you need to write : deque > instead of : deque SEE ALSO stable_partition STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 permutation Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME permutation - Generate successive permutations of a sequence based on an ordering function. See the entries for next_permutation and prev_permutation. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 pop_heap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME pop_heap - Moves the largest element off the heap. SYNOPSIS template void pop_heap(RandomAccessIterator first, RandomAccessIterator last); template void pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm or a new element added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The pop_heap algorithm uses the less than (<) operator as the default comparison. An alternate comparison operator can be specified. The pop_heap algorithm can be used as part of an operation to remove the largest element from a heap. It assumes that the range [first, last) is a valid heap (i.e., that first is the largest element in the heap or the first element based on the alternate comparison operator). It then swaps the value in the location first with the value in the location last - 1 and makes [first, last -1)back into a heap. You can then access the element in last using the vector or deque back() member function, or remove the element using the pop_back member function. Note that pop_heap does not actually remove the element from the data structure, you must use another function to do that. COMPLEXITY pop_heap performs at most 2 * log(last - first) comparisons. EXAMPLE // // heap_ops.cpp // #include #include #include int main(void) { int d1[4] = {1,2,3,4}; int d2[4] = {1,3,2,4}; // Set up two vectors vector v1(d1,d1 + 4), v2(d2,d2 + 4); // Make heaps make_heap(v1.begin(),v1.end()); make_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Note that x, y and z represent the remaining // values in the container (other than 4). // The definition of the heap and heap operations // does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now sort those heaps sort_heap(v1.begin(),v1.end()); sort_heap(v2.begin(),v2.end(),less()); // v1 = v2 = (1,2,3,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; return 0; } Output : 4 2 3 1 4 3 2 1 3 2 1 4 3 1 2 4 4 3 1 2 4 3 2 1 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you need to write : vector > instead of : vector SEE ALSO make_heap, push_heap, sort_heap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 prev_permutation Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME prev_permutation - Generate successive permutations of a sequence based on an ordering function. SYNOPSIS #include template bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last); template bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last, Compare comp); DESCRIPTION The permutation-generating algorithms (next_permutation and prev_permutation) assume that the set of all permutations of the elements in a sequence is lexicographically sorted with respect to operator< or comp. So, for example, if a sequence includes the integers 1 2 3, that sequence has six permutations, which, in order from first to last, are: 1 2 3 , 1 3 2, 2 1 3, 2 3 1, 3 1 2, and 3 2 1. The prev_permutation algorithm takes a sequence defined by the range [first, last) and transforms it into its previous permutation, if possible. If such a permutation does exist, the algorithm completes the transformation and returns true. If the permutation does not exist, prev_permutation returns false, and transforms the permutation into its "last" permutation (according to the lexicographical ordering defined by either operator <, the default used in the first version of the algorithm, or comp, which is user-supplied in the second version of the algorithm.) For example, if the sequence defined by [first, last) contains the integers 1 2 3 (in that order), there is not a "previous permutation." Therefore, the algorithm transforms the sequence into its last permutation (3 2 1) and returns false. COMPLEXITY At most (last - first)/2 swaps are performed. EXAMPLE // // permute.cpp // #include //for accumulate #include //for vector #include //for less #include int main() { //Initialize a vector using an array of ints int a1[] = {0,0,0,0,1,0,0,0,0,0}; char a2[] = "abcdefghji"; //Create the initial set and copies for permuting vector m1(a1, a1+10); vector prev_m1((size_t)10), next_m1((size_t)10); vector m2(a2, a2+10); vector prev_m2((size_t)10), next_m2((size_t)10); copy(m1.begin(), m1.end(), prev_m1.begin()); copy(m1.begin(), m1.end(), next_m1.begin()); copy(m2.begin(), m2.end(), prev_m2.begin()); copy(m2.begin(), m2.end(), next_m2.begin()); //Create permutations prev_permutation(prev_m1.begin(), prev_m1.end(),less()); next_permutation(next_m1.begin(), next_m1.end(),less()); prev_permutation(prev_m2.begin(), prev_m2.end(),less()); next_permutation(next_m2.begin(), next_m2.end(),less()); //Output results cout << "Example 1: " << endl << " "; cout << "Original values: "; copy(m1.begin(),m1.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous permutation: "; copy(prev_m1.begin(),prev_m1.end(), ostream_iterator(cout," ")); cout << endl<< " "; cout << "Next Permutation: "; copy(next_m1.begin(),next_m1.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "Example 2: " << endl << " "; cout << "Original values: "; copy(m2.begin(),m2.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous Permutation: "; copy(prev_m2.begin(),prev_m2.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Next Permutation: "; copy(next_m2.begin(),next_m2.end(), ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : Example 1: Original values: 0 0 0 0 1 0 0 0 0 0 Previous permutation: 0 0 0 0 0 1 0 0 0 0 Next Permutation: 0 0 0 1 0 0 0 0 0 0 Example 2: Original values: a b c d e f g h j i Previous Permutation: a b c d e f g h i j Next Permutation: a b c d e f g i h j WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO next_permutation STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 push_heap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME push_heap - Places a new element into a heap. SYNOPSIS #include template void push_heap(RandomAccessIterator first, RandomAccessIterator last); template void push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm, or a new element added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The push_heap algorithms uses the less than (<) operator as the default comparison. As with all of the heap manipulation algorithms, an alternate comparison function can be specified. The push_heap algorithm is used to add a new element to the heap. First, a new element for the heap is added to the end of a range. (For example, you can use the vector or deque member function push_back()to add the element to the end of either of those containers.) The push_heap algorithm assumes that the range [first, last - 1) is a valid heap. It then properly posi- tions the element in the location last - 1 into its proper position in the heap, resulting in a heap over the range [first, last). Note that the push_heap algorithm does not place an element into the heap's underlying container. You must user another function to add the element to the end of the container before applying push_heap. COMPLEXITY For push_heap at most log(last - first) comparisons are performed. EXAMPLE // // heap_ops.cpp // #include #include #include int main(void) { int d1[4] = {1,2,3,4}; int d2[4] = {1,3,2,4}; // Set up two vectors vector v1(d1,d1 + 4), v2(d2,d2 + 4); // Make heaps make_heap(v1.begin(),v1.end()); make_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Note that x, y and z represent the remaining // values in the container (other than 4). // The definition of the heap and heap operations // does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now sort those heaps sort_heap(v1.begin(),v1.end()); sort_heap(v2.begin(),v2.end(),less()); // v1 = v2 = (1,2,3,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; return 0; } Output : 4 2 3 1 4 3 2 1 3 2 1 4 3 1 2 4 4 3 1 2 4 3 2 1 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO make_heap, pop_heap, sort_heap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 random_shuffle Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME random_shuffle - Randomly shuffles elements of a collection. SYNOPSIS #include template void random_shuffle (RandomAccessIterator first, RandomAccessIterator last); template void random_shuffle (RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& rand); DESCRIPTION The random_shuffle algorithm shuffles the elements in the range [first, last) with uniform distribution. random_shuffle can take a particular random number generating function object rand , where rand takes a positive argument n of distance type of the RandomAccessIterator and returns a randomly chosen value between 0 and n - 1. COMPLEXITY In the random_shuffle algorithm, (last - first) -1 swaps are done. EXAMPLE // // rndshufl.cpp // #include #include #include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before random_shuffle: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Mix them up with random_shuffle random_shuffle(v.begin(), v.end()); //Print out the mixed up elements cout << "Elements after random_shuffle: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl; return 0; } Output : Elements before random_shuffle: 1 2 3 4 5 6 7 8 9 10 Elements after random_shuffle: 7 9 10 3 2 5 4 8 1 6 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 remove Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME remove - Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends. SYNOPSIS #include template ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& value); DESCRIPTION The remove algorithm eliminates all the elements referred to by iterator i in the range [first, last) for which the following condition holds: *i == value. remove returns an iterator that designates the end of the resulting range. remove is stable, that is, the relative order of the elements that are not removed is the same as their relative order in the original range. remove does not actually reduce the size of the sequence. It actually operates by: 1) copying the values that are to be retained to the front of the sequence, and 2) returning an iterator that describes where the sequence of retained values ends. Elements that are after this iterator are simply the original sequence values, left unchanged. Here's a simple example: Say we want to remove all values of "2" from the following sequence: 354621271 Applying the remove algorithm results in the following sequence: 3546171|XX The vertical bar represents the position of the iterator returned by remove. Note that the elements to the left of the vertical bar are the original sequence with the "2's" removed. If you want to actually delete items from the container, use the following technique: container.erase(remove(first,last,value),container.end()); COMPLEXITY Exactly last1 - first1 applications of the corresponding predicate are done. EXAMPLE // // remove.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator()(const Arg& x){ return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove the 7 vector::iterator result = remove(v.begin(), v.end(), 7); // delete dangling elements from the vector v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove everything beyond the fourth element result = remove_if(v.begin()+4, v.begin()+8, all_true()); // delete dangling elements v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 8 9 10 1 2 3 4 1 2 4 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO remove_if, remove_copy, remove_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 remove_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME remove_copy - Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends. SYNOPSIS #include template OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& value); DESCRIPTION The remove_copy algorithm copies all the elements referred to by the iterator i in the range [first, last) for which the following corresponding condition does not hold: *i == value. remove_copy returns the end of the resulting range. remove_copy is stable, that is, the relative order of the elements in the resulting range is the same as their relative order in the original range. The elements in the original sequence are not altered by remove_copy. COMPLEXITY Exactly last1 - first1 applications of the corresponding predicate are done. EXAMPLE // // remove.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr+0, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove the 7. // vector::iterator result = remove(v.begin(), v.end(), 7); // // Delete dangling elements from the vector. // v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove everything beyond the fourth element. // result = remove_if(v.begin()+4, v.begin()+8, all_true()); // // Delete dangling elements. // v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Now remove all 3s on output. // remove_copy(v.begin(), v.end(), ostream_iterator(cout," "), 3); cout << endl << endl; // // Now remove everything satisfying predicate on output. // Should yield a NULL vector. // remove_copy_if(v.begin(), v.end(), ostream_iterator(cout," "), all_true()); return 0; } Output : 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 8 9 10 1 2 3 4 1 2 4 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO remove, remove_if, remove_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 remove_copy_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME remove_copy_if - Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends. SYNOPSIS #include template OutputIterator remove_copy_if (InputIterator first, InputIterator last, OutputIterator result, Predicate pred); DESCRIPTION The remove_copy_if algorithm copies all the elements referred to by the iterator i in the range [first, last) for which the following condition does not hold: pred(*i) == true. remove_copy_if returns the end of the resulting range. remove_copy_if is stable, that is, the relative order of the elements in the resulting range is the same as their relative order in the original range. COMPLEXITY Exactly last1 - first1 applications of the corresponding predicate are done. EXAMPLE // // remove.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr+0, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove the 7. // vector::iterator result = remove(v.begin(), v.end(), 7); // // Delete dangling elements from the vector. // v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove everything beyond the fourth element. // result = remove_if(v.begin()+4, v.begin()+8, all_true()); // // Delete dangling elements. // v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Now remove all 3s on output. // remove_copy(v.begin(), v.end(), ostream_iterator(cout," "), 3); cout << endl << endl; // // Now remove everything satisfying predicate on output. // Should yield a NULL vector. // remove_copy_if(v.begin(), v.end(), ostream_iterator(cout," "), all_true()); return 0; } Output : 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 8 9 10 1 2 3 4 1 2 4 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO remove, remove_if, remove_copy STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 remove_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME remove_if - Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends. SYNOPSIS #include template ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, Predicate pred); DESCRIPTION The remove_if algorithm eliminates all the elements referred to by iterator i in the range [first, last) for which the following corresponding condition holds: pred(*i) == true. remove_if returns the end of the resulting range. remove_if is stable, that is, the relative order of the elements that are not removed is the same as their relative order in the original range. remove_if does not actually reduce the size of the sequence. It actually operates by: 1) copying the values that are to be retained to the front of the sequence, and 2) returning an iterator that describes where the sequence of retained values ends. Elements that are after this iterator are simply the original sequence values, left unchanged. Here's a simple example: Say we want to remove all even numbers from the following sequence: 123456789 Applying the remove_if algorithm results in the following sequence: 13579|XXXX The vertical bar represents the position of the iterator returned by remove_if. Note that the elements to the left of the vertical bar are the original sequence with the even numbers removed. The elements to the right of the bar are simply the untouched original members of the original sequence. If you want to actually delete items from the container, use the following technique: container.erase(remove(first,last,value),container.end()); COMPLEXITY Exactly last1 - first1 applications of the corresponding predicate are done. EXAMPLE // // remove.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator()(const Arg& x){ return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove the 7 vector::iterator result = remove(v.begin(), v.end(), 7); // delete dangling elements from the vector v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove everything beyond the fourth element result = remove_if(v.begin()+4, v.begin()+8, all_true()); // delete dangling elements v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 8 9 10 1 2 3 4 1 2 4 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO remove, remove_copy, remove_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 replace Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME replace - Substitutes elements stored in a collection with new values. SYNOPSIS #include template void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value); DESCRIPTION The replace algorithm replaces elements referred to by iterator i in the range [first, last) with new_value when the following condition holds: *i == old_value COMPLEXITY Exactly last - first comparisons or applications of the corresponding predicate are done. EXAMPLE // // replace.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator()(const Arg&){ return 1; } }; int main() { //Initialize a vector with an array of integers int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out original vector cout << "The original list: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Replace the number 7 with 11 replace(v.begin(), v.end(), 7, 11); // Print out vector with 7 replaced, // s.b. 1 2 3 4 5 6 11 8 9 10 cout << "List after replace " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Replace 1 2 3 with 13 13 13 replace_if(v.begin(), v.begin()+3, all_true(), 13); // Print out the remaining vector, // s.b. 13 13 13 4 5 6 11 8 9 10 cout << "List after replace_if " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO replace_if, replace_copy, replace_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 replace_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME replace_copy - Substitutes elements stored in a collection with new values. SYNOPSIS #include template OutputIterator replace_copy (InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value); DESCRIPTION The replace_copy algorithm leaves the original sequence intact and places the revised sequence into result. The algorithm compares elements referred to by iterator i in the range [first, last) with old_value. If *i does not equal old_value, then the replace_copy copies *i to result+(first-i). If *i==old_value, then replace_copy copies new_value to result+(first-i). replace_copy returns result+(last-first). COMPLEXITY Exactly last - first comparisons between values are done. EXAMPLE // // replace.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out original vector. // cout << "The original list: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace the number 7 with 11. // replace(v.begin(), v.end(), 7, 11); // // Print out vector with 7 replaced. // cout << "List after replace:" << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace 1 2 3 with 13 13 13. // replace_if(v.begin(), v.begin()+3, all_true(), 13); // // Print out the remaining vector. // cout << "List after replace_if:" << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace those 13s with 17s on output. // cout << "List using replace_copy to cout:" << endl << " "; replace_copy(v.begin(), v.end(), ostream_iterator(cout, " "), 13, 17); cout << endl << endl; // // A simple example of replace_copy_if. // cout << "List w/ all elements output as 19s:" << endl << " "; replace_copy_if(v.begin(), v.end(), ostream_iterator(cout, " "), all_true(), 19); cout << endl; return 0; } Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO replace, replace_if, replace_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 replace_copy_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME replace_copy_if - Substitutes elements stored in a collection with new values. SYNOPSIS #include template OutputIterator replace_copy_if (InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value); DESCRIPTION The replace_copy_if algorithm leaves the original sequence intact and places a revised sequence into result. The algorithm compares each element *i in the range [first,last) with the conditions specified by pred. If pred(*i)==false, replace_copy_if copies *i to result+(first-i). If pred(*i)==true, then replace_copy copies new_value to result+(first-i). replace_copy_if returns result+(last-first). COMPLEXITY Exactly last - first applications of the predicate are performed. EXAMPLE // // replace.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out original vector. // cout << "The original list: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace the number 7 with 11. // replace(v.begin(), v.end(), 7, 11); // // Print out vector with 7 replaced. // cout << "List after replace:" << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace 1 2 3 with 13 13 13. // replace_if(v.begin(), v.begin()+3, all_true(), 13); // // Print out the remaining vector. // cout << "List after replace_if:" << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Replace those 13s with 17s on output. // cout << "List using replace_copy to cout:" << endl << " "; replace_copy(v.begin(), v.end(), ostream_iterator(cout, " "), 13, 17); cout << endl << endl; // // A simple example of replace_copy_if. // cout << "List w/ all elements output as 19s:" << endl << " "; replace_copy_if(v.begin(), v.end(), ostream_iterator(cout, " "), all_true(), 19); cout << endl; return 0; } Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO replace, replace_if, replace_copy STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 replace_if Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME replace_if - Substitutes elements stored in a collection with new values. SYNOPSIS #include template void replace_if (ForwardIterator first, ForwardIterator last, Predicate pred const T& new_value); DESCRIPTION The replace_if algorithm replaces element referred to by iterator i in the range [first, last) with new_value when the following condition holds: pred(*i) == true. COMPLEXITY Exactly last - first applications of the predicate are done. EXAMPLE // // replace.cpp // #include #include #include #include template struct all_true : public unary_function { bool operator()(const Arg&){ return 1; } }; int main() { //Initialize a vector with an array of integers int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out original vector cout << "The original list: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Replace the number 7 with 11 replace(v.begin(), v.end(), 7, 11); // Print out vector with 7 replaced, // s.b. 1 2 3 4 5 6 11 8 9 10 cout << "List after replace " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Replace 1 2 3 with 13 13 13 replace_if(v.begin(), v.begin()+3, all_true(), 13); // Print out the remaining vector, // s.b. 13 13 13 4 5 6 11 8 9 10 cout << "List after replace_if " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; return 0; } Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO replace, replace_copy, replace_copy_if STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 reverse Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME reverse - Reverse the order of elements in a collection. SYNOPSIS #include template void reverse (BidirectionalIterator first, BidirectionalIterator last); DESCRIPTION The algorithm reverse reverses the elements in a sequence so that the last element becomes the new first element, and the first element becomes the new last. For each non-negative integer i <= (last - first)/2 , reverse applies swap to all pairs of iterators first + I, (last - I) - 1. Because the iterators are assumed to be bidirectional, reverse does not return anything. COMPLEXITY reverse performs exactly (last - first)/2 swaps. EXAMPLE // // reverse.cpp // #include #include #include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before reverse: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Reverse the ordering reverse(v.begin(), v.end()); //Print out the reversed elements cout << "Elements after reverse: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl; return 0; } Output : Elements before reverse: 1 2 3 4 5 6 7 8 9 10 Elements after reverse: 10 9 8 7 6 5 4 3 2 1 A reverse_copy to cout: 1 2 3 4 5 6 7 8 9 10 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO reverse_copy, swap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 reverse_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME reverse_copy - Reverse the order of elements in a collection while copying them to a new collecton. SYNOPSIS #include template OutputIterator reverse_copy (BidirectionalIterator first, BidirectionalIterator last, OutputIterator result); DESCRIPTION The reverse_copy algorithm copies the range [first, last) to the range [result, result + (last - first)) such that for any non-negative integer i < (last - first), the following assignment takes place: *(result + (last - first) -i) = *(first + i) reverse_copy returns result + (last - first). The ranges [first, last) and [result, result + (last - first)) must not overlap. COMPLEXITY reverse_copy performs exactly (last - first) assignments. EXAMPLE // // reverse.cpp // #include #include #include int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out elements in original (sorted) order. // cout << "Elements before reverse: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Reverse the ordering. // reverse(v.begin(), v.end()); // // Print out the reversed elements. // cout << "Elements after reverse: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; cout << "A reverse_copy to cout: " << endl << " "; reverse_copy(v.begin(), v.end(), ostream_iterator(cout, " ")); cout << endl; return 0; } Output : Elements before reverse: 1 2 3 4 5 6 7 8 9 10 Elements after reverse: 10 9 8 7 6 5 4 3 2 1 A reverse_copy to cout: 1 2 3 4 5 6 7 8 9 10 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO reverse STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 rotate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME rotate, rotate_copy - Left rotates the order of items in a collection, placing the first item at the end, second item first, etc., until the item pointed to by a specified iterator is the first item in the collection. SYNOPSIS #include template void rotate (ForwardIterator first, ForwardIterator middle, ForwardIterator last); template OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result); DESCRIPTION The rotate algorithm takes three iterator arguments, first, which defines the start of a sequence, last, which defines the end of the sequence, and middle which defines a point within the sequence. rotate "swaps" the segment that contains elements from first through middle-1 with the segment that contains the elements from middle through last. After rotate has been applied, the element that was in position middle, is in position first, and the other elements in that segment are in the same order relative to each other. Similarly, the element that was in position first is now in position last-middle +1. An example will illustrate how rotate works: Say that we have the sequence: 2 4 6 8 1 3 5 If we call rotate with middle = 5, the two segments are 2 4 6 8 and 1 3 5 After we apply rotate, the new sequence will be: 1 3 5 2 4 6 8 Note that the element that was in the fifth position is now in the first position, and the element that was in the first position is in position 4 (last - first + 1, or 8 - 5 +1 =4). The formal description of this algorithms is: for each non-negative integer i < (last - first), rotate places the element from the position first + i into position first + (i + (last - middle)) % (last - first). [first, middle) and [middle, last) are valid ranges. rotate_copy rotates the elements as described above, but instead of swapping elements within the same sequence, it copies the result of the rotation to a container specified by result. rotate_copy copies the range [first, last) to the range [result, result + (last - first)) such that for each non-negative integer i < (last - first) the following assignment takes place: *(result + (i + (last - middle)) % (last -first)) = *(first + i). The ranges [first, last) and [result, result, + (last - first)) may not overlap. COMPLEXITY For rotate at most last - first swaps are performed. For rotate_copy last - first assignments are performed. EXAMPLE // // rotate // #include #include #include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before rotate: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Rotate the elements rotate(v.begin(), v.begin()+4, v.end()); //Print out the rotated elements cout << "Elements after rotate: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl; return 0; } Output : Elements before rotate: 1 2 3 4 5 6 7 8 9 10 Elements after rotate: 5 6 7 8 9 10 1 2 3 4 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 rotate_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME rotate, rotate_copy - Left rotates the order of items in a collection, placing the first item at the end, second item first, etc., until the item pointed to by a specified iterator is the first item in the collection. SYNOPSIS #include template void rotate (ForwardIterator first, ForwardIterator middle, ForwardIterator last); template OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result); DESCRIPTION The rotate algorithm takes three iterator arguments, first, which defines the start of a sequence, last, which defines the end of the sequence, and middle which defines a point within the sequence. rotate "swaps" the segment that contains elements from first through middle-1 with the segment that contains the elements from middle through last. After rotate has been applied, the element that was in position middle, is in position first, and the other elements in that segment are in the same order relative to each other. Similarly, the element that was in position first is now in position last-middle +1. An example will illustrate how rotate works: Say that we have the sequence: 2 4 6 8 1 3 5 If we call rotate with middle = 5, the two segments are 2 4 6 8 and 1 3 5 After we apply rotate, the new sequence will be: 1 3 5 2 4 6 8 Note that the element that was in the fifth position is now in the first position, and the element that was in the first position is in position 4 (last - first + 1, or 8 - 5 +1 =4). The formal description of this algorithms is: for each non-negative integer i < (last - first), rotate places the element from the position first + i into position first + (i + (last - middle)) % (last - first). [first, middle) and [middle, last) are valid ranges. rotate_copy rotates the elements as described above, but instead of swapping elements within the same sequence, it copies the result of the rotation to a container specified by result. rotate_copy copies the range [first, last) to the range [result, result + (last - first)) such that for each non-negative integer i < (last - first) the following assignment takes place: *(result + (i + (last - middle)) % (last -first)) = *(first + i). The ranges [first, last) and [result, result, + (last - first)) may not overlap. COMPLEXITY For rotate at most last - first swaps are performed. For rotate_copy last - first assignments are performed. EXAMPLE // // rotate // #include #include #include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before rotate: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Rotate the elements rotate(v.begin(), v.begin()+4, v.end()); //Print out the rotated elements cout << "Elements after rotate: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl; return 0; } Output : Elements before rotate: 1 2 3 4 5 6 7 8 9 10 Elements after rotate: 5 6 7 8 9 10 1 2 3 4 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 search Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME search, search_n - Finds a sub-sequence within a sequence of values that is element-wise equal to the values in an indicated range. SYNOPSIS #include template ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred); template ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value); template ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred) DESCRIPTION The search and search_n are used for searching for a sub-sequence within a sequence. The search algorithm searches for a sub-sequence [first2, last2) within a sequence [first1, last1), and returns the beginning location of the sub-sequence. If it does not find the sub-sequence, search returns last1. The first version of search uses the equality (==) operator as a default, and the second version allows you to specify a binary predicate to perform the comparison. The search_n algorithm searches for the sub-sequence composed of count occurrences of value within a sequence [first, last), and returns first if this sub-sequence is found. If it does not find the sub-sequence, search_n returns last. The first version of search_n uses the equality (==) operator as a default, and the second version allows you to specify a binary predicate to perform the comparison. COMPLEXITY search performs at most (last1 - first1)*(last2-first2) applications of the corresponding predicate. search_n performs at most (last - first) applications of the corresponding predicate. EXAMPLE // // search.cpp // #include #include #include int main() { // Initialize a list sequence and // sub-sequence with characters char seq[40] = "Here's a string with a substring in it"; char subseq[10] = "substring"; list sequence(seq, seq+39); list subseqnc(subseq, subseq+9); //Print out the original sequence cout << endl << "The sub-sequence, " << subseq << ", was found at the "; cout << endl << "location identified by a '*'" << endl << " "; // Create an iterator to identify the location of // sub-sequence within sequence list::iterator place; //Do search place = search(sequence.begin(), sequence.end(), subseqnc.begin(), subseqnc.end()); //Identify result by marking first character with a '*' *place = '*'; //Output sequence to display result for(list::iterator i = sequence.begin(); i != sequence.end(); i++) cout << *i; cout << endl; return 0; } Output : The sub-sequence, substring, was found at the location identified by a '*' Here's a string with a *substring in it WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : list > instead of : list STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 search_n Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME search, search_n - Finds a sub-sequence within a sequence of values that is element-wise equal to the values in an indicated range. SYNOPSIS #include template ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred); template ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value); template ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred) DESCRIPTION The search and search_n are used for searching for a sub-sequence within a sequence. The search algorithm searches for a sub-sequence [first2, last2) within a sequence [first1, last1), and returns the beginning location of the sub-sequence. If it does not find the sub-sequence, search returns last1. The first version of search uses the equality (==) operator as a default, and the second version allows you to specify a binary predicate to perform the comparison. The search_n algorithm searches for the sub-sequence composed of count occurrences of value within a sequence [first, last), and returns first if this sub-sequence is found. If it does not find the sub-sequence, search_n returns last. The first version of search_n uses the equality (==) operator as a default, and the second version allows you to specify a binary predicate to perform the comparison. COMPLEXITY search performs at most (last1 - first1)*(last2-first2) applications of the corresponding predicate. search_n performs at most (last - first) applications of the corresponding predicate. EXAMPLE // // search.cpp // #include #include #include int main() { // Initialize a list sequence and // sub-sequence with characters char seq[40] = "Here's a string with a substring in it"; char subseq[10] = "substring"; list sequence(seq, seq+39); list subseqnc(subseq, subseq+9); //Print out the original sequence cout << endl << "The sub-sequence, " << subseq << ", was found at the "; cout << endl << "location identified by a '*'" << endl << " "; // Create an iterator to identify the location of // sub-sequence within sequence list::iterator place; //Do search place = search(sequence.begin(), sequence.end(), subseqnc.begin(), subseqnc.end()); //Identify result by marking first character with a '*' *place = '*'; //Output sequence to display result for(list::iterator i = sequence.begin(); i != sequence.end(); i++) cout << *i; cout << endl; return 0; } Output : The sub-sequence, substring, was found at the location identified by a '*' Here's a string with a *substring in it WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : list > instead of : list STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 set_difference Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME set_difference - Basic set operation for sorted sequences. SYNOPSIS #include template OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); DESCRIPTION The set_difference algorithm constructs a sorted difference that includes copies of the elements that are present in the range [first1, last1) but are not present in the range [first2, last2). It returns the end of the constructed range. As an example, assume we have the following two sets: 1 2 3 4 5 and 3 4 5 6 7 The result of applying set_difference is the set: 1 2 The result of set_difference is undefined if the result range overlaps with either of the original ranges. set_difference assumes that the ranges are sorted using the default comparison operator less than (<), unless an alternative comparison operator (comp) is provided. Use the set_symetric_difference algorithm to return a result that contains all elements that are not in common between the two sets. COMPLEXITY At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. EXAMPLE // // set_diff.cpp // #include #include #include int main() { //Initialize some sets int a1[10] = {1,2,3,4,5,6,7,8,9,10}; int a2[6] = {2,4,6,8,10,12}; set > all(a1, a1+10), even(a2, a2+6), odd; //Create an insert_iterator for odd insert_iterator > > odd_ins(odd, odd.begin()); //Demonstrate set_difference cout << "The result of:" << endl << "{"; copy(all.begin(),all.end(), ostream_iterator(cout," ")); cout << "} - {"; copy(even.begin(),even.end(), ostream_iterator(cout," ")); cout << "} =" << endl << "{"; set_difference(all.begin(), all.end(), even.begin(), even.end(), odd_ins); copy(odd.begin(),odd.end(), ostream_iterator(cout," ")); cout << "}" << endl << endl; return 0; } Output : The result of: {1 2 3 4 5 6 7 8 9 10 } - {2 4 6 8 10 12 } = {1 3 5 7 9 } WARNING If your compiler does not support default template parameters, then you need to always supply the Compare template argument and the Allocator template argument. For instance, you will need to write : set allocator > instead of : set SEE ALSO includes, set, set_union, set_intersection, set_symmetric_difference STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 set_intersection Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME set_intersection - Basic set operation for sorted sequences. SYNOPSIS #include template OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator last2, OutputIterator result); template OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); DESCRIPTION The set_intersection algorithm constructs a sorted intersection of elements from the two ranges. It returns the end of the constructed range. When it finds an element present in both ranges, set_intersection always copies the element from the first range into result. This means that the result of set_intersection is guaranteed to be stable. The result of set_intersection is undefined if the result range overlaps with either of the original ranges. set_intersection assumes that the ranges are sorted using the default comparison operator less than (<), unless an alternative comparison operator (comp) is provided. COMPLEXITY At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are per- formed. EXAMPLE // // set_intr.cpp // #include #include #include int main() { //Initialize some sets int a1[10] = {1,3,5,7,9,11}; int a3[4] = {3,5,7,8}; set > odd(a1, a1+6), result, small(a3,a3+4); //Create an insert_iterator for result insert_iterator > > res_ins(result, result.begin()); //Demonstrate set_intersection cout << "The result of:" << endl << "{"; copy(small.begin(),small.end(), ostream_iterator(cout," ")); cout << "} intersection {"; copy(odd.begin(),odd.end(), ostream_iterator(cout," ")); cout << "} =" << endl << "{"; set_intersection(small.begin(), small.end(), odd.begin(), odd.end(), res_ins); copy(result.begin(),result.end(), ostream_iterator(cout," ")); cout << "}" << endl << endl; return 0; } Output : The result of: {3 5 7 8 } intersection {1 3 5 7 9 11 } = {3 5 7 } WARNING If your compiler does not support default template parameters, then you need to always supply the Compare template argument and the Allocator template argument. For instance, you will need to write : set allocator > instead of : set SEE ALSO includes, set, set_union, set_difference, set_symmetric_difference STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 set_symmetric_difference Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME set_symmetric_difference - Basic set operation for sorted sequences. SYNOPSIS #include template OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); DESCRIPTION set_symmetric_difference constructs a sorted symmetric difference of the elements from the two ranges. This means that the constructed range includes copies of the elements that are present in the range [first1, last1) but not present in the range [first2, last2)and copies of the elements that are present in the range [first2, last2) but not in the range [first1, last1). It returns the end of the constructed range. For example, suppose we have two sets: 1 2 3 4 5 and 3 4 5 6 7 The set_symmetric_difference of these two sets is: 1 2 6 7 The result of set_symmetric_difference is undefined if the result range overlaps with either of the original ranges. set_symmetric_difference assumes that the ranges are sorted using the default comparison operator less than (<), unless an alternative comparison operator (comp) is provided. Use the set_symmetric_difference algorithm to return a result that includes elements that are present in the first set and not in the second. COMPLEXITY At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. EXAMPLE // // set_s_di.cpp // #include #include #include int main() { //Initialize some sets int a1[] = {1,3,5,7,9,11}; int a3[] = {3,5,7,8}; set > odd(a1,a1+6), result, small(a3,a3+4); //Create an insert_iterator for result insert_iterator > > res_ins(result, result.begin()); //Demonstrate set_symmetric_difference cout << "The symmetric difference of:" << endl << "{"; copy(small.begin(),small.end(), ostream_iterator(cout," ")); cout << "} with {"; copy(odd.begin(),odd.end(), ostream_iterator(cout," ")); cout << "} =" << endl << "{"; set_symmetric_difference(small.begin(), small.end(), odd.begin(), odd.end(), res_ins); copy(result.begin(),result.end(), ostream_iterator(cout," ")); cout << "}" << endl << endl; return 0; } Output : The symmetric difference of: {3 5 7 8 } with {1 3 5 7 9 11 } = {1 8 9 11 } WARNING If your compiler does not support default template parameters, then you need to always supply the Compare template argument and the Allocator template argument. For instance, you will need to write : set, allocator > instead of : set SEE ALSO includes, set, set_union, set_intersection, set_difference STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 set_union Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME set_union - Basic set operation for sorted sequences. SYNOPSIS #include template OutputIterator set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); DESCRIPTION The set_union algorithm constructs a sorted union of the elements from the two ranges. It returns the end of the constructed range. set_union is stable, that is, if an element is present in both ranges, the one from the first range is copied. The result of set_union is undefined if the result range overlaps with either of the original ranges. Note that set_union does not merge the two sorted sequences. If an element is present in both sequences, only the element from the first sequence is copied to result. (Use the merge algorithm to create an ordered merge of two sorted sequences that contains all the elements from both sequences.) set_union assumes that the sequences are sorted using the default comparison operator less than (<), unless an alternative comparison operator (comp) is provided. COMPLEXITY At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. EXAMPLE // // set_unin.cpp // #include #include #include int main() { //Initialize some sets int a2[6] = {2,4,6,8,10,12}; int a3[4] = {3,5,7,8}; set > even(a2, a2+6), result, small(a3,a3+4); //Create an insert_iterator for result insert_iterator > > res_ins(result, result.begin()); //Demonstrate set_union cout << "The result of:" << endl << "{"; copy(small.begin(),small.end(), ostream_iterator(cout," ")); cout << "} union {"; copy(even.begin(),even.end(), ostream_iterator(cout," ")); cout << "} =" << endl << "{"; set_union(small.begin(), small.end(), even.begin(), even.end(), res_ins); copy(result.begin(),result.end(), ostream_iterator(cout," ")); cout << "}" << endl << endl; return 0; } Output : The result of: {3 5 7 8 } union {2 4 6 8 10 12 } = {2 3 4 5 6 7 8 10 12 } WARNING If your compiler does not support default template parameters, then you need to always supply the Compare template argument and the Allocator template argument. For instance, you will need to write : set, allocator > instead of : set SEE ALSO includes, set, set_intersection, set_difference, set_symmetric_difference STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 sort Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME sort - Templated algorithm for sorting collections of entities. SYNOPSIS #include template void sort (RandomAccessIterator first, RandomAccessIterator last); template void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION The sort algorithm sorts the elements in the range [first, last) using either the less than (<) operator or the comparison operator comp. If the worst case behavior is important stable_sort or partial_sort should be used. COMPLEXITY sort performs approximately NlogN, where N equals last - first, comparis- ons on the average. EXAMPLE // // sort.cpp // #include #include #include #include struct associate { int num; char chr; associate(int n, char c) : num(n), chr(c){}; associate() : num(0), chr(' '){}; }; bool operator<(const associate &x, const associate &y) { return x.num < y.num; } ostream& operator<<(ostream &s, const associate &x) { return s << "<" << x.num << ";" << x.chr << ">"; } int main () { vector::iterator i, j, k; associate arr[20] = {associate(-4, ' '), associate(16, ' '), associate(17, ' '), associate(-3, 's'), associate(14, ' '), associate(-6, ' '), associate(-1, ' '), associate(-3, 't'), associate(23, ' '), associate(-3, 'a'), associate(-2, ' '), associate(-7, ' '), associate(-3, 'b'), associate(-8, ' '), associate(11, ' '), associate(-3, 'l'), associate(15, ' '), associate(-5, ' '), associate(-3, 'e'), associate(15, ' ')}; // Set up vectors vector v(arr, arr+20), v1((size_t)20), v2((size_t)20); // Copy original vector to vectors #1 and #2 copy(v.begin(), v.end(), v1.begin()); copy(v.begin(), v.end(), v2.begin()); // Sort vector #1 sort(v1.begin(), v1.end()); // Stable sort vector #2 stable_sort(v2.begin(), v2.end()); // Display the results cout << "Original sort stable_sort" << endl; for(i = v.begin(), j = v1.begin(), k = v2.begin(); i != v.end(); i++, j++, k++) cout << *i << " " << *j << " " << *k << endl; return 0; } Output : Original sort stable_sort <-4; > <-8; > <-8; > <16; > <-7; > <-7; > <17; > <-6; > <-6; > <-3;s> <-5; > <-5; > <14; > <-4; > <-4; > <-6; > <-3;e> <-3;s> <-1; > <-3;s> <-3;t> <-3;t> <-3;l> <-3;a> <23; > <-3;t> <-3;b> <-3;a> <-3;b> <-3;l> <-2; > <-3;a> <-3;e> <-7; > <-2; > <-2; > <-3;b> <-1; > <-1; > <-8; > <11; > <11; > <11; > <14; > <14; > <-3;l> <15; > <15; > <15; > <15; > <15; > <-5; > <16; > <16; > <-3;e> <17; > <17; > <15; > <23; > <23; > WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO stable_sort, partial_sort, partial_sort_copy STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 sort_heap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME sort_heap - Converts a heap into a sorted collection. SYNOPSIS #include template void sort_heap(RandomAccessIterator first, RandomAccessIterator last); template void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by pop_heap(), or a new element added by push_heap(), in O(logN) time. These properties make heaps useful as priority queues. The sort_heap algorithm converts a heap into a sorted collection over the range [first, last) using either the default operator (<) or the comparison function supplied with the algorithm. Note that sort_heap is not stable, i.e., the elements may not be in the same relative order after sort_heap is applied. COMPLEXITY sort_heap performs at most NlogN comparisons where N is equal to last - first. EXAMPLE // // heap_ops.cpp // #include #include #include int main(void) { int d1[4] = {1,2,3,4}; int d2[4] = {1,3,2,4}; // Set up two vectors vector v1(d1,d1 + 4), v2(d2,d2 + 4); // Make heaps make_heap(v1.begin(),v1.end()); make_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Note that x, y and z represent the remaining // values in the container (other than 4). // The definition of the heap and heap operations // does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now sort those heaps sort_heap(v1.begin(),v1.end()); sort_heap(v2.begin(),v2.end(),less()); // v1 = v2 = (1,2,3,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; return 0; } Output : 4 2 3 1 4 3 2 1 3 2 1 4 3 1 2 4 4 3 1 2 4 3 2 1 1 2 3 4 1 2 3 4 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO make_heap, pop_heap, push_heap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 stable_partition Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME stable_partition - Places all of the entities that satisfy the given predicate before all of the entities that do not, while maintaining the relative order of elements in each group. SYNOPSIS #include template BidirectionalIterator stable_partition (BidirectionalIterator first, BidirectionalIterator last, Predicate pred); DESCRIPTION The stable_partition algorithm places all the elements in the range [first, last) that satisfy pred before all the elements that do not satisfy it. It returns an iterator i that is one past the end of the group of elements that satisfy pred. In other words stable_partition returns i such that for any iterator j in the range [first, i), pred(*j) == true, and for any iterator k in the range [i, last), pred(*j) == false. The relative order of the elements in both groups is preserved. The partition algorithm can be used when it is not necessary to maintain the relative order of elements within the groups that do and do not match the predicate. COMPLEXITY The stable_partition algorithm does at most (last - first) * log(last - first) swaps. and applies the predicate exactly last - first times. EXAMPLE // // prtition.cpp // #include #include #include #include //Create a new predicate from unary_function template class is_even : public unary_function { public: bool operator()(const Arg& arg1) { return (arg1 % 2) == 0; } }; int main() { //Initialize a deque with an array of ints int init[10] = {1,2,3,4,5,6,7,8,9,10}; deque d(init, init+10); //Print out the original values cout << "Unpartitioned values: " << endl << " "; copy(d.begin(),d.end(),ostream_iterator(cout," ")); cout << endl << endl; //Partition the deque according to even/oddness stable_partition(d.begin(), d.end(), is_even()); //Output result of partition cout << "Partitioned values: " << endl << " "; copy(d.begin(),d.end(),ostream_iterator(cout," ")); return 0; } Output : Unpartitioned values: 1 2 3 4 5 6 7 8 9 10 Partitioned values: 10 2 8 4 6 5 7 3 9 1 Stable partitioned values: 2 4 6 8 10 1 3 5 7 9 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : deque > instead of : deque SEE ALSO partition STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 stable_sort Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME stable_sort - Templated algorithm for sorting collections of entities. SYNOPSIS #include template void stable_sort (RandomAccessIterator first, RandomAccessIterator last); template void stable_sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); DESCRIPTION The stable_sort algorithm sorts the elements in the range [first, last). The first version of the algorithm uses less than (<) as the comparison operator for the sort. The second version uses the comparison function comp. The stable_sort algorithm is considered stable because the relative order of the equal elements is preserved. COMPLEXITY stable_sort does at most N(logN) **2, where N equals last -first, comparisons; if enough extra memory is available, it is NlogN. EXAMPLE // // sort.cpp // #include #include #include #include struct associate { int num; char chr; associate(int n, char c) : num(n), chr(c){}; associate() : num(0), chr(' '){}; }; bool operator<(const associate &x, const associate &y) { return x.num < y.num; } ostream& operator<<(ostream &s, const associate &x) { return s << "<" << x.num << ";" << x.chr << ">"; } int main () { vector::iterator i, j, k; associate arr[20] = {associate(-4, ' '), associate(16, ' '), associate(17, ' '), associate(-3, 's'), associate(14, ' '), associate(-6, ' '), associate(-1, ' '), associate(-3, 't'), associate(23, ' '), associate(-3, 'a'), associate(-2, ' '), associate(-7, ' '), associate(-3, 'b'), associate(-8, ' '), associate(11, ' '), associate(-3, 'l'), associate(15, ' '), associate(-5, ' '), associate(-3, 'e'), associate(15, ' ')}; // Set up vectors vector v(arr, arr+20), v1((size_t)20), v2((size_t)20); // Copy original vector to vectors #1 and #2 copy(v.begin(), v.end(), v1.begin()); copy(v.begin(), v.end(), v2.begin()); // Sort vector #1 sort(v1.begin(), v1.end()); // Stable sort vector #2 stable_sort(v2.begin(), v2.end()); // Display the results cout << "Original sort stable_sort" << endl; for(i = v.begin(), j = v1.begin(), k = v2.begin(); i != v.end(); i++, j++, k++) cout << *i << " " << *j << " " << *k << endl; return 0; } Output : Original sort stable_sort <-4; > <-8; > <-8; > <16; > <-7; > <-7; > <17; > <-6; > <-6; > <-3;s> <-5; > <-5; > <14; > <-4; > <-4; > <-6; > <-3;e> <-3;s> <-1; > <-3;s> <-3;t> <-3;t> <-3;l> <-3;a> <23; > <-3;t> <-3;b> <-3;a> <-3;b> <-3;l> <-2; > <-3;a> <-3;e> <-7; > <-2; > <-2; > <-3;b> <-1; > <-1; > <-8; > <11; > <11; > <11; > <14; > <14; > <-3;l> <15; > <15; > <15; > <15; > <15; > <-5; > <16; > <16; > <-3;e> <17; > <17; > <15; > <23; > <23; > WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector instead of : vector SEE ALSO sort, partial_sort, partial_sort_copy STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 swap Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME swap - Exchange values. SYNOPSIS #include template void swap (T& a, T& b); DESCRIPTION The swap algorithm exchanges the values of a and b. The effect is: T tmp = a a = b b = tmp SEE ALSO iter_swap, swap_ranges STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 swap_ranges Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME swap_ranges - Exchange a range of values in one location with those in another SYNOPSIS #include template ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2); DESCRIPTION The swap_ranges algorithm exchanges corresponding values in two ranges, in the following manner: For each non-negative integer n < (last - first) the function exchanges *(first1 + n) with *(first2 + n)). After completing all exchanges, swap_ranges returns an iterator that points to the end of the second container, i.e., first2 + (last1 -first1). The result of swap_ranges is undefined if the two ranges [first, last) and [first2, first2 + (last1 - first1)) overlap. EXAMPLE // // swap.cpp // #include #include int main() { int d1[] = {6, 7, 8, 9, 10, 1, 2, 3, 4, 5}; // Set up a vector vector v(d1,d1 + 10); // Output original vector cout << "For the vector: "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); // Swap the first five elements with the last five elements swap_ranges(v.begin(),v.begin()+5, v.begin()+5); // Output result cout << endl << endl << "Swapping the first five elements " << "with the last five gives: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); return 0; } Output : For the vector: 6 7 8 9 10 1 2 3 4 5 Swapping the first five elements with the last five gives: 1 2 3 4 5 6 7 8 9 10 Swapping the first and last elements gives: 10 2 3 4 5 6 7 8 9 1 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO iter_swap, swap STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 transform Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME transform - Applies an operation to a range of values in a collection and stores the result. SYNOPSIS #include template OutputIterator transform (InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op); template OutputIterator transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op); DESCRIPTION The transform algorithm has two forms. The first form applies unary operation op to each element of the range [first, last), and sends the result to the output iterator result. For example, this version of transform, could be used to square each element in a vector. If the output iterator (result) is the same as the input iterator used to traverse the range, transform, performs its transformation in place. The second form of transform applies a binary operation, binary_op, to corresponding elements in the range [first1, last1) and the range that begins at first2, and sends the result to result. For example, transform can be used to add corresponding elements in two sequences, and store the set of sums in a third. The algorithm assumes, but does not check, that the second sequence has at least as many elements as the first sequence. Note that the output iterator result can be a third sequence, or either of the two input sequences. Formally, transform assigns through every iterator i in the range [result, result + (last1 - first1)) a new corresponding value equal to: op(*(first1 + (i - result)) or binary_op(*(first1 + (i - result), *(first2 + (i - result))) transform returns result + (last1 - first1). op and binary_op must not have any side effects. result may be equal to first in case of unary transform, or to first1 or first2 in case of binary transform. COMPLEXITY Exactly last1 - first1 applications of op or binary_op are performed. EXAMPLE // // trnsform.cpp // #include #include #include #include #include int main() { //Initialize a deque with an array of ints int arr1[5] = {99, 264, 126, 330, 132}; int arr2[5] = {280, 105, 220, 84, 210}; deque d1(arr1, arr1+5), d2(arr2, arr2+5); //Print the original values cout << "The following pairs of numbers: " << endl << " "; deque::iterator i1; for(i1 = d1.begin(); i1 != d1.end(); i1++) cout << setw(6) << *i1 << " "; cout << endl << " "; for(i1 = d2.begin(); i1 != d2.end(); i1++) cout << setw(6) << *i1 << " "; // Transform the numbers in the deque to their // factorials and store in the vector transform(d1.begin(), d1.end(), d2.begin(), d1.begin(), multiplies()); //Display the results cout << endl << endl; cout << "Have the products: " << endl << " "; for(i1 = d1.begin(); i1 != d1.end(); i1++) cout << setw(6) << *i1 << " "; return 0; } Output : The following pairs of numbers: 99 264 126 330 132 280 105 220 84 210 Have the products: 27720 27720 27720 27720 27720 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : deque > instead of: deque STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 uninitialized_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME uninitialized_copy - An algorithms that uses construct to copy values from one range to another location. SYNOPSIS #include template ForwardIterator uninitialized_copy (InputIterator first, InputIterator last, ForwardIterator result); DESCRIPTION uninitialized_copy copies all items in the range [first, last) into the location beginning at result using the construct algorithm. SEE ALSO construct STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 uninitialized_fill Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME uninitialized_fill - Algorithm that uses the construct algorithm for setting values in a collection. SYNOPSIS #include template void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x); DESCRIPTION uninitialized_fill initializes all of the items in the range [first, last) to the value x, using the construct algorithm. SEE ALSO construct, uninitialized_fill_n STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 uninitialized_fill_n Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME uninitialized_fill_n - Algorithm that uses the construct algorithm for setting values in a collection. SYNOPSIS #include template void uninitialized_fill_n (ForwardIterator first, Size n, const T& x); DESCRIPTION unitialized_fill_n starts at the iterator first and initializes the first n items to the value x, using the construct algorithm. SEE ALSO construct, uninitialized_fill STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 unique Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME unique, unique_copy - Removes consecutive duplicates from a range of values and places the resulting unique values into the result. SYNOPSIS #include template ForwardIterator unique (ForwardIterator first, ForwardIterator last); template ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred); template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result); template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred); DESCRIPTION The unique algorithm moves through a sequence and eliminates all but the first element from every consecutive group of equal elements. There are two versions of the algorithm, one tests for equality, and the other tests whether a binary predicate applied to adjacent elements is true. An element is unique if it does not meet the corresponding condition listed here: *i == *(i - 1) or binary_pred(*i, *(i - 1)) == true. If an element is unique, it is copied to the front of the sequence, overwriting the existing elements. Once all unique elements have been identified. The remainder of the sequence is left unchanged, and unique returns the end of the resulting range. The unique_copy algorithm copies the first element from every consecutive group of equal elements, to an OutputIterator. The unique_copy algorithm, also has two versions--one that tests for equality and a second that tests adjacent elements against a binary predicate. unique_copy returns the end of the resulting range. COMPLEXITY Exactly (last - first) - 1 applications of the corresponding predicate are performed. EXAMPLE // // unique.cpp // #include #include #include int main() { //Initialize two vectors int a1[20] = {4, 5, 5, 9, -1, -1, -1, 3, 7, 5, 5, 5, 6, 7, 7, 7, 4, 2, 1, 1}; vector v(a1, a1+20), result; //Create an insert_iterator for results insert_iterator > ins(result, result.begin()); //Demonstrate includes cout << "The vector: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); //Find the unique elements unique_copy(v.begin(), v.end(), ins); //Display the results cout << endl << endl << "Has the following unique elements:" << endl << " "; copy(result.begin(),result.end(), ostream_iterator(cout," ")); return 0; } Output : The vector: 4 5 5 9 -1 -1 -1 3 7 5 5 5 6 7 7 7 4 2 1 1 Has the following unique elements: 4 5 9 -1 3 7 5 6 7 4 2 1 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 unique_copy Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME unique, unique_copy - Removes consecutive duplicates from a range of values and places the resulting unique values into the result. SYNOPSIS #include template ForwardIterator unique (ForwardIterator first, ForwardIterator last); template ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred); template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result); template OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred); DESCRIPTION The unique algorithm moves through a sequence and eliminates all but the first element from every consecutive group of equal elements. There are two versions of the algorithm, one tests for equality, and the other tests whether a binary predicate applied to adjacent elements is true. An element is unique if it does not meet the corresponding condition listed here: *i == *(i - 1) or binary_pred(*i, *(i - 1)) == true. If an element is unique, it is copied to the front of the sequence, overwriting the existing elements. Once all unique elements have been identified. The remainder of the sequence is left unchanged, and unique returns the end of the resulting range. The unique_copy algorithm copies the first element from every consecutive group of equal elements, to an OutputIterator. The unique_copy algorithm, also has two versions--one that tests for equality and a second that tests adjacent elements against a binary predicate. unique_copy returns the end of the resulting range. COMPLEXITY Exactly (last - first) - 1 applications of the corresponding predicate are performed. EXAMPLE // // unique.cpp // #include #include #include int main() { //Initialize two vectors int a1[20] = {4, 5, 5, 9, -1, -1, -1, 3, 7, 5, 5, 5, 6, 7, 7, 7, 4, 2, 1, 1}; vector v(a1, a1+20), result; //Create an insert_iterator for results insert_iterator > ins(result, result.begin()); //Demonstrate includes cout << "The vector: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); //Find the unique elements unique_copy(v.begin(), v.end(), ins); //Display the results cout << endl << endl << "Has the following unique elements:" << endl << " "; copy(result.begin(),result.end(), ostream_iterator(cout," ")); return 0; } Output : The vector: 4 5 5 9 -1 -1 -1 3 7 5 5 5 6 7 7 7 4 2 1 1 Has the following unique elements: 4 5 9 -1 3 7 5 6 7 4 2 1 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of: vector STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 upper_bound Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME upper_bound - Determines the last valid position for a value in a sorted container. SYNOPSIS #include template ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value); template ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); DESCRIPTION The upper_bound algorithm is part of a set of binary search algorithms. All of these algorithms perform binary searches on ordered containers. Each algorithm has two versions. The first version uses the less than operator (operator<) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version allows you to include a function object of type Compare, and assumes that Compare is the function used to sort the sequence. The function object must be a binary predicate. The upper_bound algorithm finds the last position in a container that value can occupy without violating the container's ordering. upper_bound's return value is the iterator for the first element in the container that is greater than value, or, when the comparison operator is used, the first element that does not satisfy the comparison function. Because the algorithm is restricted to using the less than operator or the user-defined function to perform the search, upper_bound returns an iterator i in the range [first, last) such that for any iterator j in the range [first, i) the appropriate version of the following conditions holds: !(value < *j) or comp(value, *j) == false COMPLEXITY upper_bound performs at most log(last - first) + 1 comparisons. EXAMPLE // // ul_bound.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[11] = {0,1,2,2,3,4,2,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 11); // Try lower_bound variants iterator it1 = lower_bound(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4 iterator it2 = lower_bound(v1.begin(),v1.end(),2,less()); // it2 = v1.begin() + 4 // Try upper_bound variants iterator it3 = upper_bound(v1.begin(),v1.end(),3); // it3 = vector + 5 iterator it4 = upper_bound(v1.begin(),v1.end(),2,less()); // it4 = v1.begin() + 5 cout << endl << endl << "The upper and lower bounds of 3: ( " << *it1 << " , " << *it3 << " ]" << endl; cout << endl << endl << "The upper and lower bounds of 2: ( " << *it2 << " , " << *it4 << " ]" << endl; return 0; } Output : The upper and lower bounds of 3: ( 3 , 4 ] The upper and lower bounds of 2: ( 2 , 3 ] WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO lower_bound, equal_range STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Iterators - Pointer generalizations for traversal and modification of collections. DESCRIPTION Input Iterator Output Iterator read only write only forward moving forward moving | | | | -------------------------------- | | Forward Iterator read and write forward moving | | Bidirectional Iterator read and write moves forward or backward | | Random Access Iterator read and write random access Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. The illustration below displays the five iterator categories defined by the standard library, and shows their hierarchical relationship. Because standard library iterator categories are hierarchical, each category includes all the requirements of the categories above it. Because iterators are used to traverse and access containers, the nature of the container determines what type of iterator it generates. And, because algorithms require specific iterator types as arguments, it is iterators that, for the most part, determine which standard library algorithms can be used with which standard library containers. To conform to the C++ standard, all container and sequence classes must provide their own iterators. An instance of a container or sequence's iterator may be declared using either of the following: class name ::iterator class name ::const_iterator Containers and sequences must also provide const iterators to the beginning and end of their collections. These may be accessed using the class members, begin() and end(). The semantics of iterators are a generalization of the semantics of C++ pointers. Every template function that takes iterators will work using C++ pointers for processing typed contiguous memory sequences. Iterators may be constant or mutable depending upon whether the result of the operator* behaves as a reference or as a reference to a constant. Constant iterators cannot satisfy the requirements of an output_iterator. Every iterator type guarantees that there is an iterator value that points past the last element of a corresponding container. This value is called the past-the-end value. No guarantee is made that this value is dereferencable. Every function provided by an iterator is required to be realized in amortized constant time. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator requirements listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR INPUT ITERATORS The following expressions must be valid for input iterators: X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool *a a == b implies *a == *b a->m equivalent to (*a).m ++r returns X& r++ return value convertible to const X& *r++ returns type T For input iterators, a == b does not imply that ++a == ++b. Algorithms using input iterators should be single pass algorithms. That is they should not pass through the same iterator twice. The value of type T does not have to be an lvalue. REQUIREMENTS FOR OUTPUT ITERATORS The following expressions must be valid for output iterators: X(a) copy constructor, a == X(a) X u(a) copy constructor, u == a X u = a assignment, u == a *a = t result is not used ++r returns X& r++ return value convertible to const X& *r++ = t result is not used The only valid use for the operator* is on the left hand side of the assignment statement. Algorithms using output iterators should be single pass algorithms. That is they should not pass through the same iterator twice. REQUIREMENTS FOR FORWARD ITERATORS The following expressions must be valid for forward iterators: X u u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a) X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool *a return value convertible to T& a->m equivalent to (*a).m ++r returns X& r++ return value convertible to const X& *r++ returns T& Forward iterators have the condition that a == b implies *a== *b. There are no restrictions on the number of passes an algorithm may make through the structure. REQUIREMENTS FOR BIDIRECTIONAL ITERATORS A bidirectional iterator must meet all the requirements for forward iterators. In addition, the following expressions must be valid: --r returns X& r-- return value convertible to const X& *r-- returns T& REQUIREMENTS FOR RANDOM ACCESS ITERATORS A random access iterator must meet all the requirements for bidirectional iterators. In addition, the following expressions must be valid: r += n Semantics of --r or ++r n times depending on the sign of n a + n, n + a returns type X r -= n returns X&, behaves as r += -n a - n returns type X b - a returns Distance a[n] *(a+n), return value convertible to T a < b total ordering relation a > b total ordering relation opposite to < a <= b !(a > b) a >= b !(a < b) All relational operators return a value convertible to bool. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME iterator - Base iterator class. SYNOPSIS #include template struct iterator { typedef T value_type; typedef Distance distance_type; typedef Category iterator_category; }; DESCRIPTION The iterator structure provides a base class from which all other iterator types can be derived. This structure defines an interface that consists of three public types: value_type, distance_type, and iterator_category. These types are used primarily by classes derived from iterator and by the iterator_traits class. See the iterators section in the Class Reference for a description of iterators and the capabilities associated with various types. SEE ALSO iterator_traits STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 iterator_category Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME iterator_category - Determines the category that an iterator belongs to. This function is now obsolete. It is retained in order to provide backward compatibility and support compilers that do not provide partial specialization. SYNOPSIS #include template inline input_iterator_tag iterator_category (const input_iterator&) inline output_iterator_tag iterator_category (const output_iterator&) template inline forward_iterator_tag iterator_category (const forward_iterator&) template inline bidirectional_iterator_tag iterator_category (const bidirectional_iterator&) template inline random_access_iterator_tag iterator_category (const random_access_iterator&) template inline random_access_iterator_tag iterator_category (const T*) DESCRIPTION The iterator_category family of function templates allows you to determine the category that any iterator belongs to. The first five functions take an iterator of a specific type and return the tag for that type. The last takes a T* and returns random_access_iterator_tag. TAG TYPES input_iterator_tag output_iterator_tag forward_iterator_tag bidirectional_iterator_tag random_access_iterator_tag The iterator_category function is particularly useful for improving the efficiency of algorithms. An algorithm can use this function to select the most efficient implementation an iterator is capable of handling without sacrificing the ability to work with a wide range of iterator types. For instance, both the advance and distance primitives use iterator_category to maximize their efficiency by using the tag returned from iterator_category to select from one of several different auxiliary functions. Because this is a compile time selection, use of this primitive incurs no significant runtime overhead. iterator_category is typically used like this: template void foo(Iterator first, Iterator last) { __foo(begin,end,iterator_category(first)); } template void __foo(Iterator first, Iterator last, input_iterator_tag> { // Most general implementation } template void __foo(Iterator first, Iterator last, bidirectional_iterator_tag> { // Implementation takes advantage of bi-diretional // capability of the iterators } _etc. See the iterator section in the Class Reference for a description of iterators and the capabilities associated with each type of iterator tag. SEE ALSO Other iterator primitives: value_type, distance_type, distance,advance, iterator STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 iterator_traits Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME iterator_traits - Provides basic information about an iterator. SYNOPSIS template struct iterator_traits { typedef Iterator::value_type value_type; typedef Iterator::distance_type distance_type; typedef Iterator::iterator::category iterator_category; }; // Specialization template struct iterator_traits { typedef T value_type; typedef Distance ptrdiff_t; typedef Category random_access_iterator_tag; }; DESCRIPTION The iterator_traits template and specialization provides a uniform way for algorithms to access information about a particular iterator. The template depends on an iterator providing a basic interface consisting of the types value_type, distance_type, and iterator_category, or on there being a spe- cialization for the iterator. The library provides one specialization (partial) to handle all pointer iterator types. iterator_traits are used within algorithms to provide local variables of the type pointed to by the iterator, or of the iterator's distance type. The traits are is also used to improve the efficiency of algorithms by making use of knowledge about basic iterator categories provided by the iterator_category member. An algorithm can use this "tag" to select the most efficient implementation an iterator is capable of handling without sacrificing the ability to work with a wide range of iterator types. For instance, both the advance and distance primitives use iterator_category to maximize their efficiency by using the tag to select from one of several different auxiliary functions. The iterator_category must therefore be one of the iterator tags provided by the library. TAG TYPES input_iterator_tag output_iterator_tag forward_iterator_tag bidirectional_iterator_tag random_access_iterator_tag iterator_traits::iterator_category is typically used like this: template void foo(Iterator first, Iterator last) { __foo(begin,end, iterator_traits::iterator_category); } template void __foo(Iterator first, Iterator last, input_iterator_tag> { // Most general implementation } template void __foo(Iterator first, Iterator last, bidirectional_iterator_tag> { // Implementation takes advantage of bi-diretional // capability of the iterators } _etc. See the iterator section in the Class Reference for a description of iterators and the capabilities associated with each type of iterator tag. WARNING If your compiler does not support partial specialization then this template and specialization will not be available to you. Instead you will need to use the distance_type, value_type, and iterator_category families of function templates. The Rogue Wave Standard C++ Library also provides alternate implementations of the distance, advance, and count functions when partial specialization is not supported by a particular compiler. SEE ALSO value_type, distance_type, iterator_category, distance,advance, iterator STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 back_inserter Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME back_insert_iterator, back_inserter - An insert iterator used to insert items at the end of a collection. SYNOPSIS #include template class back_insert_iterator : public output_iterator; DESCRIPTION Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class back_insert_iterator is used to insert items at the end of a collection. The function back_inserter creates an instance of a back_insert_iterator for a particular collection type. A back_insert_iterator can be used with vectors, deques, and lists, but not with maps or sets. INTERFACE template class back_insert_iterator : public output_iterator { protected: Container& container; public: back_insert_iterator (Container&); back_insert_iterator& operator= (const Container::value_type&); back_insert_iterator& operator* (); back_insert_iterator& operator++ (); back_insert_iterator operator++ (int); }; template back_insert_iterator back_inserter (Container&); CONSTRUCTOR back_insert_iterator (Container& x); Constructor. Creates an instance of a back_insert_iterator associated with container x. OPERATORS back_insert_iterator& operator= (const Container::value_type& value); Inserts a copy of value on the end of the container, and returns *this. back_insert_iterator& operator* (); Returns *this. back_insert_iterator& operator++ (); back_insert_iterator operator++ (int); Increments the input iterator and returns *this. HELPER FUNCTION template back_insert_iterator back_inserter (Container& x) Returns a back_insert_iterator that will insert elements at the end of container x. This function allows you to create insert iterators inline. EXAMPLE // // ins_itr.cpp // #include #include #include int main () { // // Initialize a deque using an array. // int arr[4] = { 3,4,7,8 }; deque d(arr+0, arr+4); // // Output the original deque. // cout << "Start with a deque: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert into the middle. // insert_iterator > ins(d, d.begin()+2); *ins = 5; *ins = 6; // // Output the new deque. // cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // A deque of four 1s. // deque d2(4, 1); // // Insert d2 at front of d. // copy(d2.begin(), d2.end(), front_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a front_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert d2 at back of d. // copy(d2.begin(), d2.end(), back_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a back_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : Start with a deque: 3 4 7 8 Use an insert_iterator: 3 4 5 6 7 8 Use a front_inserter: 1 1 1 1 3 4 5 6 7 8 Use a back_inserter: 1 1 1 1 3 4 5 6 7 8 1 1 1 1 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO insert iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 back_insert_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME back_insert_iterator, back_inserter - An insert iterator used to insert items at the end of a collection. SYNOPSIS #include template class back_insert_iterator : public output_iterator; DESCRIPTION Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class back_insert_iterator is used to insert items at the end of a collection. The function back_inserter creates an instance of a back_insert_iterator for a particular collection type. A back_insert_iterator can be used with vectors, deques, and lists, but not with maps or sets. INTERFACE template class back_insert_iterator : public output_iterator { protected: Container& container; public: back_insert_iterator (Container&); back_insert_iterator& operator= (const Container::value_type&); back_insert_iterator& operator* (); back_insert_iterator& operator++ (); back_insert_iterator operator++ (int); }; template back_insert_iterator back_inserter (Container&); CONSTRUCTOR back_insert_iterator (Container& x); Constructor. Creates an instance of a back_insert_iterator associated with container x. OPERATORS back_insert_iterator& operator= (const Container::value_type& value); Inserts a copy of value on the end of the container, and returns *this. back_insert_iterator& operator* (); Returns *this. back_insert_iterator& operator++ (); back_insert_iterator operator++ (int); Increments the input iterator and returns *this. HELPER FUNCTION template back_insert_iterator back_inserter (Container& x) Returns a back_insert_iterator that will insert elements at the end of container x. This function allows you to create insert iterators inline. EXAMPLE // // ins_itr.cpp // #include #include #include int main () { // // Initialize a deque using an array. // int arr[4] = { 3,4,7,8 }; deque d(arr+0, arr+4); // // Output the original deque. // cout << "Start with a deque: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert into the middle. // insert_iterator > ins(d, d.begin()+2); *ins = 5; *ins = 6; // // Output the new deque. // cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // A deque of four 1s. // deque d2(4, 1); // // Insert d2 at front of d. // copy(d2.begin(), d2.end(), front_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a front_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert d2 at back of d. // copy(d2.begin(), d2.end(), back_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a back_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : Start with a deque: 3 4 7 8 Use an insert_iterator: 3 4 5 6 7 8 Use a front_inserter: 1 1 1 1 3 4 5 6 7 8 Use a back_inserter: 1 1 1 1 3 4 5 6 7 8 1 1 1 1 WARNING If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO insert iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Bidirectional_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Bidirectional_Iterators - An iterator that can both read and write and can traverse a container in both directions DESCRIPTION For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. Bidirectional iterators can move both forwards and backwards through a container, and have the ability to both read and write data. These iterators satisfy the requirements listed below. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator descriptions listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR BIDIRECTIONAL ITERATORS A bidirectional iterator must meet all the requirements listed below. Note that most of these requirements are also the requirements for forward iterators. X u u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool a->m equivalent to (*a).m *a return value convertible to T& ++r returns X& r++ return value convertible to const X& *r++ returns T& --r returns X& r-- return value convertible to const X& *r-- returns T& Like forward iterators, bidirectional iterators have the condition that a == b implies *a== *b. There are no restrictions on the number of passes an algorithm may make through the structure. SEE ALSO Containers, Iterators, Forward Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Forward_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Forward_Iterators - A forward-moving iterator that can both read and write. DESCRIPTION For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. Forward iterators are forward moving, and have the ability to both read and write data. These iterators satisfy the requirements listed below. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator requirements listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR FORWARD ITERATORS The following expressions must be valid for forward iterators: X u u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool *a return value convertible to T& a->m equivalent to (*a).m ++r returns X& r++ return value convertible to const X& *r++ returns T& Forward iterators have the condition that a == b implies *a == *b. There are no restrictions on the number of passes an algorithm may make through the structure. SEE ALSO Iterators, Bidirectional Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 front_inserter Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME front_insert_iterator, front_inserter - An insert iterator used to insert items at the beginning of a collection. SYNOPSIS #include template class front_insert_iterator : public output_iterator ; DESCRIPTION Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class front_insert_iterator is used to insert items at the beginning of a collection. The function front_inserter creates an instance of a front_insert_iterator for a particular collection type. A front_insert_iterator can be used with deques and lists, but not with maps or sets. Note that a front_insert_iterator makes each element that it inserts the new front of the container. This has the effect of reversing the order of the inserted elements. For example, if you use a front_insert_iterator to insert "1" then "2" then "3" onto the front of container exmpl, you will find, after the three insertions, that the first three elements of exmpl are "3 2 1". INTERFACE template class front_insert_iterator : public output_iterator { public: explicit front_insert_iterator (Container&); front_insert_iterator& operator= (const typename Container::value_type&); front_insert_iterator& operator* (); front_insert_iterator& operator++ (); front_insert_iterator operator++ (int); }; template front_insert_iterator front_inserter (Container&); CONSTRUCTOR explicit front_insert_iterator(Container& x); Constructor. Creates an instance of a front_insert_iterator associated with container x. OPERATORS front_insert_iterator& operator=(const typename Container::value_type& value); Assignment Operator. Inserts a copy of value on the front of the container, and returns *this. front_insert_iterator& operator*(); Returns *this (the input iterator itself). front_insert_iterator& operator++(); front_insert_iterator operator++(int); Increments the insert iterator and returns *this. NON-MEMBER FUNCTION template front_insert_iterator front_inserter(Container& x) Returns a front_insert_iterator that will insert elements at the beginning of container x. This function allows you to create front insert iterators inline. EXAMPLE // // ins_itr.cpp // #include #include #include int main () { // // Initialize a deque using an array. // int arr[4] = { 3,4,7,8 }; deque d(arr+0, arr+4); // // Output the original deque. // cout << "Start with a deque: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert into the middle. // insert_iterator > ins(d, d.begin()+2); *ins = 5; *ins = 6; // // Output the new deque. // cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // A deque of four 1s. // deque d2(4, 1); // // Insert d2 at front of d. // copy(d2.begin(), d2.end(), front_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a front_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert d2 at back of d. // copy(d2.begin(), d2.end(), back_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a back_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); cout << endl; return 0; } Output : Start with a deque: 3 4 7 8 Use an insert_iterator: 3 4 5 6 7 8 Use a front_inserter: 1 1 1 1 3 4 5 6 7 8 Use a back_inserter: 1 1 1 1 3 4 5 6 7 8 1 1 1 1 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: deque > instead of: deque SEE ALSO Insert Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Input_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Input_Iterators - A read-only, forward moving iterator. DESCRIPTION For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. Input iterators are read-only, forward moving iterators that satisfy the requirements listed below. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator requirement descriptions listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR INPUT ITERATORS The following expressions must be valid for input iterators: X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool *a a == b implies *a == *b ++r returns X& r++ return value convertible to const X& *r++ returns type T a -> m returns (*a).m For input iterators, a == b does not imply that ++a == ++b. Algorithms using input iterators should be single pass algorithms. That is they should not pass through the same iterator twice. The value of type T does not have to be an lvalue. SEE ALSO iterators, output iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 inserter Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME insert_iterator, inserter - An insert iterator used to insert items into a collection rather than overwrite the collection. SYNOPSIS #include template class insert_iterator : public output_iterator; DESCRIPTION Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class insert_iterator is used to insert items into a specified location of a collection. The function inserter creates an instance of an insert_iterator given a particular collection type and iterator. An insert_iterator can be used with vectors, deques, lists, maps and sets. INTERFACE template class insert_iterator : public output_iterator { public: insert_iterator (Container&, typename Container::iterator); insert_iterator& operator= (const typename Container::value_type&); insert_iterator& operator* (); insert_iterator& operator++ (); insert_iterator& operator++ (int); }; template insert_iterator inserter (Container&, Iterator) CONSTRUCTOR insert_iterator(Container& x, typename Container::iterator i); Constructor. Creates an instance of an insert_iterator associated with container x and iterator i. OPERATORS insert_iterator& operator=(const typename Container::value_type& value); Assignment operator. Inserts a copy of value into the container at the location specified by the insert_iterator, increments the iterator, and returns *this. insert_iterator& operator*(); Returns *this (the input iterator itself). insert_iterator& operator++(); insert_iterator& operator++(int); Increments the insert iterator and returns *this. NON-MEMBER FUNCTION template insert_iterator inserter(Container& x, Iterator i); Returns an insert_iterator that will insert elements into container x at location i. This function allows you to create insert iterators inline. EXAMPLE #include #include #include int main() { //Initialize a vector using an array int arr[4] = {3,4,7,8}; vector v(arr,arr+4); //Output the original vector cout << "Start with a vector: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); //Insert into the middle insert_iterator > ins(v, v.begin()+2); *ins = 5; *ins = 6; //Output the new vector cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); return 0; } WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of: vector SEE ALSO back_insert_iterator, front_insert_iterator, Insert Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 insert_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME insert_iterator, inserter - An insert iterator used to insert items into a collection rather than overwrite the collection. SYNOPSIS #include template class insert_iterator : public output_iterator; DESCRIPTION Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class insert_iterator is used to insert items into a specified location of a collection. The function inserter creates an instance of an insert_iterator given a particular collection type and iterator. An insert_iterator can be used with vectors, deques, lists, maps and sets. INTERFACE template class insert_iterator : public output_iterator { public: insert_iterator (Container&, typename Container::iterator); insert_iterator& operator= (const typename Container::value_type&); insert_iterator& operator* (); insert_iterator& operator++ (); insert_iterator& operator++ (int); }; template insert_iterator inserter (Container&, Iterator) CONSTRUCTOR insert_iterator(Container& x, typename Container::iterator i); Constructor. Creates an instance of an insert_iterator associated with container x and iterator i. OPERATORS insert_iterator& operator=(const typename Container::value_type& value); Assignment operator. Inserts a copy of value into the container at the location specified by the insert_iterator, increments the iterator, and returns *this. insert_iterator& operator*(); Returns *this (the input iterator itself). insert_iterator& operator++(); insert_iterator& operator++(int); Increments the insert iterator and returns *this. NON-MEMBER FUNCTION template insert_iterator inserter(Container& x, Iterator i); Returns an insert_iterator that will insert elements into container x at location i. This function allows you to create insert iterators inline. EXAMPLE #include #include #include int main() { //Initialize a vector using an array int arr[4] = {3,4,7,8}; vector v(arr,arr+4); //Output the original vector cout << "Start with a vector: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); //Insert into the middle insert_iterator > ins(v, v.begin()+2); *ins = 5; *ins = 6; //Output the new vector cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); return 0; } WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write: vector > instead of: vector SEE ALSO back_insert_iterator, front_insert_iterator, Insert Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Insert_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Insert_Iterators - Iterator adaptor that allows an iterator to insert into a container rather than overwrite elements in the container. SYNOPSIS #include template class insert_iterator : public output_iterator; template class back_insert_iterator:public output_iterator; template class front_insert_iterator : public output_iterator; DESCRIPTION Insert iterators are iterator adaptors that let an iterator insert new elements into a collection rather than overwrite existing elements when copying to a container. There are several types of insert iterator classes. + The class back_insert_iterator is used to insert items at the end of a collection. The function back_inserter can be used with an iterator inline, to create an instance of a back_insert_iterator for a particular collection type. + The class front_insert_iterator is used to insert items at the start of a collection. The function front_inserter creates an instance of a front_insert_iterator for a particular collection type. + An insert_iterator inserts new items into a collection at a location defined by an iterator supplied to the constructor. Like the other insert iterators, insert_iterator has a helper function called inserter, which takes a collection and an iterator into that collection, and creates an instance of the insert_iterator. INTERFACE template class insert_iterator : public output_iterator { public: insert_iterator (Container&, typename Container::iterator); insert_iterator& operator= (const typename Container::value_type&); insert_iterator& operator* (); insert_iterator& operator++ (); insert_iterator& operator++ (int); }; template class back_insert_iterator : public output_iterator { public: explicit back_insert_iterator (Container&); back_insert_iterator& operator= (const typename Container::value_type&); back_insert_iterator& operator* (); back_insert_iterator& operator++ (); back_insert_iterator operator++ (int); }; template class front_insert_iterator : public output_iterator { public: explicit front_insert_iterator (Container&); front_insert_iterator& operator= (const typename Container::value_type&); front_insert_iterator& operator* (); front_insert_iterator& operator++ (); front_insert_iterator operator++ (int); }; template insert_iterator inserter (Container&, Iterator); template back_insert_iterator back_inserter (Container&); template front_insert_iterator front_inserter (Container&); SEE ALSO back_insert_iterator, front_insert_iterator, insert_iterator STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 istream_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME istream_iterator - Stream iterator that provides iterator capabilities for istreams. This iterator allows generic algorithms to be used directly on streams. SYNOPSIS #include template , class Distance = ptrdiff_t> class istream_iterator : public iterator; DESCRIPTION Stream iterators provide the standard iterator interface for input and output streams. The class istream_iterator reads elements from an input stream (using operator >>). A value of type T is retrieved and stored when the iterator is constructed and each time operator++ is called. The iterator will be equal to the end-of-stream iterator value if the end-of-file is reached. Use the constructor with no arguments to create an end-of-stream iterator. The only valid use of this iterator is to compare to other iterators when checking for end of file. Do not attempt to dereference the end-of-stream iterator; it plays the same role as the past-the-end iterator provided by the end() function of containers. Since an istream_iterator is an input iterator, you cannot assign to the value returned by dereferencing the iterator. This also means that istream_iterators can only be used for sin- gle pass algorithms. Since a new value is read every time the operator++ is used on an istream_iterator, that operation is not equality-preserving. This means that i == j does not mean that ++i == ++j (although two end-of-stream iterators are always equal). INTERFACE template class Distance = ptrdiff_t> class istream_iterator : public iterator { public: typedef T value_type; typedef charT char_type; typedef traits traits_type; typedef basic_istream istream_type; istream_iterator(); istream_iterator (istream_type&); istream_iterator (const stream_iterator&); ~istream_itertor (); const T& operator*() const; const T* operator ->() const; istream_iterator & operator++(); istream_iterator operator++ (int) }; // Non-member Operators template bool operator==(const istream_iterator&, const istream_iterator&); template bool operator!=(const istream_iterator&, const istream_iterator&); TYPES value_type; Type of value to stream in. char_type; Type of character the stream is built on. traits_type; Traits used to build the stream. istream_type; Type of stream this iterator is constructed on. CONSTRUCTORS istream_iterator(); Construct an end-of-stream iterator. This iterator can be used to compare against an end-of-stream condition. Use it to provide end iterators to algorithms istream_iterator(istream& s); Construct an istream_iterator on the given stream. istream_iterator(const istream_iterator& x); Copy constructor. DESTRUCTORS ~istream_iterator(); Destructor. OPERATORS const T& operator*() const; Return the current value stored by the iterator. const T* operator->() const; Return a pointer to the current value stored by the iterator. istream_iterator& operator++() istream_iterator operator++(int) Retrieve the next element from the input stream. NON-MEMBER OPERATORS bool operator==(const istream_iterator& x, const istream_iterator& y) Equality operator. Returns true if x is the same as y. bool operator!=(const istream_iterator& x, const istream_iterator& y) Inequality operator. Returns true if x is not the same as y. EXAMPLE // // io_iter.cpp // #include #include #include #include int main () { vector d; int total = 0; // // Collect values from cin until end of file // Note use of default constructor to get ending iterator // cout << "Enter a sequence of integers (eof to quit): " ; copy(istream_iterator(cin), istream_iterator(), inserter(d,d.begin())); // // stream the whole vector and the sum to cout // copy(d.begin(),d.end()-1, ostream_iterator(cout," + ")); if (d.size()) cout << *(d.end()-1) << " = " << accumulate(d.begin(),d.end(),total) << endl; return 0; } WARNING If your compiler does not support default template parameters, then you will need to always supply the Allocator template argument. And you'll have to provide all parameters to the istream_iterator template. For instance, you'll have to write : vector > instead of : vector SEE ALSO iterators, ostream_iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 istreambuf_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME istreambuf_iterator SYNOPSIS #include template > class istreambuf_iterator : public input_iterator DESCRIPTION The template class istreambuf_iterator reads successive characters from the stream buffer for which it was constructed. operator* provides access to the current input character, if any, and operator++ advances to the next input character. If the end of stream is reached, the iterator becomes equal to the end of stream iterator value, which is constructed by the default constructor, istreambuf_iterator(). An istreambuf_iterator object can be used only for one-pass-algorithms. INTERFACE template > class istreambuf_iterator : public input_iterator { public: typedef charT char_type; typedef typename traits::int_type int_type; typedef traits traits_type; typedef basic_streambuf streambuf_type; typedef basic_istream istream_type; class proxy; istreambuf_iterator() throw(); istreambuf_iterator(istream_type& s) throw(); istreambuf_iterator(streambuf_type *s) throw(); istreambuf_iterator(const proxy& p) throw(); char_type operator*(); istreambuf_iterator& operator++(); proxy operator++(int); bool equal(istreambuf_iterator& b); }; template bool operator==(istreambuf_iterator& a, istreambuf_iterator& b); TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. istream_type The type istream_type is an instantiation of class basic_istream on types charT and traits: typedef basic_istream istream_type; streambuf_type The type streambuf_type is an instantiation of class basic_streambuf on types charT and traits: typedef basic_streambuf streambuf_type; traits_type The type traits_type is a synonym for the template parameter traits. NESTED CLASS PROXY Class istreambuf_iterator::proxy provides a temporary placeholder as the return value of the post-increment operator. It keeps the character pointed to by the previous value of the iterator for some possible future access. CONSTRUCTORS istreambuf_iterator() throw(); Constructs the end of stream iterator. istreambuf_iterator(istream_type& s) throw(); Constructs an istreambuf_iterator that inputs characters using the basic_streambuf object pointed to by s.rdbuf(). If s.rdbuf() is a null pointer, the istreambuf_iterator is the end-of-stream iterator. istreambuf_iterator(streambuf_type *s) throw(); Constructs an istreambuf_iterator that inputs characters using the basic_streambuf object pointed at by s. If s is a null pointer, the istreambuf_iterator is the end-of-stream iterator. istreambuf_iterator(const proxy& p) throw(); Constructs an istreambuf_iterator that uses the basic_streambuf object embedded in the proxy object. MEMBER OPERATORS char_type operator*(); Returns the character pointed at by the input sequence of the attached stream buffer. If no character is available, the iterator becomes equal to the end-of-stream iterator. istreambuf_iterator& operator++(); Increments the input sequence of the attached stream buffer to point to the next character. If the current character is the last one, the iterator becomes equal to the end-of-stream iterator. proxy operator++(int); Increments the input sequence of the attached stream buffer to point to the next character. If the current character is the last one, the iterator becomes equal to the end-of-stream iterator. The proxy object returned contains the character pointed at before carrying out the post-increment operator. PUBLIC MEMBER FUNCTION bool equal(istreambuf_iterator& b); Returns true if and only if both iterators are at end of stream, or neither is at end of stream, regardless of what stream buffer object they are using. NON MEMBER FUNCTIONS template bool operator==(istreambuf_iterator& a, istreambuf_iterator& b); Returns a.equal(b). EXAMPLES // // stdlib/examples/manual/istreambuf_iterator.cpp // #include #include void main ( ) { using namespace std; // open the file is_iter.out for reading and writing ofstream out("is_iter.out", ios_base::out | ios_base::in ); // output the example sentence into the file out << "Ceci est un simple example pour demontrer le" << endl; out << "fonctionement de istreambuf_iterator"; // seek to the beginning of the file out.seekp(0); // construct an istreambuf_iterator pointing to // the ofstream object underlying stream buffer istreambuf_iterator iter(out.rdbuf()); // construct an end of stream iterator istreambuf_iterator end_of_stream_iterator; cout << endl; // output the content of the file while( !iter.equal(end_of_stream_iterator) ) // use both operator++ and operator* cout << *iter++; cout << endl; } SEE ALSO basic_streambuf, basic_istream, ostreambuf_iterator Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 24.4.3 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 ostream_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME ostream_iterator - Stream iterators provide iterator capabilities for ostreams and istreams. They allow generic algorithms to be used directly on streams. SYNOPSIS #include template > class ostream_iterator : public iterator; DESCRIPTION Stream iterators provide the standard iterator interface for input and output streams. The class ostream_iterator writes elements to an output stream. If you use the constructor that has a second, char * argument, then that string will be written after every element . (The string must be null-terminated.) Since an ostream iterator is an output iterator, it is not possible to get an element out of the iterator. You can only assign to it. INTERFACE template > class ostream_iterator : public iterator { public: typedef T value_type; typedef charT char_type; typedef traits traits_type; typedef basic_ostream ostream_type; ostream_iterator(ostream&); ostream_iterator (ostream&, const char*); ostream_iterator (const ostream_iterator >&); ~ostream_itertor (); ostream_iterator >& operator=(const T&); ostream_iterator >& operator* () const; ostream_iterator >& operator++ (); ostream_iterator > operator++ (int); }; TYPES value_type; Type of value to stream in. char_type; Type of character the stream is built on. traits_type; Traits used to build the stream. ostream_type; Type of stream this iterator is constructed on. CONSTRUCTORS ostream_iterator (ostream& s); Construct an ostream_iterator on the given stream. ostream_iterator (ostream& s, const char* delimiter); Construct an ostream_iterator on the given stream. The null terminated string delimitor is written to the stream after every element. ostream_iterator (const ostream_iterator& x); Copy constructor. DESTRUCTOR ~ostream_iterator (); Destructor OPERATORS const T& operator= (const T& value); Shift the value T onto the output stream. const T& ostream_iterator& operator* (); ostream_iterator& operator++(); ostream_iterator operator++ (int); These operators all do nothing. They simply allow the iterator to be used in common constructs. EXAMPLE #include #include #include #include int main () { // // Initialize a vector using an array. // int arr[4] = { 3,4,7,8 }; int total=0; deque d(arr+0, arr+4); // // stream the whole vector and a sum to cout // copy(d.begin(),d.end()-1, ostream_iterator(cout," + ")); cout << *(d.end()-1) << " = " << accumulate(d.begin(),d.end(),total) << endl; return 0; } WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : deque > instead of : deque SEE ALSO istream_iterator, iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 ostreambuf_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME ostreambuf_iterator SYNOPSIS #include template > class ostreambuf_iterator : public output_iterator DESCRIPTION The template class ostreambuf_iterator writes successive characters onto the stream buffer object from which it was constructed. The operator= is used to write the characters and in case of failure the member function failed() returns true. INTERFACE template > class ostreambuf_iterator : public output_iterator { public: typedef charT char_type; typedef traits traits_type; typedef basic_streambuf streambuf_type; typedef basic_ostream ostream_type; ostreambuf_iterator(ostream_type& s) throw(); ostreambuf_iterator(streambuf_type *s) throw(); ostreambuf_iterator& operator*(); ostreambuf_iterator& operator++(); ostreambuf_iterator operator++(int); ostreambuf_iterator& operator=(charT c); bool failed( ) const throw(); }; TYPES char_type The type char_type is a synonym for the template parameter charT. ostream_type The type ostream_type is an instantiation of class basic_ostream on types charT and traits: typedef basic_ostream ostream_type; streambuf_type The type streambuf_type is an instantiation of class basic_streambuf on types charT and traits: typedef basic_streambuf streambuf_type; traits_type The type traits_type is a synonym for the template parameter traits. CONSTRUCTORS ostreambuf_iterator(ostream_type& s) throw(); Constructs an ostreambuf_iterator that uses the basic_streambuf object pointed at by s.rdbuf()to output characters. If s.rdbuf() is a null pointer, calls to the member function failed() return true. ostreambuf_iterator(streambuf_type *s) throw(); Constructs an ostreambuf_iterator that uses the basic_streambuf object pointed at by s to output characters. If s is a null pointer, calls to the member function failed() return true. MEMBER OPERATORS ostreambuf_iterator& operator=(charT c); Inserts the character c into the output sequence of the attached stream buffer. If the operation fails, calls to the member function failed() return true. ostreambuf_iterator& operator++(); Returns *this. ostreambuf_iterator operator++(int); Returns *this. ostreambuf_iterator operator*(); Returns *this. PUBLIC MEMBER FUNCTION bool failed() const throw(); Returns true if the iterator failed inserting a characters or false otherwise. EXAMPLES // // stdlib/examples/manual/ostreambuf_iterator.cpp // #include #include void main ( ) { using namespace std; // create a filebuf object filebuf buf; // open the file iter_out and link it to the filebuf object buf.open("iter_out", ios_base::in | ios_base::out ); // create an ostreambuf_iterator and link it to // the filebuf object ostreambuf_iterator out_iter(&buf); // output into the file using the ostreambuf_iterator for(char i=64; i<128; i++ ) out_iter = i; // seek to the beginning of the file buf.pubseekpos(0); // create an istreambuf_iterator and link it to // the filebuf object istreambuf_iterator in_iter(&buf); // construct an end of stream iterator istreambuf_iterator end_of_stream_iterator; cout << endl; // output the content of the file while( !in_iter.equal(end_of_stream_iterator) ) // use both operator++ and operator* cout << *in_iter++; cout << endl; } SEE ALSO basic_streambuf, basic_ostream, istreambuf_iterator Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 24.4.4 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Output_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Output_Iterators - A write-only, forward moving iterator. DESCRIPTION For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. Output iterators are write-only, forward moving iterators that satisfy the requirements listed below. Note that unlike other iterators used with the standard library, output iterators cannot be constant. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator requirements listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR OUTPUT ITERATORS The following expressions must be valid for output iterators: X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a X u = a assignment, u == a *a = t result is not used ++r returns X& r++ return value convertible to const X& *r++ = t result is not used The only valid use for the operator * is on the left hand side of the assignment statement. Algorithms using output iterators should be single pass algorithms. That is, they should not pass through the same iterator twice. SEE ALSO Iterators, Input Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Random_Access_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Random_Access_Iterators - An iterator that reads and writes, and provides random access to a container. DESCRIPTION For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. Random access iterators can read and write, and provide random access to the containers they serve. These iterators satisfy the requirements listed below. KEY TO ITERATOR REQUIREMENTS The following key pertains to the iterator requirements listed below: a and b values of type X n value of distance type u, Distance, tmp and m identifiers r value of type X& t value of type T REQUIREMENTS FOR RANDOM ACCESS ITERATORS The following expressions must be valid for random access iterators: X u u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a X u = a assignment, u == a a == b, a != b return value convertible to bool *a return value convertible to T& a->m equivalent to (*a).m ++r returns X& r++ return value convertible to const X& *r++ returns T& --r returns X& r-- return value convertible to const X& *r-- returns T& r += n Semantics of --r or ++r n times depending on the sign of n a + n, n + a returns type X r -= n returns X&, behaves as r += -n a - n returns type X b - a returns Distance a[n] *(a+n), return value convertible to T a < b total ordering relation a > b total ordering relation opposite to < a <= b !(a < b) a >= b !(a > b) Like forward iterators, random access iterators have the condition that a == b implies *a == *b. There are no restrictions on the number of passes an algorithm may make through the structure. All relational operators return a value convertible to bool. SEE ALSO Iterators, Forward Iterators, Bidirectional Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 raw_storage_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME raw_storage_iterator - Enables iterator-based algorithms to store results into uninitialized memory. SYNOPSIS #include template class raw_storage_iterator : public output_iterator { public: explicit raw_storage_iterator (OutputIterator); raw_storage_iterator& operator*(); raw_storage_iterator& operator= (const T&); raw_storage_iterator& operator++(); raw_storage_iterator operator++ (int); }; DESCRIPTION Class raw_storage_iterator enables iterator-based algorithms to store their results in uninitialized memory. The template parameter, OutputIterator is required to have its operator* return an object for which operator& is both defined and returns a pointer to T. CONSTRUCTOR raw_storage_iterator (OutputIterator x); Initializes the iterator to point to the same value that x points to. MEMBER OPERATORS raw_storage_iterator & operator =(const T& element); Constructs an instance of T, initialized to the value element , at the location pointed to by the iterator. raw_storage_iterator & operator++(); Pre-increment: advances the iterator and returns a reference to the updated iterator. raw_storage_iterator operator++ (int); Post-increment: advances the iterator and returns the old value of the iterator. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 reverse_bidirectional_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME reverse_bidirectional_iterator, reverse_iterator - An iterator that traverses a collection backwards. SYNOPSIS #include template class reverse_bidirectional_iterator : public iterator ; template class reverse_iterator : public iterator; DESCRIPTION The iterators reverse_iterator and reverse_bidirectional_iterator correspond to random_access_iterator and bidirectional_iterator, except they traverse the collection they point to in the opposite direction. The fundamental relationship between a reverse iterator and its corresponding iterator i is established by the identity: &*(reverse_iterator(i)) == &*(i-1); This mapping is dictated by the fact that, while there is always a pointer past the end of a container, there might not be a valid pointer before its beginning. The following are true for reverse_bidirectional_iterators : + These iterators may be instantiated with the default constructor or by a single argument constructor that initializes the new reverse_bidirectional_iterator with a bidirectional_iterator. + operator* returns a reference to the current value pointed to. + operator++ advances the iterator to the previous item (--current) and returns a reference to *this. + operator++(int) advances the iterator to the previous item (--current) and returns the old value of *this. + operator-- advances the iterator to the following item (++current) and returns a reference to *this. + operator--(int) Advances the iterator to the following item (++current) and returns the old value of *this. + operator== This non-member operator returns true if the iterators x and y point to the same item. The following are true for reverse_iterators : + These iterators may be instantiated with the default constructor or by a single argument constructor which initializes the new reverse_iterator with a random_access_iterator. + operator* returns a reference to the current value pointed to. + operator++ advances the iterator to the previous item (--current) and returns a reference to *this. + operator++(int) advances the iterator to the previous item (--current) and returns the old value of *this. + operator-- advances the iterator to the following item (++current) and returns a reference to *this. + operator--(int) advances the iterator to the following item (++current) and returns the old value of *this. + operator== is a non-member operator returns true if the iterators x and y point to the same item. + operator!= is a non-member operator returns !(x==y). + operator< is a non-member operator returns true if the iterator x precedes the iterator y. + operator> is a non-member operator returns y < x. + operator<= is a non-member operator returns !(y < x). + operator>= is a non-member operator returns !(x < y). + The remaining operators (<, +, - , +=, -=) are redefined to behave exactly as they would in a random_access_iterator, except with the sense of direction reversed. COMPLEXITY All iterator operations are required to take at most amortized constant time. INTERFACE template class reverse_bidirectional_iterator : public iterator { typedef reverse_bidirectional_iterator self; friend bool operator== (const self&, const self&); public: reverse_bidirectional_iterator (); explicit reverse_bidirectional_iterator (BidirectionalIterator); BidirectionalIterator base (); Reference operator* (); self& operator++ (); self operator++ (int); self& operator-- (); self operator-- (int); }; // Non-member Operators template bool operator== ( const reverse_bidirectional_iterator &, const reverse_bidirectional_iterator &); template bool operator!= ( const reverse_bidirectional_iterator &, const reverse_bidirectional_iterator &); template class reverse_iterator : public iterator { typedef reverse_iterator self; friend bool operator== (const self&, const self&); friend bool operator< (const self&, const self&); friend Distance operator- (const self&, const self&); friend self operator+ (Distance, const self&); public: reverse_iterator (); explicit reverse_iterator (RandomAccessIterator); RandomAccessIterator base (); Reference operator* (); self& operator++ (); self operator++ (int); self& operator-- (); self operator-- (int); self operator+ (Distance) const; self& operator+= (Distance); self operator- (Distance) const; self& operator-= (Distance); Reference operator[] (Distance); }; // Non-member Operators template bool operator== ( const reverse_iterator&, const reverse_iterator&); template bool operator!= ( const reverse_iterator&, const reverse_iterator&); template bool operator< ( const reverse_iterator&, const reverse_iterator&); template bool operator> ( const reverse_iterator&, const reverse_iterator&); template bool operator<= ( const reverse_iterator&, const reverse_iterator&); template bool operator>= ( const reverse_iterator&, const reverse_iterator&); template Distance operator- ( const reverse_iterator&, const reverse_iterator&); template reverse_iterator operator+ ( Distance, const reverse_iterator&); EXAMPLE // // rev_itr.cpp // #include #include #include int main() { //Initialize a vector using an array int arr[4] = {3,4,7,8}; vector v(arr,arr+4); //Output the original vector cout << "Traversing vector with iterator: " << endl << " "; for(vector::iterator i = v.begin(); i != v.end(); i++) cout << *i << " "; //Declare the reverse_iterator vector::reverse_iterator rev(v.end()); vector::reverse_iterator rev_end(v.begin()); //Output the vector backwards cout << endl << endl; cout << "Same vector, same loop, reverse_itertor: " << endl << " "; for(; rev != rev_end; rev++) cout << *rev << " "; return 0; } Output : Traversing vector with iterator: 3 4 7 8 Same vector, same loop, reverse_itertor: 8 7 4 3 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 reverse_iterator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME reverse_bidirectional_iterator, reverse_iterator - An iterator that traverses a collection backwards. SYNOPSIS #include template class reverse_bidirectional_iterator : public iterator ; template class reverse_iterator : public iterator; DESCRIPTION The iterators reverse_iterator and reverse_bidirectional_iterator correspond to random_access_iterator and bidirectional_iterator, except they traverse the collection they point to in the opposite direction. The fundamental relationship between a reverse iterator and its corresponding iterator i is established by the identity: &*(reverse_iterator(i)) == &*(i-1); This mapping is dictated by the fact that, while there is always a pointer past the end of a container, there might not be a valid pointer before its beginning. The following are true for reverse_bidirectional_iterators : + These iterators may be instantiated with the default constructor or by a single argument constructor that initializes the new reverse_bidirectional_iterator with a bidirectional_iterator. + operator* returns a reference to the current value pointed to. + operator++ advances the iterator to the previous item (--current) and returns a reference to *this. + operator++(int) advances the iterator to the previous item (--current) and returns the old value of *this. + operator-- advances the iterator to the following item (++current) and returns a reference to *this. + operator--(int) Advances the iterator to the following item (++current) and returns the old value of *this. + operator== This non-member operator returns true if the iterators x and y point to the same item. The following are true for reverse_iterators : + These iterators may be instantiated with the default constructor or by a single argument constructor which initializes the new reverse_iterator with a random_access_iterator. + operator* returns a reference to the current value pointed to. + operator++ advances the iterator to the previous item (--current) and returns a reference to *this. + operator++(int) advances the iterator to the previous item (--current) and returns the old value of *this. + operator-- advances the iterator to the following item (++current) and returns a reference to *this. + operator--(int) advances the iterator to the following item (++current) and returns the old value of *this. + operator== is a non-member operator returns true if the iterators x and y point to the same item. + operator!= is a non-member operator returns !(x==y). + operator< is a non-member operator returns true if the iterator x precedes the iterator y. + operator> is a non-member operator returns y < x. + operator<= is a non-member operator returns !(y < x). + operator>= is a non-member operator returns !(x < y). + The remaining operators (<, +, - , +=, -=) are redefined to behave exactly as they would in a random_access_iterator, except with the sense of direction reversed. COMPLEXITY All iterator operations are required to take at most amortized constant time. INTERFACE template class reverse_bidirectional_iterator : public iterator { typedef reverse_bidirectional_iterator self; friend bool operator== (const self&, const self&); public: reverse_bidirectional_iterator (); explicit reverse_bidirectional_iterator (BidirectionalIterator); BidirectionalIterator base (); Reference operator* (); self& operator++ (); self operator++ (int); self& operator-- (); self operator-- (int); }; // Non-member Operators template bool operator== ( const reverse_bidirectional_iterator &, const reverse_bidirectional_iterator &); template bool operator!= ( const reverse_bidirectional_iterator &, const reverse_bidirectional_iterator &); template class reverse_iterator : public iterator { typedef reverse_iterator self; friend bool operator== (const self&, const self&); friend bool operator< (const self&, const self&); friend Distance operator- (const self&, const self&); friend self operator+ (Distance, const self&); public: reverse_iterator (); explicit reverse_iterator (RandomAccessIterator); RandomAccessIterator base (); Reference operator* (); self& operator++ (); self operator++ (int); self& operator-- (); self operator-- (int); self operator+ (Distance) const; self& operator+= (Distance); self operator- (Distance) const; self& operator-= (Distance); Reference operator[] (Distance); }; // Non-member Operators template bool operator== ( const reverse_iterator&, const reverse_iterator&); template bool operator!= ( const reverse_iterator&, const reverse_iterator&); template bool operator< ( const reverse_iterator&, const reverse_iterator&); template bool operator> ( const reverse_iterator&, const reverse_iterator&); template bool operator<= ( const reverse_iterator&, const reverse_iterator&); template bool operator>= ( const reverse_iterator&, const reverse_iterator&); template Distance operator- ( const reverse_iterator&, const reverse_iterator&); template reverse_iterator operator+ ( Distance, const reverse_iterator&); EXAMPLE // // rev_itr.cpp // #include #include #include int main() { //Initialize a vector using an array int arr[4] = {3,4,7,8}; vector v(arr,arr+4); //Output the original vector cout << "Traversing vector with iterator: " << endl << " "; for(vector::iterator i = v.begin(); i != v.end(); i++) cout << *i << " "; //Declare the reverse_iterator vector::reverse_iterator rev(v.end()); vector::reverse_iterator rev_end(v.begin()); //Output the vector backwards cout << endl << endl; cout << "Same vector, same loop, reverse_itertor: " << endl << " "; for(; rev != rev_end; rev++) cout << *rev << " "; return 0; } Output : Traversing vector with iterator: 3 4 7 8 Same vector, same loop, reverse_itertor: 8 7 4 3 WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO Iterators STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Stream_Iterators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Stream_Iterators - Stream iterators provide iterator capabilities for ostreams and istreams. They allow generic algorithms to be used directly on streams. See the sections istream_iterator and ostream_iterator for a description of these iterators. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 value_type Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME value_type - Determine the type of value an iterator points to. This function is now obsolete. It is retained in order to provide backward compatibility and support compilers that do not provide partial specialization. SYNOPSIS #include template inline T* value_type (const input_iterator&) template inline T* value_type (const forward_iterator&) template inline T* value_type (const bidirectional_iterator&) template inline T* value_type (const random_access_iterator&) template inline T* value_type (const T*) DESCRIPTION The value_type function template returns a pointer to a default value of the type pointed to by an iterator. Five overloaded versions of this function template handle the four basic iterator types and simple arrays. Each of the first four take an iterator of a specific type, and return the value used to instantiate the iterator. The fifth version takes and returns a T* in order to handle the case when an iterator is a simple pointer. This family of function templates can be used to extract a value type from an iterator and subsequently use that type to create a local variable. Typically the value_type functions are used like this: template void foo(Iterator first, Iterator last) { __foo(begin,end,value_type(first)); } template void __foo(Iterator first, Iterator last, T*> { T temp = *first; _ } The auxiliary function __foo extracts a usable value type from the iterator and then puts the type to work. SEE ALSO Other iterator primitives: distance_type, iterator_category, distance, advance STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Function_Objects 3 Function_Objects Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Function_Objects - Objects with an operator() defined. Function objects are used in place of pointers to functions as arguments to templated algorithms. SYNOPSIS #include // typedefs template struct unary_function; template struct binary_function; DESCRIPTION Function objects are objects with an operator() defined. They are important for the effective use of the standard library's generic algorithms, because the interface for each algorithmic template can accept either an object with an operator() defined, or a pointer to a function. The Standard C++ Library provides both a standard set of function objects, and a pair of classes that you can use as the base for creating your own function objects. Function objects that take one argument are called unary function objects. Unary function objects are required to provide the typedefs argument_type and result_type. Similarly, function objects that take two arguments are called binary function objects and, as such, are required to provide the typedefs first_argument_type, second_argument_type, and result_type. The classes unary_function and binary_function make the task of c reating templated function objects easier. The necessary typedefs for a unary or binary function object are provided by inheriting from the appropriate function object class. The function objects provided by the standard library are listed below, together with a brief description of their operation. This class reference also includes an alphabetic entry for each function. Name Operation arithmetic functions plus addition x + y minus subtraction x - y multiplies multiplication x * y divides division x / y modulus remainder x % y negate negation - x comparison functions equal_to equality test x == y not_equal_to inequality test x != y greater greater comparison x > y less less-than comparison x < y greater_equal greater than or equal comparison x >= y less_equal less than or equal comparison x <= y logical functions logical_and logical conjunction x && y logical_or logical disjunction x || y logical_not logical negation ! x INTERFACE template struct unary_function{ typedef Arg argument_type; typedef Result result_type; }; template struct binary_function{ typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; }; // Arithmetic Operations template struct plus : binary_function { T operator() (const T&, const T&) const; }; template struct minus : binary_function { T operator() (const T&, const T&) const; }; template struct multiplies : binary_function { T operator() (const T&, const T&) const; }; template struct divides : binary_function { T operator() (const T&, const T&) const; }; template struct modulus : binary_function { T operator() (const T&, const T&) const; }; template struct negate : unary_function { T operator() (const T&) const; }; // Comparisons template struct equal_to : binary_function { bool operator() (const T&, const T&) const; }; template struct not_equal_to : binary_function { bool operator() (const T&, const T&) const; }; template struct greater : binary_function { bool operator() (const T&, const T&) const; }; template struct less : binary_function { bool operator() (const T&, const T&) const; }; template struct greater_equal : binary_function { bool operator() (const T&, const T&) const; }; template struct less_equal : binary_function { bool operator() (const T&, const T&) const; }; // Logical Comparisons template struct logical_and : binary_function { bool operator() (const T&, const T&) const; }; template struct logical_or : binary_function { bool operator() (const T&, const T&) const; }; template struct logical_not : unary_function { bool operator() (const T&, const T&) const; }; EXAMPLE // // funct_ob.cpp // #include #include #include #include #include //Create a new function object from unary_function template class factorial : public unary_function { public: Arg operator()(const Arg& arg) { Arg a = 1; for(Arg i = 2; i <= arg; i++) a *= i; return a; } }; int main() { //Initialize a deque with an array of ints int init[7] = {1,2,3,4,5,6,7}; deque d(init, init+7); //Create an empty vector to store the factorials vector v((size_t)7); //Transform the numbers in the deque to their factorials and // store in the vector transform(d.begin(), d.end(), v.begin(), factorial()); //Print the results cout << "The following numbers: " << endl << " "; copy(d.begin(),d.end(),ostream_iterator(cout," ")); cout << endl << endl; cout << "Have the factorials: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); return 0; } Output : The following numbers: 1 2 3 4 5 6 7 Have the factorials: 1 2 6 24 120 720 5040 WARNINGS If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > and deque > instead of : vector and deque SEE ALSO binary_function, unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 divides Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME divides - Returns the result of dividing its first argument by its second. SYNOPSIS #include template struct divides; DESCRIPTION divides is a binary function object. Its operator() returns the result of dividing x by y. You can pass a divides object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. divides would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), divides()); After this call to transform, vecResult[n] will contain vec1[n] divided by vec2[n]. INTERFACE template struct divides : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 less Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME less - Binary function object that returns true if its first argument is less than its second SYNOPSIS #include template struct less : public binary_function ; DESCRIPTION less is a binary function object. Its operator() returns true if x is less than y. You can pass a less object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result of the function. less would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), less()); After this call to transform, vecResult(n) will contain a "1" if vec1(n) was less than vec2(n) or a "0" if vec1(n) was greater than or equal to vec2(n). INTERFACE template struct less : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 less_equal Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME less_equal - Binary function object that returns true if its first argument is less than or equal to its second SYNOPSIS #include template struct less_equal : public binary_function; DESCRIPTION less_equal is a binary function object. Its operator() returns true if x is less than or equal to y. You can pass a less_equal object to any algorithm that requires a binary function. For example, the sort algorithm can accept a binary function as an alternate comparison object to sort a sequence. less_equal would be used in that algorithm in the following manner: vector vec1; sort(vec1.begin(), vec1.end(),less_equal()); After this call to sort, vec1 will be sorted in ascending order. INTERFACE template struct less_equal : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write : vector > instead of vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 logical_and Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME logical_and - Binary function object that returns true if both of its arguments are true. SYNOPSIS #include template struct logical_and : public binary_function; DESCRIPTION logical_and is a binary function object. Its operator() returns true if both x and y are true. You can pass a logical_and object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result of the function. logical_and is used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), logical_and()); After this call to transform, vecResult(n) will contain a "1" (true) if both vec1(n) and vec2(n) are true or a "0" (false) if either vec1(n) or vec2(n) is false. INTERFACE template struct logical_and : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, you will need to always supply the Allocator template argument. For instance, you will have to write : vector > instead of: vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 logical_not Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME logical_not - Unary function object that returns true if its argument is false. SYNOPSIS #include template struct logical_not : unary_function ; DESCRIPTION logical_not is a unary function object. Its operator() returns true if its argument is false. You can pass a logical_not object to any algorithm that requires a unary function. For example, the replace_if algorithm replaces an element with another value if the result of a unary operation is true. logical_not is used in that algorithm in the following manner: vector vec1; void replace_if(vec1.begin(), vec1.end(), logical_not(),1); This call to replace_if replaces all zeros in the vec1 with "1". INTERFACE template struct logical_not : unary_function { typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; bool operator() (const T&) const; }; WARNING If your compiler does not support default template parameters, you will need to always supply the Allocator template argument. For instance, you will have to write : vector > instead of : vector SEE ALSO function objects, unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 logical_or Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME logical_or - Binary function object that returns true if either of its arguments are true. SYNOPSIS #include template struct logical_or : binary_function ; DESCRIPTION logical_or is a binary function object. Its operator() returns true if either x or y are true. You can pass a logical_or object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result of the function. logical_or is used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), logical_or()); After this call to transform, vecResult(n) will contain a "1" (true) if either vec1(n) or vec2(n) is true or a "0" (false) if both vec1(n) and vec2(n) are false. INTERFACE template struct logical_or : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, you will need to always supply the Allocator template argument. For instance, you will have to write : vector > instead of: vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 minus Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME minus - Returns the result of subtracting its second argument from its first. SYNOPSIS #include template struct minus : public binary_function; DESCRIPTION minus is a binary function object. Its operator() returns the result of x minus y. You can pass a minus object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. minus would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), minus()); After this call to transform, vecResult(n) will contain vec1(n) minus vec2(n). INTERFACE template struct minus : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will have to write : vector > instead of : vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 modulus Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME modulus - Returns the remainder obtained by dividing the first argument by the second argument. SYNOPSIS #include template struct modulus : public binary_function ; DESCRIPTION modulus is a binary function object. Its operator() returns the remainder resulting from of x divided by y. You can pass a modulus object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. modulus would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), modulus()); After this call to transform, vecResult(n) will contain the remainder of vec1(n) divided by vec2(n). INTERFACE template struct modulus : binary_function { typedef typename binary_function::second_argument_type n second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of vector SEE ALSO binary_function, function object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 multiplies Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME multiplies - A binary function object that returns the result of multiplying its first and second arguments. SYNOPSIS #include template struct multiplies : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; DESCRIPTION multiplies is a binary function object. Its operator() returns the result of multiplying x and y. You can pass a multiplies object to any algorithm that uses a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. multiplies would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vecResult.begin(), multiplies()); After this call to transform, vecResult(n) will contain vec1(n) times vec2(n). WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will have to write : vector > instead of : vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 negate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME negate - Unary function object that returns the negation of its argument. SYNOPSIS #include template struct negate : public unary_function; DESCRIPTION negate is a unary function object. Its operator() returns the negation of its argument, i.e., true if its argument is false, or false if its argument is true. You can pass a negate object to any algorithm that requires a unary function. For example, the transform algorithm applies a unary operation to the values in a collection and stores the result. negate could be used in that algorithm in the following manner: vector vec1; vector vecResult; transform(vec1.begin(), vec1.end(), vecResult.begin(), negate()); After this call to transform, vecResult(n) will contain the negation of the element in vec1(n). INTERFACE template struct negate : unary_function { typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; T operator() (const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO function objects, unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Negators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Negators - Function adaptors and function objects used to reverse the sense of predicate function objects. SYNOPSIS #include template class unary_negate; template unary_negate not1(const Predicate&); template class binary_negate; template binary_negate not2(const Predicate&); DESCRIPTION Negators not1 and not2 are functions that take predicate function objects as arguments and return predicate function objects with the opposite sense. Negators work only with function objects defined as subclasses of the classes unary_function and binary_function. not1 accepts and returns unary predicate function objects. not2 accepts and returns binary predicate function objects. unary_negate and binary_negate are function object classes that provide return types for the negators, not1 and not2. INTERFACE template class unary_negate : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; explicit unary_negate (const Predicate&); bool operator() (const argument_type&) const; }; template unary_negate not1 (const Predicate&); template class binary_negate : public binary_function { public: typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; explicit binary_negate (const Predicate&); bool operator() (const first_argument_type&, const second_argument_type&) const; }; template binary_negate not2 (const Predicate&); EXAMPLE // // negator.cpp // #include #include #include //Create a new predicate from unary_function template class is_odd : public unary_function { public: bool operator()(const Arg& arg1) const { return (arg1 % 2 ? true : false); } }; int main() { less less_func; // Use not2 on less cout << (less_func(1,4) ? "TRUE" : "FALSE") << endl; cout << (less_func(4,1) ? "TRUE" : "FALSE") << endl; cout << (not2(less())(1,4) ? "TRUE" : "FALSE") << endl; cout << (not2(less())(4,1) ? "TRUE" : "FALSE") << endl; //Create an instance of our predicate is_odd odd; // Use not1 on our user defined predicate cout << (odd(1) ? "TRUE" : "FALSE") << endl; cout << (odd(4) ? "TRUE" : "FALSE") << endl; cout << (not1(odd)(1) ? "TRUE" : "FALSE") << endl; cout << (not1(odd)(4) ? "TRUE" : "FALSE") << endl; return 0; } Output : TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE SEE ALSO algorithm, binary_function, function_object, unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 not1 Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME not1 - Function adaptor used to reverse the sense of a unary predicate function object. SYNOPSIS #include template unary_negate not1 (const Predicate&); DESCRIPTION not1 is a function adaptor, known as a negator, that takes a unary predicate function object as its argument and returns a unary predicate function object that is the complement of the original. unary_negate is a function object class that provides a return type for the not1 negator. Note that not1 works only with function objects that are defined as subclasses of the class unary_function. SEE ALSO negators, not2, unary_function, unary_negate, pointer_to_unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 not2 Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME not2 - Function adaptor used to reverse the sense of a binary predicate function object. SYNOPSIS #include template binary_negate not2 (const Predicate& pred); DESCRIPTION not2 is a function adaptor, known as a negator, that takes a binary predicate function object as its argument and returns a binary predicate function object that is the complement of the original. binary_negate is a function object class that provides a return type for the not2 negator. Note that not2 works only with function objects that are defined as subclasses of the class binary_function. SEE ALSO binary_function, binary_negate, negators, not1, pointer_to_binary_function, unary_negate STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 not_equal_to Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME not_equal_to - Binary function object that returns true if its first argument is not equal to its second. SYNOPSIS #include template struct not_equal_to : public binary_function ; DESCRIPTION not_equal_to is a binary function object. Its operator() returns true if x is not equal to y. You can pass a not_equal_to object to any algorithm that requires a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. not_equal_to would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), not_equal_to()); After this call to transform, vecResult(n) will contain a "1" if vec1(n) was not equal to vec2(n) or a "1" if vec1(n) was equal to vec2(n). INTERFACE template struct not_equal_to : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; bool operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO binary_function, function object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 plus Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME plus - A binary function object that returns the result of adding its first and second arguments. SYNOPSIS #include template struct plus : public binary_function ; DESCRIPTION plus is a binary function object. Its operator() returns the result of adding x and y. You can pass a plus object to any algorithm that uses a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. plus would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), plus()); After this call to transform, vecResult(n) will contain vec1(n) plus vec2(n). INTERFACE template struct plus : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write: vector > instead of : vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 Predicates Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME Predicates - A function or a function object that returns a boolean (true/false) value or an integer value. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 times Standard C++ Library NAME times - A binary function object that returns the result of multiplying its first and second arguments. SYNOPSIS #include template struct times : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; DESCRIPTION times is a binary function object. Its operator() returns the result of multiplying x and y. You can pass a times object to any algorithm that uses a binary function. For example, the transform algorithm applies a binary operation to corresponding values in two collections and stores the result. times would be used in that algorithm in the following manner: vector vec1; vector vec2; vector vecResult; transform(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vecResult.begin(), times()); After this call to transform, vecResult(n) will contain vec1(n) times vec2(n). WARNING If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you will have to write : vector instead of : vector SEE ALSO binary_function, function objects STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 unary_function Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME unary_function - Base class for creating unary function objects. SYNOPSIS #include template struct unary_function{ typedef Arg argument_type; typedef Result result_type; }; DESCRIPTION Function objects are objects with an operator() defined. They are important for the effective use of the standard library's generic algorithms, because the interface for each algorithmic template can accept either an object with an operator() defined or a pointer to a function. The standard library provides both a standard set of function objects, and a pair of classes that you can use as the base for creating your own function objects. Function objects that take one argument are called unary function objects. Unary function objects are required to provide the typedefs argument_type and result_type. The unary_function class makes the task of creating templated unary function objects easier by providing the necessary typedefs for a unary function object. You can create your own unary function objects by inheriting from unary_function. SEE ALSO function objects, and Function Objects Section in User's Guide. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 unary_negate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME unary_negate - Function object that returns the complement of the result of its unary predicate SYNOPSIS #include template class unary_negate : public unary_function; DESCRIPTION unary_negate is a function object class that provides a return type for the function adapter not1. not1 is a function adapter, known as a negator, that takes a unary predicate function object as its argument and returns a unary predicate function object that is the complement of the original. Note that not1 works only with function objects that are defined as subclasses of the class unary_function. INTERFACE template class unary_negate : public unary_function { typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; public: explicit unary_negate (const Predicate&); bool operator() (const argument_type&) const; }; template unary_negate not1 (const Predicate&); CONSTRUCTOR explicit unary_negate(const Predicate& pred); Construct a unary_negate object from predicate pred. OPERATOR bool operator()(const argument_type& x) const; Return the result of pred(x) SEE ALSO not1, not2, unary_function, binary_negate STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 binary_function Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME binary_function - Base class for creating binary function objects. SYNOPSIS #include template struct binary_function{ typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; }; DESCRIPTION Function objects are objects with an operator() defined. They are important for the effective use of the standard library's generic algorithms, because the interface for each algorithmic template can accept either an object with an operator() defined or a pointer to a function. The Standard C++ Library provides both a standard set of function objects, and a pair of classes that you can use as the base for creating your own function objects. Function objects that take two arguments are called binary function objects. Binary function objects are required to provide the typedefs first_argument_type, second_argument_type, and result_type. The binary_function class makes the task of creating templated binary function objects easier by providing the necessary typedefs for a binary function object. You can create your own binary function objects by inheriting from binary_function. SEE ALSO function objects_ unary_function, the Function Objects section of the User's Guide. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 binary_negate Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME binary_negate - Function object that returns the complement of the result of its binary predicate SYNOPSIS #include template class binary_negate ; DESCRIPTION binary_negate is a function object class that provides a return type for the function adaptor not2. not2 is a function adaptor, known as a negator, that takes a binary predicate function object as its argument and returns a binary predicate function object that is the complement of the original. Note that not2 works only with function objects that are defined as subclasses of the class binary_function. INTERFACE template class binary_negate : public binary_function { public: typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; explicit binary_negate (const Predicate&); bool operator() (const first_argument_type&, const second_argument_type&) const; }; // Non-member Functions template binary_negate not2 (const Predicate& pred); CONSTRUCTOR explicit binary_negate(const Predicate& pred); Construct a binary_negate object from predicate pred. OPERATOR bool operator()(const first_argument_type& x, const second_argument_type& y) const; Return the result of pred(x,y) SEE ALSO binary_function, not2, unary_negate STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Adaptors 3 bind1st Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME bind1st, bind2nd, binder1st, binder2nd - Templatized utilities to bind values to function objects SYNOPSIS #include template class binder1st : public unary_function ; template binder1st bind1st (const Operation&, const T&); template class binder2nd : public unary_function ; template binder2nd bind2nd (const Operation&, const T&); DESCRIPTION Because so many functions provided by the standard library take other functions as arguments, the library includes classes that let you build new function objects out of old ones. Both bind1st() and bind2nd() are functions that take as arguments a binary function object f and a value x, and return, respectively, classes binder1st and binder2nd. The underlying function object must be a subclass of binary_function. Class binder1st binds the value to the first argument of the binary function, and binder2nd does the same thing for the second argument of the function. The resulting classes can be used in place of a unary predicate in other function calls. For example, you could use the count_if algorithm to count all elements in a vector that are less than or equal to 7, using the following: count_if (v.begin, v.end, bind1st(greater (),7), littleNums) This function adds one to littleNums each time the predicate is true, i.e., each time 7 is greater than the element. INTERFACE // Class binder1st template class binder1st : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder1st(const Operation&, const typename Operation::first_argument_type&); result_type operator() (const argument_type&) const; }; // Class binder2nd template class binder2nd : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder2nd(const Operation&, const typename Operation::second_argument_type&); result_type operator() (const argument_type&) const; }; // Creator bind1st template binder1st bind1st (const Operation&, const T&); // Creator bind2nd template binder2nd bind2nd(const Operation&, const T&); EXAMPLE // // binders.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[4] = {1,2,3,4}; // // Set up a vector // vector v1(d1,d1 + 4); // // Create an 'equal to 3' unary predicate by binding 3 to // the equal_to binary predicate. // binder1st > equal_to_3 = bind1st(equal_to(),3); // // Now use this new predicate in a call to find_if // iterator it1 = find_if(v1.begin(),v1.end(),equal_to_3); // // Even better, construct the new predicate on the fly // iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // // And now the same thing using bind2nd // Same result since == is commutative // iterator it3 = find_if(v1.begin(),v1.end(),bind2nd(equal_to(),3)); // // it3 = v1.begin() + 2 // // Output results // cout << *it1 << " " << *it2 << " " << *it3 << endl; return 0; } Output : 3 3 3 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Function Object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 bind2nd Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME bind1st, bind2nd, binder1st, binder2nd - Templatized utilities to bind values to function objects SYNOPSIS #include template class binder1st : public unary_function ; template binder1st bind1st (const Operation&, const T&); template class binder2nd : public unary_function ; template binder2nd bind2nd (const Operation&, const T&); DESCRIPTION Because so many functions provided by the standard library take other functions as arguments, the library includes classes that let you build new function objects out of old ones. Both bind1st() and bind2nd() are functions that take as arguments a binary function object f and a value x, and return, respectively, classes binder1st and binder2nd. The underlying function object must be a subclass of binary_function. Class binder1st binds the value to the first argument of the binary function, and binder2nd does the same thing for the second argument of the function. The resulting classes can be used in place of a unary predicate in other function calls. For example, you could use the count_if algorithm to count all elements in a vector that are less than or equal to 7, using the following: count_if (v.begin, v.end, bind1st(greater (),7), littleNums) This function adds one to littleNums each time the predicate is true, i.e., each time 7 is greater than the element. INTERFACE // Class binder1st template class binder1st : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder1st(const Operation&, const typename Operation::first_argument_type&); result_type operator() (const argument_type&) const; }; // Class binder2nd template class binder2nd : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder2nd(const Operation&, const typename Operation::second_argument_type&); result_type operator() (const argument_type&) const; }; // Creator bind1st template binder1st bind1st (const Operation&, const T&); // Creator bind2nd template binder2nd bind2nd(const Operation&, const T&); EXAMPLE // // binders.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[4] = {1,2,3,4}; // // Set up a vector // vector v1(d1,d1 + 4); // // Create an 'equal to 3' unary predicate by binding 3 to // the equal_to binary predicate. // binder1st > equal_to_3 = bind1st(equal_to(),3); // // Now use this new predicate in a call to find_if // iterator it1 = find_if(v1.begin(),v1.end(),equal_to_3); // // Even better, construct the new predicate on the fly // iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // // And now the same thing using bind2nd // Same result since == is commutative // iterator it3 = find_if(v1.begin(),v1.end(),bind2nd(equal_to(),3)); // // it3 = v1.begin() + 2 // // Output results // cout << *it1 << " " << *it2 << " " << *it3 << endl; return 0; } Output : 3 3 3 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Function Object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 binder1st Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME bind1st, bind2nd, binder1st, binder2nd - Templatized utilities to bind values to function objects SYNOPSIS #include template class binder1st : public unary_function ; template binder1st bind1st (const Operation&, const T&); template class binder2nd : public unary_function ; template binder2nd bind2nd (const Operation&, const T&); DESCRIPTION Because so many functions provided by the standard library take other functions as arguments, the library includes classes that let you build new function objects out of old ones. Both bind1st() and bind2nd() are functions that take as arguments a binary function object f and a value x, and return, respectively, classes binder1st and binder2nd. The underlying function object must be a subclass of binary_function. Class binder1st binds the value to the first argument of the binary function, and binder2nd does the same thing for the second argument of the function. The resulting classes can be used in place of a unary predicate in other function calls. For example, you could use the count_if algorithm to count all elements in a vector that are less than or equal to 7, using the following: count_if (v.begin, v.end, bind1st(greater (),7), littleNums) This function adds one to littleNums each time the predicate is true, i.e., each time 7 is greater than the element. INTERFACE // Class binder1st template class binder1st : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder1st(const Operation&, const typename Operation::first_argument_type&); result_type operator() (const argument_type&) const; }; // Class binder2nd template class binder2nd : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder2nd(const Operation&, const typename Operation::second_argument_type&); result_type operator() (const argument_type&) const; }; // Creator bind1st template binder1st bind1st (const Operation&, const T&); // Creator bind2nd template binder2nd bind2nd(const Operation&, const T&); EXAMPLE // // binders.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[4] = {1,2,3,4}; // // Set up a vector // vector v1(d1,d1 + 4); // // Create an 'equal to 3' unary predicate by binding 3 to // the equal_to binary predicate. // binder1st > equal_to_3 = bind1st(equal_to(),3); // // Now use this new predicate in a call to find_if // iterator it1 = find_if(v1.begin(),v1.end(),equal_to_3); // // Even better, construct the new predicate on the fly // iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // // And now the same thing using bind2nd // Same result since == is commutative // iterator it3 = find_if(v1.begin(),v1.end(),bind2nd(equal_to(),3)); // // it3 = v1.begin() + 2 // // Output results // cout << *it1 << " " << *it2 << " " << *it3 << endl; return 0; } Output : 3 3 3 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Function Object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 binder2nd Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME bind1st, bind2nd, binder1st, binder2nd - Templatized utilities to bind values to function objects SYNOPSIS #include template class binder1st : public unary_function ; template binder1st bind1st (const Operation&, const T&); template class binder2nd : public unary_function ; template binder2nd bind2nd (const Operation&, const T&); DESCRIPTION Because so many functions provided by the standard library take other functions as arguments, the library includes classes that let you build new function objects out of old ones. Both bind1st() and bind2nd() are functions that take as arguments a binary function object f and a value x, and return, respectively, classes binder1st and binder2nd. The underlying function object must be a subclass of binary_function. Class binder1st binds the value to the first argument of the binary function, and binder2nd does the same thing for the second argument of the function. The resulting classes can be used in place of a unary predicate in other function calls. For example, you could use the count_if algorithm to count all elements in a vector that are less than or equal to 7, using the following: count_if (v.begin, v.end, bind1st(greater (),7), littleNums) This function adds one to littleNums each time the predicate is true, i.e., each time 7 is greater than the element. INTERFACE // Class binder1st template class binder1st : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder1st(const Operation&, const typename Operation::first_argument_type&); result_type operator() (const argument_type&) const; }; // Class binder2nd template class binder2nd : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder2nd(const Operation&, const typename Operation::second_argument_type&); result_type operator() (const argument_type&) const; }; // Creator bind1st template binder1st bind1st (const Operation&, const T&); // Creator bind2nd template binder2nd bind2nd(const Operation&, const T&); EXAMPLE // // binders.cpp // #include #include #include #include int main() { typedef vector::iterator iterator; int d1[4] = {1,2,3,4}; // // Set up a vector // vector v1(d1,d1 + 4); // // Create an 'equal to 3' unary predicate by binding 3 to // the equal_to binary predicate. // binder1st > equal_to_3 = bind1st(equal_to(),3); // // Now use this new predicate in a call to find_if // iterator it1 = find_if(v1.begin(),v1.end(),equal_to_3); // // Even better, construct the new predicate on the fly // iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // // And now the same thing using bind2nd // Same result since == is commutative // iterator it3 = find_if(v1.begin(),v1.end(),bind2nd(equal_to(),3)); // // it3 = v1.begin() + 2 // // Output results // cout << *it1 << " " << *it2 << " " << *it3 << endl; return 0; } Output : 3 3 3 WARNINGS If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write: vector > instead of: vector SEE ALSO Function Object STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 mem_fun Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME mem_fun, mem_fun1, mem_fun_ref, mem_fun_ref1 - Function objects that adapt a pointer to a member function to work where a global function is called for. SYNOPSIS #include template class mem_fun_t; template class mem_fun1_t; template class mem_fun_ref_t; template class mem_fun1_ref_t; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); DESCRIPTION The mem_fun group of templates each encapsulates a pointer to a member function. Each category of template (i.e. mem_fun, mem_fun1, mem_fun_ref, or mem_fun1_ref) provides both a class template and a function template, where the class is distinguished by the addition of _t on the end of the name to identify it as a type. The class's constructor takes a pointer to a member function, and provides an operator() that forwards the call to that member function. In this way the resulting object serves as a global function object for that member function. The accompanying function template simplifies the use of this facility by constructing an instance of the class on the fly. The library provides zero and one argument adaptors for containers of pointers and containers of references (_ref). This technique can be easily extended to include adaptors for two argument functions, and so on. INTERFACE template class mem_fun_t : public unary_function { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_t : public binary_function { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template class mem_fun_ref_t : public unary_function { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_ref_t : public binary_function { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); EXAMPLE // // mem_fun example // #include #include int main(void) { int a1[] = {2,1,5,6,4}; int a2[] = {11,4,67,3,14}; list s1(a1,a1+5); list s2(a2,a2+5); // Build a list of lists list* > l; l.insert(l.begin(),s1); l.insert(l.begin(),s2); // Sort each list in the list for_each(l.begin(),l.end(),mem_fun(&list::sort)); } SEE ALSO binary_function, function_objects, pointer_to_unary_function, ptr_fun STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 mem_fun1 Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME mem_fun, mem_fun1, mem_fun_ref, mem_fun_ref1 - Function objects that adapt a pointer to a member function to work where a global function is called for. SYNOPSIS #include template class mem_fun_t; template class mem_fun1_t; template class mem_fun_ref_t; template class mem_fun1_ref_t; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); DESCRIPTION The mem_fun group of templates each encapsulates a pointer to a member function. Each category of template (i.e. mem_fun, mem_fun1, mem_fun_ref,or mem_fun1_ref) provides both a class template and a function template, where the class is distinguished by the addition of _t on the end of the name to identify it as a type. The class's constructor takes a pointer to a member function, and provides an operator() that forwards the call to that member function. In this way the resulting object serves as a global function object for that member function. The accompanying function template simplifies the use of this facility by constructing an instance of the class on the fly. The library provides zero and one argument adaptors for containers of pointers and containers of references (_ref). This technique can be easily extended to include adaptors for two argument functions, and so on. INTERFACE template class mem_fun_t : public unary_function { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_t : public binary_function { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template class mem_fun_ref_t : public unary_function { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_ref_t : public binary_function { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); EXAMPLE // // mem_fun example // #include #include int main(void) { int a1[] = {2,1,5,6,4}; int a2[] = {11,4,67,3,14}; list s1(a1,a1+5); list s2(a2,a2+5); // Build a list of lists list* > l; l.insert(l.begin(),s1); l.insert(l.begin(),s2); // Sort each list in the list for_each(l.begin(),l.end(),mem_fun(&list::sort)); } SEE ALSO binary_function, function_objects, pointer_to_unary_function, ptr_fun STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 mem_fun_ref Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME mem_fun, mem_fun1, mem_fun_ref, mem_fun_ref1 - Function objects that adapt a pointer to a member function to work where a global function is called for. SYNOPSIS #include template class mem_fun_t; template class mem_fun1_t; template class mem_fun_ref_t; template class mem_fun1_ref_t; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); DESCRIPTION The mem_fun group of templates each encapsulates a pointer to a member function. Each category of template (i.e. mem_fun, mem_fun1, mem_fun_ref, or mem_fun1_ref) provides both a class template and a function template, where the class is distinguished by the addition of _t on the end of the name to identify it as a type. The class's constructor takes a pointer to a member function, and provides an operator() that forwards the call to that member function. In this way the resulting object serves as a global function object for that member function. The accompanying function template simplifies the use of this facility by constructing an instance of the class on the fly. The library provides zero and one argument adaptors for containers of pointers and containers of references (_ref). This technique can be easily extended to include adaptors for two argument functions, and so on. INTERFACE template class mem_fun_t : public unary_function { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_t : public binary_function { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template class mem_fun_ref_t : public unary_function { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_ref_t : public binary_function { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); EXAMPLE // // mem_fun example // #include #include int main(void) { int a1[] = {2,1,5,6,4}; int a2[] = {11,4,67,3,14}; list s1(a1,a1+5); list s2(a2,a2+5); // Build a list of lists list* > l; l.insert(l.begin(),s1); l.insert(l.begin(),s2); // Sort each list in the list for_each(l.begin(),l.end(),mem_fun(&list::sort)); } SEE ALSO binary_function, function_objects, pointer_to_unary_function, ptr_fun STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 mem_fun_ref1 Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME mem_fun, mem_fun1, mem_fun_ref, mem_fun_ref1 - Function objects that adapt a pointer to a member function to work where a global function is called for. SYNOPSIS #include template class mem_fun_t; template class mem_fun1_t; template class mem_fun_ref_t; template class mem_fun1_ref_t; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); DESCRIPTION The mem_fun group of templates each encapsulates a pointer to a member function. Each category of template (i.e. mem_fun, mem_fun1, mem_fun_ref, or mem_fun1_ref) provides both a class template and a function template, where the class is distinguished by the addition of _t on the end of the name to identify it as a type. The class's constructor takes a pointer to a member function, and provides an operator() that forwards the call to that member function. In this way the resulting object serves as a global function object for that member function. The accompanying function template simplifies the use of this facility by constructing an instance of the class on the fly. The library provides zero and one argument adaptors for containers of pointers and containers of references (_ref). This technique can be easily extended to include adaptors for two argument functions, and so on. INTERFACE template class mem_fun_t : public unary_function { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_t : public binary_function { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_t mem_fun(S, (T::*f)()); template mem_fun1_t mem_fun1(S, (T::*f)(A)); template class mem_fun_ref_t : public unary_function { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T* p); }; template class mem_fun1_ref_t : public binary_function { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T* p, A x); }; template mem_fun_ref_t mem_fun_ref(S, (T::*f)()); template mem_fun1_ref_t mem_fun1_ref(S, (T::*f)(A)); EXAMPLE // // mem_fun example // #include #include int main(void) { int a1[] = {2,1,5,6,4}; int a2[] = {11,4,67,3,14}; list s1(a1,a1+5); list s2(a2,a2+5); // Build a list of lists list* > l; l.insert(l.begin(),s1); l.insert(l.begin(),s2); // Sort each list in the list for_each(l.begin(),l.end(),mem_fun(&list::sort)); } SEE ALSO binary_function, function_objects, pointer_to_unary_function, ptr_fun STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Operators 3 Operators Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME operator!=, operator>, operator<=, operator>= - Operators for the C++ Standard C++ Library SYNOPSIS #include namespace rel_ops { template bool operator!= (const T&, const T&); template bool operator> (const T&, const T&); template bool operator<= (const T&, const T&); template bool operator>= (const T&, const T&); } DESCRIPTION To avoid redundant definitions of operator!= out of operator== and of operators >, <=, and >= out of operator<, the library provides these definitions: operator!= returns !(x==y), operator> returns y= returns !(x template struct pair ; DESCRIPTION The pair class provides a template for encapsulating pairs of values that may be of different types. INTERFACE template struct pair { T1 first; T2 second; pair(); pair (const T1&, const T2&); ~pair(); }; template bool operator== (const pair&, const pair T1, T2>&); template bool operator!= (const pair&, const pair T1, T2>&); template bool operator< (const pair&, const pair T1, T2>&); template bool operator> (const pair&, const pair T1, T2>&); template bool operator<= (const pair&, const pair T1, T2>&); template bool operator>= (const pair&, const pair T1, T2>&); template pair make_pair (const T1&, const T2&); CONSTRUCTORS AND DESTRUCTORS pair (); Default constructor. Initializes first and second using their default constructors. pair (const T1& x, const T2& y); The constructor creates a pair of types T1 and T2, making the necessary conversions in x and y. ~pair (); Destructor. NON-MEMBER OPERATORS template bool operator== (const pair& x, const pair T1, T2>& y); Returns true if (x.first == y.first && x.second == y.second) is true. Otherwise it returns false. template bool operator!= (const pair& x, const pair T1, T2>& y); Returns !(x==y). template bool operator< (const pair& x, const pair T1, T2>& y); Returns true if (x.first < y.first || (!(y.first < x.first) && x.second < y.second)) is true. Otherwise it returns false. template bool operator> (const pair& x, const pair T1, T2>& y); Returns y < x. template bool operator<= (const pair& x, const pair T1, T2>& y); Returns !(y < x). template bool operator>= (const pair& x, const pair T1, T2>& y); Returns !(x < y). NON-MEMBER FUNCTIONS template pair make_pair(x,y); make_pair(x,y) creates a pair by deducing and returning the types of x and y. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 pointer_to_binary_function Standard C++ Library NAME pointer_to_binary_function - A function object which adapts a pointer to a binary function to work where a binary_function is called for. SYNOPSIS #include template class pointer_to_binary_function : public binary_function ; DESCRIPTION The pointer_to_binary_function class encapsulates a pointer to a two- argument function. The class provides an operator() so that the resulting object serves as a binary function object for that function. The ptr_fun function is overloaded to create instances of a pointer_to_binary_function when provided with the appropriate pointer to a function. INTERFACE template class pointer_to_binary_function : public binary_function { public: typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; explicit pointer_to_binary_function (Result (*f)(Arg1, Arg2)); Result operator() (const Arg1&, const Arg2&) const; }; template pointer_to_binary_function ptr_fun (Result (*x)(Arg1, Arg2)); SEE ALSO binary_function, function_objects, pointer_to_unary_function, ptr_fun STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 pointer_to_unary_function Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME pointer_to_unary_function - A function object class that adapts a pointer to a function to work where a unary_function is called for. SYNOPSIS #include template class pointer_to_unary_function : public unary_function; DESCRIPTION The pointer_to_unary_function class encapsulates a pointer to a single-argument function. The class provides an operator() so that the resulting object serves as a function object for that function. The ptr_fun function is overloaded to create instances of pointer_to_unary_function when provided with the appropriate pointer to a function. INTERFACE template class pointer_to_unary_function : public unary_function { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; explicit pointer_to_unary_function (Result (*f)(Arg)); Result operator() (const Arg&) const; }; template pointer_to_unary_function ptr_fun (Result (*f)(Arg)); SEE ALSO function_objects, pointer_to_binary_function, ptr_fun, unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 ptr_fun Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME ptr_fun - A function that is overloaded to adapt a pointer to a function to work where a function is called for. SYNOPSIS #include template pointer_to_unary_function ptr_fun (Result (*f)(Arg)); template pointer_to_binary_function ptr_fun (Result (*x)(Arg1, Arg2)); DESCRIPTION The pointer_to_unary_function and pointer_to_binary_function classes encapsulate pointers to functions and provide an operator() so that the resulting object serves as a function object for the function. The ptr_fun function is overloaded to create instances of pointer_to_unary_function or pointer_to_binary_function when provided with the appropriate pointer to a function. EXAMPLE // // pnt2fnct.cpp // #include #include #include #include #include //Create a function int factorial(int x) { int result = 1; for(int i = 2; i <= x; i++) result *= i; return result; } int main() { //Initialize a deque with an array of ints int init[7] = {1,2,3,4,5,6,7}; deque d(init, init+7); //Create an empty vector to store the factorials vector v((size_t)7); //Transform the numbers in the deque to their factorials and //store in the vector transform(d.begin(), d.end(), v.begin(), ptr_fun(factorial)); //Print the results cout << "The following numbers: " << endl << " "; copy(d.begin(),d.end(),ostream_iterator(cout," ")); cout << endl << endl; cout << "Have the factorials: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); return 0; } Output : The following numbers: 1 2 3 4 5 6 7 Have the factorials: 1 2 6 24 120 720 5040 WARNING If your compiler does not support default template parameters, you need to always supply the Allocator template argument. For instance, you will need to write : vector > instead of : vector SEE ALSO function_objects, pointer_to_binary_function, pointer_to_unary_function STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 allocator Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME allocator - The default allocator object for storage management in Standard Library containers. SYNOPSIS #include template class allocator; DESCRIPTION Containers in the Standard Library allow you control of storage management through the use of allocator objects. Each container has an allocator template parameter specifying the type of allocator to be used. Every constructor, except the copy constructor, provides an allocator parameter, allowing you to pass in a specific allocator. A container uses that allocator for all storage management. The library provides a default allocator, called allocator. This allocator uses the global new and delete operators. By default, all containers use this allocator. You can also design your own allocator, but if you do so it must provide an appropriate interface. The standard interface is specified below. STANDARD INTERFACE template 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; template struct rebind; allocator () throw(); template allocator(const allocator&) throw(); template allocator& operator=(const allocator&) throw(); ~allocator () throw(); pointer address (reference) const; const_pointer address (const_reference) const; pointer allocate (size_type, typename allocator const_pointer = 0); void deallocate(pointer); size_type max_size () const; void construct (pointer, const T&); void destroy (pointer); }; // specialize for void: template <> class allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef void* pointer; typedef const void* const_pointer; // reference-to-void members are impossible. typedef void value_type; template struct rebind { typedef allocator other; }; allocator() throw(); template allocator(const allocator&) throw(); template allocator operator=(const allocator&) throw(); ~allocator() throw(); pointer allocate(size_type, const void* hint); void deallocate(pointer p); size_type max_size() const throw(); }; // globals template void* operator new(size_t N, allocator& a); template bool operator==(const allocator&, const allocator&) throw(); template bool operator!=(const allocator&, const allocator&) throw(); TYPES size_type Type used to hold the size of an allocated block of storage. difference_type Type used to hold values representing distances between storage addresses. pointer Type of pointer returned by allocator. const_pointer Const version of pointer. reference Type of reference to allocated objects. const_reference Const version of reference. value_type Type of allocated object. template struct rebind; Provides a way to convert an allocator templated on one type to an allocator templated on another type. This struct contains a single type member: typedef allocator other. OPERATIONS allocator() Default constructor. template allocator(const allocator&) Copy constructor. template allocator& operator=(const allocator&) throw()>&) Assignment operator. ~allocator() Destructor. pointer address(reference x) const; Returns the address of the reference x as a pointer. const_pointer address(const_reference x) const; Returns the address of the reference x as a const_pointer. pointer allocate(size_type n, typename allocator::const_pointer p = 0) Allocates storage. Returns a pointer to the first element in a block of storage n*sizeof(T) bytes in size. The block will be aligned appropriately for objects of type T. Throws the exception bad_alloc if the storage is unavailable. This function uses operator new(size_t). The second parameter p can be used by an allocator to localize memory allocation, but the default allocator does not use it. void deallocate(pointer p) Deallocates the storage indicated by p. The storage must have been obtained by a call to allocate. size_type max_size () const; Returns the largest size for which a call to allocate might succeed. void construct (pointer p, const T& val); Constructs an object of type T2 with the initial value of val at the location specified by p. This function calls the placement new operator. void destroy (pointer p) Calls the destructor on the object pointed to by p, but does not delete. See the container section of the Class Reference for a further description of how to use the alternate allocator within a user-defined container. SEE ALSO container STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 get_temporary_buffer Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME get_temporary_buffer - Pointer based primitive for handling memory SYNOPSIS #include template pair get_temporary_buffer (ptrdiff_t, T*); DESCRIPTION The get_temporary_buffer templated function reserves from system memory the largest possible buffer that is less than or equal to the size requested (n*sizeof(T)), and returns a pair containing the address and size of that buffer. The units used to describe the capacity are in sizeof(T). SEE ALSO allocate, construct, deallocate, pair, return_temporary_buffer. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 return_temporary_buffer Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME return_temporary_buffer - Pointer based primitive for handling memory SYNOPSIS #include template void return_temporary_buffer (T* p, T*); DESCRIPTION The return_temporary_buffer templated function returns a buffer, previously allocated through get_temporary_buffer, to available memory. Parameter p points to the buffer. SEE ALSO allocate, deallocate, construct, get_temporary_buffer STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 auto_ptr Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME auto_ptr_ - A simple, smart pointer class. SYNOPSIS #include template class auto_ptr; DESCRIPTION The template class auto_ptr holds onto a pointer obtained via new and deletes that object when the auto_ptr object itself is destroyed (such as when leaving block scope). auto_ptr can be used to make calls to operator new exception-safe. The auto_ptr class provides semantics of strict ownership: an object may be safely pointed to by only one auto_ptr, so copying an auto_ptr copies the pointer and transfers ownership to the destination if the source had already had ownership. INTERFACE template class auto_ptr { public: // constructor/copy/destroy explicit auto_ptr (X* = 0) throw(); template auto_ptr (const auto_ptr&) throw(); template void operator= (const auto_ptr&) throw(); ~auto_ptr (); // members X& operator* () const throw(); X* operator-> () const throw(); X* get () const throw(); X* release () throw(); }; CONSTRUCTORS AND DESTRUCTORS explicit auto_ptr (X* p = 0); Constructs an object of class auto_ptr, initializing the held pointer to p, and acquiring ownership of that pointer. Requires that p points to an object of class X or a class derived from X for which delete p is defined and accessible, or that p is a null pointer. template auto_ptr (const auto_ptr& a); Copy constructor. Constructs an object of class auto_ptr, and copies the argument a to *this. If a owned the underlying pointer then *this becomes the new owner of that pointer. ~auto_ptr (); Deletes the underlying pointer. OPERATORS template void operator= (const auto_ptr& a); Assignment operator. Copies the argument a to *this. If *this becomes the new owner of the underlying pointer. If a owned the underlying pointer then *this becomes the new owner of that pointer. If *this already owned a pointer, then that pointer is deleted first. X& operator* () const; Returns a reference to the object to which the underlying pointer points. X* operator-> () const; Returns the underlying pointer. MEMBER FUNCTIONS X* get () const; Returns the underlying pointer. X* release(); Releases ownership of the underlying pointer. Returns that pointer. EXAMPLE // // auto_ptr.cpp // #include #include // // A simple structure. // struct X { X (int i = 0) : m_i(i) { } int get() const { return m_i; } int m_i; }; int main () { // // b will hold a pointer to an X. // auto_ptr b(new X(12345)); // // a will now be the owner of the underlying pointer. // auto_ptr a = b; // // Output the value contained by the underlying pointer. // cout << a->get() << endl; // // The pointer will be deleted when a is destroyed on // leaving scope. // return 0; } Output : 12345 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 Runtime_Support 3 new Standard C++ Library NAME new - The new operators (used to allocate dynamic storage in a program) are declared in the header . SYNOPSIS #include void *operator new(size_t n) throw(std::bad_alloc); void *operator new(size_t n, const std::nothrow_t&) throw(); void *operator new(size_t n, void *p) throw(); void *operator new[](size_t n) throw(std::bad_alloc); void *operator new[](size_t n,const std::nothrow_t&) throw(); void *operator new[](size_t n, void *p) throw(); DESCRIPTION void *operator new(size_t n) throw(std::bad_alloc); void *operator new(size_t n, const std::nothrow_t&) throw() These versions of new are called to allocate n bytes of suitably aligned storage to represent an object of that size. A C++ program can define a function with either of these signatures which is intended to replace the implementation provided default provided by the Standard C++ Library. Both return a non-null pointer when memory allocation succeeds. The first function throws bad_alloc on memory allocation failure. The second or nothrow version of operator new returns null on memory allocation failure. void *operator new(size_t n, void *p) throw(); This function is called by a placement new expression which looks like new (p) T, where p is a pointer to an object. The function returns p. void *operator new[](size_t n) throw(std::bad_alloc); void *operator new[](size_t n,const std::nothrow_t&) throw(); The next two functions are called by a new[] expression i.e. by the array form of a new expression. They are called to allocate n bytes of suitably aligned storage to represent an array object of that or smaller size. A C++ program can define a function with either of these signatures which is intended to replace the default implementation provided by the Standard C++ Library. Both return a non-null pointer when memory allocation succeeds. The first function throws bad_alloc on memory allocation failure. The second or nothrow version of operator new returns null on memory allocation failure. void *operator new[](size_t n, void *p) throw(); This function is called by a placement array new expression which looks like new (p) T[n], where p is a pointer to an object. The function returns p. SEE ALSO delete, bad_alloc, no_throw STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 new_handler Standard C++ Library NAME new_handler, set_new_handler - new_handler is the type of a function called by operator new() or operator new []() when a request for storage can not be met. set_new_handler() is a function which sets the current new_handler. SYNOPSIS #include namespace std { typedef void (*new_handler)(); new_handler set_new_handler(new_handler new_h) throw(); } DESCRIPTION set_new_handler() sets the current new_handler to the the function passed in as its new_handler input parameter. It returns the previous new_handler. A function of type new_handler is required to do one of the following: o make more storage available for allocation and return o throw an exception of type bad_alloc or a class derived from bad_alloc o call abort() or exit() The Standard C++ Library provides a default new_handler which throws an exception of type bad_alloc. The implementation provided new_handler is called by default. SEE ALSO new, bad_alloc STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 delete Standard C++ Library NAME delete - The delete operators (used to deallocate dynamic storage in a program) are declared in the header . SYNOPSIS #include void operator delete(void* ptr) throw(); void operator delete(void* ptr, const std::nothrow_t&) throw(); void operator delete(void *p, void*) throw(); void operator delete[](void *p) throw(); void operator delete[](void* ptr ,const std::nothrow_t&) throw(); void operator delete[](void* ptr, void*) throw(); DESCRIPTION void *operator delete(void* ptr) throw(); void *operator delete(void* ptr, const std::nothrow_t&) throw() These versions of delete are called by a delete expression to deallocate storeage pointed to by ptr. A C++ program can define a function with either of these signatures which is intended to replace the implementation provided default provided by the Standard C++ Library. These functions accept a value for ptr which is null or that was returned by a previous call to operator new(std::size_t) or operator new (std::size_t, const std::nothrow_t&). For a null ptr value, these functions do nothing. void operator delete(void * ptr, void *) throw(); This function is called by a placement delete expression. It complements default placement new and performs no action. void operator delete[](void* ptr) throw(); void operator delete[](void* ptr,const std::nothrow_t&) throw(); The next two functions are called by a delete[] expression i.e. by the forarray form of a delete expression. They are called with a value of ptr which is null or that was returned by a previous call to operator new[](size_t) or operator new[](size_t, const std::nothrow_t&). For a null ptr value, these functions do nothing. A C++ program can define a function with either of these signatures which is intended to replace the default implementation provided by the Standard C++ Library. void operator delete[](void* ptr, void *) throw(); This function is called by a placement array delete expression. It complements default array placement new and performs no action. SEE ALSO new, no_throw STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee NOTES Placement delete and delete applied to an array allocated with placement new is not supported in Compaq C++ Version 6.0. 3 bad_alloc Standard C++ Library NAME bad_alloc - is the type of the class which describes the exception thrown when a request for storage allocation fails. SYNOPSIS #include namespace std { class bad_alloc : public exception { public: bad_alloc() throw(); bad_alloc(const bad_alloc&) throw(); bad_alloc& operator=(const bad_alloc&) throw(); virtual ~bad_alloc() throw(); virtual const char* what() const throw(); }; } DESCRIPTION bad_alloc() throw(); This function constructs an object of class bad_alloc. bad_alloc(const bad_alloc&) throw(); bad_alloc& operator=(const bad_alloc&) throw(); These functions copy an object of class bad_alloc. virtual const char* what() const throw(); what() returns a string providing information about the error. The string returned by what() is implementation defined. SEE ALSO new, exception, new_handler STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 type_info Standard C++ Library NAME type_info - type_info is a class which describes type information generated by the implementation. Objects of class type_info store a pointer to a name for the type and an encoded value used to compare two types for equality or collating order. The names, encoding rule, and collating sequence for types are unspecified and may differ between programs. You can not copy or assign objects of class type_info. This is because the copy constructor and assignment operator are private. You construct a type_info object by: typeid o; SYNOPSIS #include namespace std { class type_info { public: virtual ~type_info(); bool operator==(const type_info& rhs) const; bool operator!=(const type_info& rhs) const; bool before(const type_info& rhs) const; const char *name() const; private: type_info(const type_info& rhs); type_info& operator=(const type_info& rhs); }; } DESCRIPTION bool operator==(const type_info& rhs) const; This function compares the current object with rhs. It returns true if the two values describe the same type. bool operator!=(const type_info& rhs) const; This function compares the current object with rhs. It returns true if the two values do not describe the same type. bool before(const type_info& rhs) const; This function compares the current object with rhs. It returns true if *this precedes rhs in the implementation's collation order. cp const char *name() const; This function returns a null terminated string which contains the name of the type. The return value is implementation defined. type_info(const type_info& rhs); type_info& operator=(const type_info& rhs); These functions copy a type_info object. Because they are private objects of type type_info can not be copied. SEE ALSO typeid STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 bad_cast Standard C++ Library NAME bad_cast - defines the type of object thrown by the implementation as an exception to report execution of an invalid dynamic-cast expression. SYNOPSIS #include namespace std { class bad_cast : public exception { public: bad_cast() throw(); bad_cast(const bad_cast&) throw(); bad_cast& operator=(const bad_cast&) throw(); virtual ~bad_cast() throw(); virtual const char* what() const throw(); }; } DESCRIPTION bad_cast() throw(); This function constructs an object of class bad_cast. bad_cast(const bad_cast&) throw(); bad_cast& operator=(const bad_cast&) throw(); These functions copy an object of class bad_cast. virtual const char* what() const throw(); what() returns a string providing information about the error. The string returned by what() is implementation defined. SEE ALSO exception, dynamic_cast STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 bad_exception Standard C++ Library NAME bad_exception - defines the type of object thrown from an unexpected handler. SYNOPSIS #include namespace std { class bad_exception : public exception { public: bad_exception() throw(); bad_exception(const bad_exception&) throw(); bad_exception& operator=(const bad_exception&) throw(); virtual ~bad_exception() throw(); virtual const char* what() const throw(); }; } DESCRIPTION bad_exception() throw(); This function constructs an object of class bad_exception. bad_exception(const bad_exception&) throw(); bad_exception& operator=(const bad_exception&) throw(); These functions copy an object of class bad_exception. virtual const char* what() const throw(); what() returns a string providing information about the error. The string returned by what() is implementation defined. SEE ALSO exception, unexpected_handler STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 bad_typeid Standard C++ Library NAME bad_typeid - defines the type of object thrown by the implementation as an exception to report a null pointer in a typeid expression. SYNOPSIS #include namespace std { class bad_typeid : public exception { public: bad_typeid() throw(); bad_typeid(const bad_typeid&) throw(); bad_typeid& operator=(const bad_typeid&) throw(); virtual ~bad_typeid() throw(); virtual const char* what() const throw(); }; } DESCRIPTION bad_typeid() throw(); This function constructs an object of class bad_typeid. bad_typeid(const bad_typeid&) throw(); bad_typeid& operator=(const bad_typeid&) throw(); These functions copy an object of class bad_typeid. virtual const char* what() const throw(); what() returns a string providing information about the error. The string returned by what() is implementation defined. SEE ALSO exception, typeid STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 exception Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME exception,logic_error,domain_error,invalid_argument,length_error, out_of_range,runtime_error,range_error,overflow_error,underflow_error- Classes supporting logic and runtime errors. SYNOPSIS #include class exception; DESCRIPTION The class exception defines the base class for the types of objects thrown as exceptions by Standard C++ Library components, and certain expressions, to report errors detected during program execution. Users can also use these exceptions to report errors in their own programs. INTERFACE class exception { public: exception () throw(); exception (const exception&) throw(); exception& operator= (const exception&) throw(); virtual ~exception () throw(); virtual const char* what () const throw(); }; class logic_error : public exception { public: logic_error (const string& what_arg); }; class domain_error : public logic_error { public: domain_error (const string& what_arg); }; class invalid_argument : public logic_error { public: invalid_argument (const string& what_arg); }; class length_error : public logic_error { public: length_error (const string& what_arg); }; class out_of_range : public logic_error { public: out_of_range (const string& what_arg); }; class runtime_error : public exception { public: runtime_error (const string& what_arg); }; class range_error : public runtime_error { public: range_error (const string& what_arg); }; class overflow_error : public runtime_error { public: overflow_error (const string& what_arg); }; class underflow_error : public runtime_error { public: underflow_error (const string& what_arg); }; CONSTRUCTORS exception() throws(); Constructs an object of class exception. exception(const exception&) throws(); The copy constructor. Copies an exception object. DESTRUCTOR virtual ~exception() throws(); Destroys an object of class exception. OPERATORS exception& operator=(const exception&) throws(); The assignment operator. Copies an exception object. MEMBER FUNCTION virtual const char* what()const throws(); Returns an implementation-defined, null-terminated byte string representing a human-readable message describing the exception. The message may be a null-terminated multibyte string, suitable for conversion and display as a wstring. CONSTRUCTORS FOR DERIVED CLASSES logic_error::logic_error(const string& what_arg); Constructs an object of class logic_error. domain_error::domain_error(const string& what_arg); Constructs an object of class domain_error. invalid_argument::invalid_argument(const string& what_arg); Constructs an object of class invalid_argument. length_error::length_error(const string& what_arg); Constructs an object of class length_error. out_of_range::out_of_range(const string& what_arg); Constructs an object of class out_of_range. runtime_error::runtime_error(const string& what_arg); Constructs an object of class runtime_error. range_error::range_error(const string& what_arg); Constructs an object of class range_error. overflow_error::overflow_error(const string& what_arg); Constructs an object of class overflow_error. underflow_error::underflow_error( const string& what_arg); Constructs an object of class underflow_error. EXAMPLE // // exception.cpp // #include #include static void f() { throw runtime_error("a runtime error"); } int main () { // // By wrapping the body of main in a try-catch block // we can be assured that we'll catch all exceptions // in the exception hierarchy. You can simply catch // exception as is done below, or you can catch each // of the exceptions in which you have an interest. // try { f(); } catch (const exception& e) { cout << "Got an exception: " << e.what() << endl; } return 0; } STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 nothrow Standard C++ Library NAME nothrow, nothrow_t - nothrow is an object of type nothrow_t used as an argument to new()/delete() functions to indicate that those functions never throw an exception. SYNOPSIS #include namespace std { class nothrow_t; extern const nothrow_t nothrow; } DESCRIPTION nothrow_t is of type: class nothrow_t {}; nothrow_t is the type of a function argument to new()/delete() which indicates that the function should never throw an exception. nothrow is an object of type nothrow_t declared in the Standard Library which is passed as a function argument (matching the type nothrow_t parameter) to new()/delete(). SEE ALSO new, delete STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 terminate_handler Standard C++ Library NAME terminate_handler, set_terminate, terminate - The type terminate_handler and functions set_terminate() and terminate() support abnormal program termination. SYNOPSIS #include namespace std { typedef void (*terminate_handler)(); terminate_handler set_terminate(terminate_handler new_h) throw(); void terminate(); } DESCRIPTION typedef void (*terminate_handler)(); terminate_handler is the type of handler function called by terminate() when terminating exception processing. The required behavior of a terminate_handler is to terminate program expansion without returning to the caller. The Standard C++ Library provides a terminate_handler which is called by default. The library provided terminate_handler calls abort(). terminate_handler set_terminate(terminate_handler new_h) throw(); set_terminate() sets the current terminate_handler to the function passed in as its terminate_handler input parameter. It returns the previous terminate_handler. The function is not allowed to be a null pointer. void terminate(); terminate() is called by the implementation when exception handling must be abandoned. It may be directly called by a user program. If called by the implementation, terminate() calls the terminate_handler function in effect after evaluating the throw-expression. If called by the program, terminate() calls the current terminate_handler function. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 unexpected_handler Standard C++ Library NAME unexpected_handler, set_unexpected, unexpected, uncaught_exception The type unexpected_handler and functions set_unexpected(), unexpected(), and uncaught_exception support abnormal program termination. SYNOPSIS #include namespace std { typedef void (*unexpected_handler)(); unexpected_handler set_unexpected(unexpected_handler new_h) throw(); void unexpected(); bool uncaught_exception(); } DESCRIPTION typedef void (*unexpected_handler)(); unexpected_handler is the type of a handler function called by unexpected() when a function attempts to throw an exception not listed in its exception-specification. The required behavior of an unexpected_handler is to throw an exception or terminate program execution without returning to the caller. The unexpected_handler may perform any of the following: o throw an exception that satisfies the exception specification (if the call to unexpected() is from the program not from the implementation any exception may be thrown) o throw an exception of class bad_exception or of any class directly or indirectly derived from bad_exception. o call terminate() o call abort() or exit() The Standard C++ Library provides a unexpected_handler which is called by default. The library provided unexpected_handler calls terminate(). unexpected_handler set_unexpected(unexpected_handler new_h) throw(); set_unexpected() sets the current unexpected_handler to the function passed in as its unexpected_handler input parameter. It returns the previous unexpected_handler. The function is not allowed to be a null pointer. void unexpected(); unexpected() is called by the implementation when a function exits by an exception not allowed by its exception specification. It may be directly called by a user program. If called by the implementation, unexpected() calls the unexpected_handler function in effect after evaluating the throw-expression. If called by the program, unexpected() calls the current unexpected_handler function. bool uncaught_exception(); uncaught_exception() returns true if a thrown exception is currently being processed. SEE ALSO bad_exception, terminate STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 string Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_string,string - A templated class for handling sequences of character-like entities. string and wstring are specialized versions of basic_string for chars and wchar_ts, respectively. This page describes the ANSI basic_string class. If you would like information on the pre-ANSI string class, use the command: help cxxl typedef basic_string string; typedef basic_string wstring; SYNOPSIS #include template , class Allocator = allocator > class basic_string; DESCRIPTION basic_string is a homogeneous collection of character-like entities. It provides general string functionality such as compare, append, assign, insert, remove, and replace , along with various searches. basic_string also functions as an STL sequence container, providing random access iterators. This allows some of the generic algorithms to apply to strings. Any underlying character-like type may be used as long as an appropriate string_char_traits class is provided or the default traits class is applicable. INTERFACE template , class Allocator = allocator > class basic_string { public: // Types typedef traits traits_type; typedef typename traits::char_type value_type; typedef Allocator allocator_type; typename size_type; typename difference_type; typename reference; typename const_reference; typename pointer; typename const_pointer; typename iterator; typename const_iterator; typename const_reverse_iterator; typename reverse_iterator; static const size_type npos = -1; // Constructors/Destructors explicit basic_string(const Allocator& = Allocator()); basic_string (const basic_string&); basic_string(const basic_string&, size_type, size_type = npos); basic_string(const charT*, size_type, const Allocator& = Allocator()); basic_string(const charT*, Allocator& = Allocator()); basic_string(size_type, charT, const Allocator& = Allocator()); template basic_string(InputIterator, InputIterator, const Allocator& = Allocator()); ~basic_string(); // Assignment operators basic_string& operator=(const basic_string&); basic_string& operator=(const charT*); basic_string& operator=(charT); // Iterators 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; // Capacity size_type size() const; size_type length() const; size_type max_size() const; void resize(size_type, charT); void resize(size_type); size_type capacity() const; void reserve(size_type); bool empty() const; // Element access const_reference operator[](size_type) const; reference operator[](size_type); const_reference at(size_type) const; reference at(size_type); // Modifiers basic_string& operator+=(const basic_string&); basic_string& operator+=(const charT*); basic_string& operator+=(charT); basic_string& append(const basic_string&); basic_string& append(const basic_string&, size_type, size_type); basic_string& append(const charT*, size_type); basic_string& append(const charT*); basic_string& append(size_type, charT); template basic_string& append(InputIterator, InputIterator); basic_string& assign(const basic_string&); basic_string& assign(const basic_string&, size_type, size_type); basic_string& assign(const charT*, size_type); basic_string& assign(const charT*); basic_string& assign(size_type, charT); template basic_string& assign(InputIterator, InputIterator); basic_string& insert(size_type, const basic_string&); basic_string& insert(size_type, const basic_string&, size_type, size_type); basic_string& insert(size_type, const charT*, size_type); basic_string& insert(size_type, const charT*); basic_string& insert(size_type, size_type, charT); iterator insert(iterator, charT = charT()); void insert(iterator, size_type, charT); template void insert(iterator, InputIterator, InputIterator); basic_string& erase(size_type = 0, size_type= npos); iterator erase(iterator); iterator erase(iterator, iterator); basic_string& replace(size_type, size_type, const basic_string&); basic_string& replace(size_type, size_type, const basic_string&, size_type, size_type); basic_string& replace(size_type, size_type, const charT*, size_type); basic_string& replace(size_type, size_type, const charT*); basic_string& replace(size_type, size_type, size_type, charT); basic_string& replace(iterator, iterator, const basic_string&); basic_string& replace(iterator, iterator, const charT*, size_type); basic_string& replace(iterator, iterator, const charT*); basic_string& replace(iterator, iterator, size_type, charT); template basic_string& replace(iterator, iterator, InputIterator, InputIterator); size_type copy(charT*, size_type, size_type = 0); void swap(basic_string&); // String operations const charT* c_str() const; const charT* data() const; const allocator_type& get_allocator() const; size_type find(const basic_string&, size_type = 0) const; size_type find(const charT*, size_type, size_type) const; size_type find(const charT*, size_type = 0) const; size_type find(charT, size_type = 0) const; size_type rfind(const basic_string&, size_type = npos) const; size_type rfind(const charT*, size_type, size_type) const; size_type rfind(const charT*, size_type = npos) const; size_type rfind(charT, size_type = npos) const; size_type find_first_of(const basic_string&, size_type = 0) const; size_type find_first_of(const charT*, size_type, size_type) const; size_type find_first_of(const charT*, size_type = 0) const; size_type find_first_of(charT, size_type = 0) const; size_type find_last_of(const basic_string&, size_type = npos) const; size_type find_last_of(const charT*, size_type, size_type) const; size_type find_last_of(const charT*, size_type = npos) const; size_type find_last_of(charT, size_type = npos) const; size_type find_first_not_of(const basic_string&, size_type = 0) const; size_type find_first_not_of(const charT*, size_type, size_type) const; size_type find_first_not_of(const charT*, size_type = 0) const; size_type find_first_not_of(charT, size_type = 0) const; size_type find_last_not_of(const basic_string&, size_type = npos) const; size_type find_last_not_of(const charT*, size_type, size_type) const; size_type find_last_not_of(const charT*, size_type = npos) const; size_type find_last_not_of(charT, size_type = npos) const; basic_string substr(size_type = 0, size_type = npos) const; int compare(const basic_string&) const; int compare(size_type, size_type, const basic_string&) const; int compare(size_type, size_type, const basic_string&, size_type, size_type) const; int compare(size_type, size_type, charT*) const; int compare(charT*) const; int compare(size_type, size_type, const charT*, size_type) const; }; // Non-member Operators template basic_string operator+ (const basic_string&, const basic_string&); template basic_string operator+ (const charT*, const basic_string&); template basic_string operator+ (charT, const basic_string&); template basic_string operator+ (const basic_string&, const charT*); template basic_string operator+ (const basic_string&, charT); template bool operator== (const basic_string&, const basic_string&); template bool operator== (const charT*, const basic_string&); template bool operator== (const basic_string&, const charT*); template bool operator< (const basic_string&, const basic_string&); template bool operator< (const charT*, const basic_string&); template bool operator< (const basic_string&, const charT*); template bool operator!= (const basic_string&, const basic_string&); template bool operator!= (const charT*, const basic_string&); template bool operator!= (const basic_string&, const charT*); template bool operator> (const basic_&, const basic_string&); template bool operator> (const charT*, const basic_string&); template bool operator> (const basic_string&, const charT*); template bool operator<= (const basic_string&, const basic_string&); template bool operator<= (const charT*, const basic_string&); template bool operator<= (const basic_string&, const charT*); template bool operator>= (const basic_string&, const basic_string&); template bool operator>= (const charT*, const basic_string&); template bool operator>= (const basic_string&, const charT*); template void swap(basic_string& a, basic_string& b); template istream& operator>> (istream&, basic_string&); template ostream& operator<< (ostream&, const basic_string&); template Stream& getline (Stream&, basic_string&, charT); CONSTRUCTORS AND DESTRUCTORS In all cases, the Allocator parameter will be used for storage management. explicit basic_string (const Allocator& a = Allocator()); The default constructor. Creates a basic_string with the following effects: data() a non-null pointer that is copyable and can have 0 added to it size() 0 capacity() an unspecified value basic_string (const basic_string& str); Copy constructor. Creates a string that is a copy of str. basic_string (const basic_string &str, size_type pos, size_type n= npos); Creates a string if pos<=size() and determines length rlen of initial string value as the smaller of n and str.size() - pos. This has the following effects: data() points at the first element of an allocated copy of rlen elements of the string controlled by str beginning at position pos size() rlen capacity() a value at least as large as size() get_allocator() str.get_allocator() An out_of_range exception will be thrown if pos>str.size(). basic_string (const charT* s, size_type n, const Allocator& a = Allocator()); Creates a string that contains the first n characters of s. s must not be a NULL pointer. The effects of this constructor are: data() points at the first element of an allocated copy of the array whose first element is pointed at by s size() n capacity() a value at least as large as size() An out_of_range exception will be thrown if n == npos. basic_string (const charT * s, const Allocator& a = Allocator()); Constructs a string containing all characters in s up to, but not including, a traits::eos() character. s must not be a null pointer. The effects of this constructor are: data() points at the first element of an allocated copy of the array whose first element is pointed at by s size() traits::length(s) capacity() a value at least as large as size() basic_string (size_type n, charT c, const Allocator& a = Allocator()); Constructs a string containing n repetitions of c. A length_error exception is thrown if n == npos. The effects of this constructor are: data() points at the first element of an allocated array of n elements, each storing the initial value c size() n capacity() a value at least as large as size() template basic_string (InputIterator first, InputIterator last, const Allocator& a = Allocator()); Creates a basic_string of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). The effects of this constructor are: data() points at the first element of an allocated copy of the elements in the range [first,last) size() distance between first and last capacity() a value at least as large as size() ~basic_string (); Releases any allocated memory for this basic_string. OPERATORS basic_string& operator= (const basic_string& str); Assignment operator. Sets the contents of this string to be the same as str. The effects of operator= are: data() points at the first element of an allocated copy of the array whose first element is pointed at by str.size() size() str.size() capacity() a value at least as large as size() basic_string& operator= (const charT * s); Assignment operator. Sets the contents of this string to be the same as s up to, but not including, the traits::eos() character. basic_string& operator= (charT c); Assignment operator. Sets the contents of this string to be equal to the single charT c. const_reference operator[] (size_type pos) const; reference operator[] (size_type pos); If pos < size(), returns the element at position pos in this string. If pos == size(), the const version returns traits::eos(), the behavior of the non-const version is undefined. The reference returned by either version is invalidated by any call to c_str(), data(), or any non-const member function for the object. basic_string& operator+= (const basic_string& s); basic_string& operator+= (const charT* s); basic_string& operator+= (charT c); Concatenates a string onto the current contents of this string. The second member operator uses traits::length() to determine the number of elements from s to add. The third member operator adds the single character c. All return a reference to this string after completion. ITERATORS iterator begin (); const_iterator begin () const; Return an iterator initialized to the first element of the string. iterator end (); const_iterator end () const; Return an iterator initialized to the position after the last element of the string. reverse_iterator rbegin (); const_reverse_iterator rbegin () const; Returns an iterator equivalent to reverse_iterator(end()). reverse_iterator rend (); const_reverse_iterator rend () const; Returns an iterator equivalent to reverse_iterator(begin()). ALLOCATOR const allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS basic_string& append (const basic_string& s, size_type pos, size_type npos); basic_string& append (const basic_string& s); basic_string& append (const charT* s, size_type n); basic_string& append (const charT* s); basic_string& append (size_type n, charT c ); template basic_string& append (InputIterator first, InputIterator last); Append another string to the end of this string. The first two functions append the lesser of n and s.size() - pos characters of s, beginning at position pos to this string. The second member will throw an out_of_range exception if pos > str.size(). The third member appends n characters of the array pointed to by s. The fourth variation appends elements from the array pointed to by s up to, but not including, a traits::eos() character. The fifth variation appends n repetitions of c. The final append function appends the elements specified in the range [first, last). All functions will throw a length_error exception if the resulting length will exceed max_size(). All return a reference to this string after completion. basic_string& assign (const basic_string& s); basic_string& assign (const basic_string& s, size_type pos, size_type n); basic_string& assign (const charT* s, size_type n); basic_string& assign (const charT* s); basic_string& assign (size_type n, charT c ); template basic_string& assign (InputIterator first, InputIterator last); Replace the value of this string with the value of another. All versions of the function assign values to this string. The first two variations assign the lesser of n and s.size() - pos characters of s, beginning at position pos. The second variation throws an out_of_range exception if pos > str.size(). The third version of the function assigns n characters of the array pointed to by s. The fourth version assigns elements from the array pointed to by s up to, but not including, a traits::eos() character. The fifth assigns one or n repetitions of c. The last variation assigns the members specified by the range [first, last). All functions will throw a length_error exception if the resulting length will exceed max_size(). All return a reference to this string after completion. const_reference at (size_type pos) const; reference at (size_type pos); If pos < size(), returns the element at position pos in this string. Otherwise, an out_of_range exception is thrown. size_type capacity () const; Returns the current storage capacity of the string. This is guaranteed to be at least as large as size(). int compare (const basic_string& str); Returns the result of a lexicographical comparison between elements of this string and elements of str. The return value is: <0 if size() < str.size() 0 if size() == str.size() >0 if size() > str.size() int compare (size_type pos1, size_type n1, const basic_string& str) const; int compare (size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) const; int compare (charT* s) const; int compare (size_type pos, size_type n1, charT* s) const; int compare (size_type pos, size_type n1, charT* s, size_type n2) const; Return the result of a lexicographical comparison between elements of this string and a given comparison string. The members return, respectively: compare (str) compare (basic_string (str, pos2, n2)) compare (basic_string(s)) compare (basic_string(s, npos)) compare (basic_string (s,n2)) size_type copy (charT* s, size_type n, size_type pos = 0) const; Replaces elements in memory with copies of elements from this string. An out_of_range exception will be thrown if pos > size(). The lesser of n and size() - pos elements of this string, starting at position pos are copied into the array pointed to by s. No terminating null is appended to s. const charT* c_str () const; const charT* data () const; Return a pointer to the initial element of an array whose first size() elements are copies of the elements in this string. A traits::eos() element is appended to the end. The elements of the array may not be altered, and the returned pointer is only valid until a non-const member function of this string is called. If size() is zero, the data() function returns a NULL pointer. bool empty () const; Returns size() == 0. basic_string& erase (size_type pos = 0, size_type n = npos); iterator erase (iterator p); iterator erase (iterator first, iterator last); This function removes elements from the string, collapsing the remaining elements, as necessary, to remove any space left empty. The first version of the function removes the smaller of n and size() - pos starting at position pos. An out_of_range exception will be thrown if pos > size(). The second version requires that p is a valid iterator on this string, and removes the character referred to by p. The last version of erase requires that both first and last are valid iterators on this string, and removes the characters defined by the range [first,last). The destructors for all removed characters are called. All versions of erase return a reference to this string after completion. size_type find (const basic_string& str, size_type pos = 0) const; Searches for the first occurrence of the substring specified by str in this string, starting at position pos. If found, it returns the index of the first character of the matching substring. If not found, returns npos. Equality is defined by traits::eq(). size_type find (const charT* s, size_type pos, size_type n) const; size_type find (const charT* s, size_type pos = 0) const; size_type find (charT c, size_type pos = 0) const; Search for the first sequence of characters in this string that match a specified string. The variations of this function return, respectively: find(basic_string(s,n), pos) find(basic_string(s), pos) find(basic_string(1, c), pos) size_type find_first_not_of (const basic_string& str, size_type pos = 0) const Searches for the first element of this string at or after position pos that is not equal to any element of str. If found, find_first_not_of returns the index of the non-matching character. If all of the characters match, the function returns npos. Equality is defined by traits::eq(). size_type find_first_not_of (const charT* s, size_type pos, size_type n) const; size_type find_first_not_of (const charT* s, size_type pos = 0) const; size_type find_first_not_of (charT c, size_type pos = 0) const; Search for the first element in this string at or after position pos that is not equal to any element of a given set of characters. The members return, respectively: find_first_not_of(basic_string(s,n), pos) find_first_not_of(basic_string(s), pos) find_first_not_of(basic_string(1, c), pos) size_type find_first_of(const basic_string& str, size_type pos = 0) const; Searches for the first occurrence at or after position pos of any element of str in this string. If found, the index of this matching character is returned. If not found, npos is returned. Equality is defined by traits::eq(). size_type find_first_of(const charT* s, size_type pos, size_type n) const; size_type find_first_of(const charT* s, size_type pos = 0) const; size_type find_first_of (charT c, size_type pos = 0) const; Search for the first occurrence in this string of any element in a specified string. The find_first_of variations return, respectively: find_first_of(basic_string(s,n), pos) find_first_of(basic_string(s), pos) find_first_of(basic_string(1, c), pos) size_type find_last_not_of(const basic_string& str, size_type pos = npos) const; Searches for the last element of this string at or before position pos that is not equal to any element of str. If find_last_not_of finds a non-matching element, it returns the index of the character. If all the elements match, the function returns npos. Equality is defined by traits::eq(). size_type find_last_not_of(const charT* s, size_type pos, size_type n) const; size_type find_last_not_of(const charT* s, size_type pos = npos) const; size_type find_last_not_of(charT c, size_type pos = npos) const; Search for the last element in this string at or before position pos that is not equal to any element of a given set of characters. The members return, respectively: find_last_not_of(basic_string(s,n), pos) find_last_not_of(basic_string(s), pos) find_last_not_of(basic_string(1, c), pos) size_type find_last_of(const basic_string& str, size_type pos = npos) const; Searches for the last occurrence of any element of str at or before position pos in this string. If found, find_last_of returns the index of the matching character. If not found find_last_of returns npos. Equality is defined by traits::eq(). size_type find_last_of(const charT* s, size_type pos, size_type n) const; size_type find_last_of(const charT* s, size_type pos = npos) const; size_type find_last_of(charT c, size_type pos = npos) const; Search for the last occurrence in this string of any element in a specified string. The members return, respectively: find_last_of(basic_string(s,n), pos) find_last_of(basic_string(s), pos) find_last_of(basic_string(1, c), pos) basic_string& insert(size_type pos1, const basic_string& s); basic_string& insert(size_type pos, const basic_string& s, size_type pos2 = 0, size_type n = npos); basic_string& insert(size_type pos, const charT* s, size_type n); basic_string& insert(size_type pos, const charT* s); basic_string& insert(size_type pos, size_type n, charT c); Insert additional elements at position pos in this string. All of the variants of this function will throw an out_of_range exception if pos > size(). All variants will also throw a length_error if the resulting string will exceed max_size(). Elements of this string will be moved apart as necessary to accommodate the inserted elements. All return a reference to this string after completion. The second variation of this function inserts the lesser of n and s.size() - pos2 characters of s, beginning at position pos2 in this string. This version will throw an out_of_range exception if pos2 > s.size(). The third version inserts n characters of the array pointed to by s. The fourth inserts elements from the array pointed to by s up to, but not including, a traits::eos() character. Finally, the fifth variation inserts n repetitions of c. iterator insert(iterator p, charT c = charT()); void insert(iterator p, size_type n, charT c); template void insert(iterator p, InputIterator first, InputIterator last); Insert additional elements in this string immediately before the character referred to by p. All of these versions of insert require that p is a valid iterator on this string. The first version inserts a copy of c. The second version inserts n repetitions of c. The third version inserts characters in the range [first, last). The first version returns p. size_type length() const; Return the number of elements contained in this string. size_type max_size() const; Returns the maximum possible size of the string. size_type rfind (const basic_string& str, size_type pos = npos) const; Searches for the last occurrence of the substring specified by str in this string, starting at position pos. Note that only the first character of the substring must be <= pos; the remaining characters may extend beyond pos. If found, the index of the first character of that matches substring is returned. If not found, npos is returned. Equality is defined by traits::eq(). size_type rfind(const charT* s, size_type pos, size_type n) const; size_type rfind(const charT* s, size_type pos = npos) const; size_type rfind(charT c, size_type pos = npos) const; Searches for the last sequence of characters in this string matching a specified string. The rfind variations return, respectively: rfind(basic_string(s,n), pos) rfind(basic_string(s), pos) rfind(basic_string(1, c), pos) basic_string& replace(size_type pos, size_type n1, const basic_string& s); basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s); basic_string& replace(size_type pos, size_type n1, size_type n2, charT c); The replace function replaces selected elements of this string with an alternate set of elements. All of these versions insert the new elements in place of n1 elements in this string, starting at position pos. They each throw an out_of_range exception if pos1 > size()and a length_error exception if the resulting string size exceeds max_size(). The second version replaces elements of the original string with n2 characters from string s starting at position pos2. It will throw the out_of_range exception if pos2 > s.size(). The third variation of the function replaces elements in the original string with n2 elements from the array pointed to by s. The fourth version replaces elements in the string with elements from the array pointed to by s, up to, but not including, a traits::eos() character. The fifth replaces n elements with n2 repetitions of character c. basic_string& replace(iterator i1, iterator i2, const basic_string& str); basic_string& replace(iterator i1, iterator i2, const charT* s, size_type n); basic_string& replace(iterator i1, iterator i2, const charT* s); basic_string& replace(iterator i1, iterator i2, size_type n, charT c); template basic_string& replace(iterator i1, iterator i2, InputIterator j1, InputIterator j2); Replace selected elements of this string with an alternative set of elements. All of these versions of replace require iterators i1 and i2 to be valid iterators on this string. The elements specified by the range [i1,i2) are replaced by the new elements. The first version shown here replaces with all members in str. The second version starts at position i1, and replaces the next n characters with n characters of the array pointed to by s. The third variation replaces string elements with elements from the array pointed to by s up to, but not including, a traits::eos() character. The fourth version replaces string elements with n repetitions of c. The last variation shown here replaces string elements with the members specified in the range [j1, j2). void reserve(size_type res_arg); Assures that the storage capacity is at least res_arg. void resize(size_type n, charT c); void resize(size_type n); Changes the capacity of this string to n. If the new capacity is smaller than the current size of the string, then it is truncated. If the capacity is larger, then the string is padded with c characters. The latter resize member pads the string with default characters specified by traits::eos(). size type size() const; Return the number of elements contained in this string. basic_string substr(size_type pos = 0, size_type n = npos) const; Returns a string composed of copies of the lesser of n and size() characters in this string starting at index pos. Throws an out_of_range exception if pos <= size(). void swap(basic_string& s); Swaps the contents of this string with the contents of s. NON-MEMBER OPERATORS template basic_string operator+(const basic_string& lhs, const basic_string& rhs); Returns a string of length lhs.size() + rhs.size(), where the first lhs.size() elements are copies of the elements of lhs, and the next rhs.size() elements are copies of the elements of rhs. template basic_string operator+(const charT* lhs, const basic_string& rhs); template basic_string operator+(charT lhs, const basic_string& rhs); template basic_string operator+(const basic_string& lhs, const charT* rhs); template basic_string operator+(const basic_string& lhs, charT rhs); Returns a string that represents the concatenation of two string-like entities. These functions return, respectively: basic_string(lhs) + rhs basic_string(1, lhs) + rhs lhs + basic_string(rhs) lhs + basic_string(1, rhs) template bool operator==(const basic_string& lhs, const basic_string& rhs); Returns a boolean value of true if lhs and rhs are equal, and false if they are not. Equality is defined by the compare() member function. template bool operator==(const charT* lhs, const basic_string& rhs); template bool operator==(const basic_string& lhs, const charT* rhs); Returns a boolean value indicating whether lhs and rhs are equal. Equality is defined by the compare() member function. These functions return, respectively: basic_string(lhs) == rhs lhs == basic_string(rhs) template bool operator!=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function. template bool operator!=(const charT* lhs, const basic_string& rhs); template bool operator!=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function. The functions return, respectively: basic_string(lhs) != rhs lhs != basic_string(rhs) template bool operator<(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical less-than relationship of lhs and rhs. Less-than is defined by the compare() member. template bool operator<(const charT* lhs, const basic_string& rhs); template bool operator<(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical less-than relationship of lhs and rhs. Less-than is defined by the compare() member function. These functions return, respectively: basic_string(lhs) < rhs lhs < basic_string(rhs) template bool operator>(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical greater-than relationship of lhs and rhs. Greater-than is defined by the compare() member function. template bool operator>(const charT* lhs, const basic_string& rhs); template bool operator>(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical greater-than relationship of lhs and rhs. Greater-than is defined by the compare() member. The functions return, respectively: basic_string(lhs) > rhs lhs > basic_string(rhs) template bool operator<=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical less-than-or-equal relationship of lhs and rhs. Less-than-or-equal is defined by the compare() member function. template bool operator<=(const charT* lhs, const basic_string& rhs); template bool operator<=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical less-than-or-equal relationship of lhs and rhs. Less-than-or-equal is defined by the compare() member function. These functions return, respectively: basic_string(lhs) <= rhs lhs <= basic_string(rhs) template bool operator>=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical greater-than-or-equal relationship of lhs and rhs. Greater-than-or-equal is defined by the compare() member function. template bool operator>=(const charT* lhs, const basic_string& rhs); template bool operator>=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical greater-than-or-equal relationship of lhs and rhs. Greater-than-or-equal is defined by the compare() member. The functions return, respectively: basic_string(lhs) >= rhs lhs >= basic_string(rhs) template void swap(basic_string& a, basic_string& b); Swaps the contents of a and b by calling a's swap function on b. template istream& operator>>(istream& is, basic_string& str); Reads str from is using traits::char_in until a traits::is_del() element is read. All elements read, except the delimiter, are placed in str. After the read, the function returns is. template ostream& operator<<(ostream& os, const basic_string& str); Writes all elements of str to os in order from first to last, using traits::char_out(). After the write, the function returns os. NON-MEMBER FUNCTION template Stream& getline(Stream& is, basic_string& str, charT delim); An unformatted input function that extracts characters from is into str until npos - 1 characters are read, the end of the input sequence is reached, or the character read is delim. The characters are read using traits::char_in(). EXAMPLE // // string.cpp // #include #include int main() { string test; //Type in a string over five characters long while(test.empty() || test.size() <= 5) { cout << "Type a string between 5 and 100 characters long. " << endl; cin >> test; } //Test operator[] access cout << "Changing the third character from " << test[2] << " to * " << endl; test[2] = '*'; cout << "now its: " << test << endl << endl; //Try the insertion member function cout << "Identifying the middle: "; test.insert(test.size() / 2, "(the middle is here!)"); cout << test << endl << endl; //Try replacement cout << "I didn't like the word 'middle',so instead,I'll say:" << endl; test.replace(test.find("middle",0), 6, "center"); cout << test << endl; return 0; } Output : Type a string between 5 and 100 characters long. roguewave Changing the third character from g to * now its: ro*uewave Identifying the middle: ro*u(the middle is here!)ewave I didn't like the word 'middle', so instead, I'll say: ro*u(the center is here!)ewave SEE ALSO Allocators, string, wstring STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 string_char_traits Standard C++ Library NAME string_char_traits_ - A traits class providing types and operations to the basic_string container. SYNOPSIS #include template struct string_char_traits struct string_char_traits; . struct string_char_traits; DESCRIPTION The string_char_traits struct provides elementary operations to instantiations of basic_string. As with all traits classes, string_char_traits is used to specialize the behavior of a template. In this case, the traits class provides functions based on character type to the basic_string template. Specializations of string_char_traits are provided for char and wchar_t. These are used to define, respectively, string and wstring. INTERFACE template struct string_char_traits . { typedef charT char_type; static void assign (char_type&, const char_type&); . static char_type* assign (char_type*, size_t, const char_type&); static bool eq (const char_type&, const char_type&); . static bool ne (const char_type&, const char_type&); . static bool lt (const char_type&, const char_type&); . static char_type eos (); . static int compare (const char_type*, const char_type*, size_t); static size_t length (const char_type * s); . static char_type* copy (char_type*, const char_type*, size_t); static char_type* move (char_type*, const char_type*, size_t); static const char_type* . find (const char_type*, int, const char_type&); }; TYPE char_type The basic character type. Same as the template parameter. OPERATIONS static void assign (char_type& c1, const char_type& c2) Assign one character value to another. The value of c2 is assigned to c1. static char_type* assign (char_type* s, size_t n, const char_type& a) Assign one character value to n elements of a character array. The value of a is assigned to n elements of s. static bool eq (const char_type& c1, const char_type& c2) Return true if c1 equals c2. static bool ne (const char_type& c1, const char_type& c2) Return true if c1 does not equal c2. static bool lt (const char_type& c1, const char_type& c2) Return true if c1 is less than c2. static char_type eos () Return the end of string value for the the character type. Typically char_type(). static int compare (const char_type* s1, const char_type* s2, size_t n) Compare n values from s1 with n values from s2. Return 1 if s1 is greater than s2, -1 if s1 is less than s2, or 0 if they are equal. static size_t length (const char_type * s) Return the length of the null terminated character array s. The eos terminator is not counted. static char_type* copy (char_type* s1, const char_type* s2, size_t n) Copy n values from s1 to s2. The ranges of (s1,s1+n) and (s2,s2+n) may not overlap. static char_type* move (char_type* s1, const char_type* s2, size_t n) Move n values from s1 to s2. The ranges of (s1,s1+n) and (s2,s2+n) may overlap. static const char_type* find (const char_type* s, int n, const char_type& a) Look for the value of a in s. Only n elements of s are examined. Returns a pointer to the matched element if one is found. Otherwise returns s + n. SEE ALSO basic_string, traits STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_string Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_string,string - A templated class for handling sequences of character-like entities. string and wstring are specialized versions of basic_string for chars and wchar_ts, respectively. This page describes the ANSI basic_string class. If you would like information on the pre-ANSI string class, use the command: help cxxl typedef basic_string string; typedef basic_string wstring; SYNOPSIS #include template , class Allocator = allocator > class basic_string; DESCRIPTION basic_string is a homogeneous collection of character-like entities. It provides general string functionality such as compare, append, assign, insert, remove, and replace , along with various searches. basic_string also functions as an STL sequence container, providing random access iterators. This allows some of the generic algorithms to apply to strings. Any underlying character-like type may be used as long as an appropriate string_char_traits class is provided or the default traits class is applicable. INTERFACE template , class Allocator = allocator > class basic_string { public: // Types typedef traits traits_type; typedef typename traits::char_type value_type; typedef Allocator allocator_type; typename size_type; typename difference_type; typename reference; typename const_reference; typename pointer; typename const_pointer; typename iterator; typename const_iterator; typename const_reverse_iterator; typename reverse_iterator; static const size_type npos = -1; // Constructors/Destructors explicit basic_string(const Allocator& = Allocator()); basic_string (const basic_string&); basic_string(const basic_string&, size_type, size_type = npos); basic_string(const charT*, size_type, const Allocator& = Allocator()); basic_string(const charT*, Allocator& = Allocator()); basic_string(size_type, charT, const Allocator& = Allocator()); template basic_string(InputIterator, InputIterator, const Allocator& = Allocator()); ~basic_string(); // Assignment operators basic_string& operator=(const basic_string&); basic_string& operator=(const charT*); basic_string& operator=(charT); // Iterators 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; // Capacity size_type size() const; size_type length() const; size_type max_size() const; void resize(size_type, charT); void resize(size_type); size_type capacity() const; void reserve(size_type); bool empty() const; // Element access const_reference operator[](size_type) const; reference operator[](size_type); const_reference at(size_type) const; reference at(size_type); // Modifiers basic_string& operator+=(const basic_string&); basic_string& operator+=(const charT*); basic_string& operator+=(charT); basic_string& append(const basic_string&); basic_string& append(const basic_string&, size_type, size_type); basic_string& append(const charT*, size_type); basic_string& append(const charT*); basic_string& append(size_type, charT); template basic_string& append(InputIterator, InputIterator); basic_string& assign(const basic_string&); basic_string& assign(const basic_string&, size_type, size_type); basic_string& assign(const charT*, size_type); basic_string& assign(const charT*); basic_string& assign(size_type, charT); template basic_string& assign(InputIterator, InputIterator); basic_string& insert(size_type, const basic_string&); basic_string& insert(size_type, const basic_string&, size_type, size_type); basic_string& insert(size_type, const charT*, size_type); basic_string& insert(size_type, const charT*); basic_string& insert(size_type, size_type, charT); iterator insert(iterator, charT = charT()); void insert(iterator, size_type, charT); template void insert(iterator, InputIterator, InputIterator); basic_string& erase(size_type = 0, size_type= npos); iterator erase(iterator); iterator erase(iterator, iterator); basic_string& replace(size_type, size_type, const basic_string&); basic_string& replace(size_type, size_type, const basic_string&, size_type, size_type); basic_string& replace(size_type, size_type, const charT*, size_type); basic_string& replace(size_type, size_type, const charT*); basic_string& replace(size_type, size_type, size_type, charT); basic_string& replace(iterator, iterator, const basic_string&); basic_string& replace(iterator, iterator, const charT*, size_type); basic_string& replace(iterator, iterator, const charT*); basic_string& replace(iterator, iterator, size_type, charT); template basic_string& replace(iterator, iterator, InputIterator, InputIterator); size_type copy(charT*, size_type, size_type = 0); void swap(basic_string&); // String operations const charT* c_str() const; const charT* data() const; const allocator_type& get_allocator() const; size_type find(const basic_string&, size_type = 0) const; size_type find(const charT*, size_type, size_type) const; size_type find(const charT*, size_type = 0) const; size_type find(charT, size_type = 0) const; size_type rfind(const basic_string&, size_type = npos) const; size_type rfind(const charT*, size_type, size_type) const; size_type rfind(const charT*, size_type = npos) const; size_type rfind(charT, size_type = npos) const; size_type find_first_of(const basic_string&, size_type = 0) const; size_type find_first_of(const charT*, size_type, size_type) const; size_type find_first_of(const charT*, size_type = 0) const; size_type find_first_of(charT, size_type = 0) const; size_type find_last_of(const basic_string&, size_type = npos) const; size_type find_last_of(const charT*, size_type, size_type) const; size_type find_last_of(const charT*, size_type = npos) const; size_type find_last_of(charT, size_type = npos) const; size_type find_first_not_of(const basic_string&, size_type = 0) const; size_type find_first_not_of(const charT*, size_type, size_type) const; size_type find_first_not_of(const charT*, size_type = 0) const; size_type find_first_not_of(charT, size_type = 0) const; size_type find_last_not_of(const basic_string&, size_type = npos) const; size_type find_last_not_of(const charT*, size_type, size_type) const; size_type find_last_not_of(const charT*, size_type = npos) const; size_type find_last_not_of(charT, size_type = npos) const; basic_string substr(size_type = 0, size_type = npos) const; int compare(const basic_string&) const; int compare(size_type, size_type, const basic_string&) const; int compare(size_type, size_type, const basic_string&, size_type, size_type) const; int compare(size_type, size_type, charT*) const; int compare(charT*) const; int compare(size_type, size_type, const charT*, size_type) const; }; // Non-member Operators template basic_string operator+ (const basic_string&, const basic_string&); template basic_string operator+ (const charT*, const basic_string&); template basic_string operator+ (charT, const basic_string&); template basic_string operator+ (const basic_string&, const charT*); template basic_string operator+ (const basic_string&, charT); template bool operator== (const basic_string&, const basic_string&); template bool operator== (const charT*, const basic_string&); template bool operator== (const basic_string&, const charT*); template bool operator< (const basic_string&, const basic_string&); template bool operator< (const charT*, const basic_string&); template bool operator< (const basic_string&, const charT*); template bool operator!= (const basic_string&, const basic_string&); template bool operator!= (const charT*, const basic_string&); template bool operator!= (const basic_string&, const charT*); template bool operator> (const basic_&, const basic_string&); template bool operator> (const charT*, const basic_string&); template bool operator> (const basic_string&, const charT*); template bool operator<= (const basic_string&, const basic_string&); template bool operator<= (const charT*, const basic_string&); template bool operator<= (const basic_string&, const charT*); template bool operator>= (const basic_string&, const basic_string&); template bool operator>= (const charT*, const basic_string&); template bool operator>= (const basic_string&, const charT*); template void swap(basic_string& a, basic_string& b); template istream& operator>> (istream&, basic_string&); template ostream& operator<< (ostream&, const basic_string&); template Stream& getline (Stream&, basic_string&, charT); CONSTRUCTORS AND DESTRUCTORS In all cases, the Allocator parameter will be used for storage management. explicit basic_string (const Allocator& a = Allocator()); The default constructor. Creates a basic_string with the following effects: data() a non-null pointer that is copyable and can have 0 added to it size() 0 capacity() an unspecified value basic_string (const basic_string& str); Copy constructor. Creates a string that is a copy of str. basic_string (const basic_string &str, size_type pos, size_type n= npos); Creates a string if pos<=size() and determines length rlen of initial string value as the smaller of n and str.size()- pos. This has the following effects: data() points at the first element of an allocated copy of rlen elements of the string controlled by str beginning at position pos size() rlen capacity() a value at least as large as size() get_allocator() str.get_allocator() An out_of_range exception will be thrown if pos>str.size(). basic_string (const charT* s, size_type n, const Allocator& a = Allocator()); Creates a string that contains the first n characters of s. s must not be a NULL pointer. The effects of this constructor are: data() points at the first element of an allocated copy of the array whose first element is pointed at by s size() n capacity() a value at least as large as size() An out_of_range exception will be thrown if n == npos. basic_string (const charT * s, const Allocator& a = Allocator()); Constructs a string containing all characters in s up to, but not including, a traits::eos() character. s must not be a null pointer. The effects of this constructor are: data() points at the first element of an allocated copy of the array whose first element is pointed at by s size() traits::length(s) capacity() a value at least as large as size() basic_string (size_type n, charT c, const Allocator& a = Allocator()); Constructs a string containing n repetitions of c. A length_error exception is thrown if n == npos. The effects of this constructor are: data() points at the first element of an allocated array of n elements, each storing the initial value c size() n capacity() a value at least as large as size() template basic_string (InputIterator first, InputIterator last, const Allocator& a = Allocator()); Creates a basic_string of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last). The effects of this constructor are: data() points at the first element of an allocated copy of the elements in the range [first,last) size() distance between first and last capacity() a value at least as large as size() ~basic_string (); Releases any allocated memory for this basic_string. OPERATORS basic_string& operator= (const basic_string& str); Assignment operator. Sets the contents of this string to be the same as str. The effects of operator= are: data() points at the first element of an allocated copy of the array whose first element is pointed at by str.size() size() str.size() capacity() a value at least as large as size() basic_string& operator= (const charT * s); Assignment operator. Sets the contents of this string to be the same as s up to, but not including, the traits::eos() character. basic_string& operator= (charT c); Assignment operator. Sets the contents of this string to be equal to the single charT c. const_reference operator[] (size_type pos) const; reference operator[] (size_type pos); If pos < size(), returns the element at position pos in this string. If pos == size(), the const version returns traits::eos(), the behavior of the non-const version is undefined. The reference returned by either version is invalidated by any call to c_str(), data(), or any non-const member function for the object. basic_string& operator+= (const basic_string& s); basic_string& operator+= (const charT* s); basic_string& operator+= (charT c); Concatenates a string onto the current contents of this string. The second member operator uses traits::length() to determine the number of elements from s to add. The third member operator adds the single character c. All return a reference to this string after completion. ITERATORS iterator begin (); const_iterator begin () const; Return an iterator initialized to the first element of the string. iterator end (); const_iterator end () const; Return an iterator initialized to the position after the last element of the string. reverse_iterator rbegin (); const_reverse_iterator rbegin () const; Returns an iterator equivalent to reverse_iterator(end()). reverse_iterator rend (); const_reverse_iterator rend () const; Returns an iterator equivalent to reverse_iterator(begin()). ALLOCATOR const allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. MEMBER FUNCTIONS basic_string& append (const basic_string& s, size_type pos, size_type npos); basic_string& append (const basic_string& s); basic_string& append (const charT* s, size_type n); basic_string& append (const charT* s); basic_string& append (size_type n, charT c ); template basic_string& append (InputIterator first, InputIterator last); Append another string to the end of this string. The first two functions append the lesser of n and s.size() - pos characters of s, beginning at position pos to this string. The second member will throw an out_of_range exception if pos > str.size(). The third member appends n characters of the array pointed to by s. The fourth variation appends elements from the array pointed to by s up to, but not including, a traits::eos() character. The fifth variation appends n repetitions of c. The final append function appends the elements specified in the range [first, last). All functions will throw a length_error exception if the resulting length will exceed max_size(). All return a reference to this string after completion. basic_string& assign (const basic_string& s); basic_string& assign (const basic_string& s, size_type pos, size_type n); basic_string& assign (const charT* s, size_type n); basic_string& assign (const charT* s); basic_string& assign (size_type n, charT c ); template basic_string& assign (InputIterator first, InputIterator last); Replace the value of this string with the value of another. All versions of the function assign values to this string. The first two variations assign the lesser of n and s.size() - pos characters of s, beginning at position pos. The second variation throws an out_of_range exception if pos > str.size(). The third version of the function assigns n characters of the array pointed to by s. The fourth version assigns elements from the array pointed to by s up to, but not including, a traits::eos() character. The fifth assigns one or n repetitions of c. The last variation assigns the members specified by the range [first, last). All functions will throw a length_error exception if the resulting length will exceed max_size(). All return a reference to this string after completion. const_reference at (size_type pos) const; reference at (size_type pos); If pos < size(), returns the element at position pos in this string. Otherwise, an out_of_range exception is thrown. size_type capacity () const; Returns the current storage capacity of the string. This is guaranteed to be at least as large as size(). int compare (const basic_string& str); Returns the result of a lexicographical comparison between elements of this string and elements of str. The return value is: <0 if size() < str.size() 0 if size() == str.size() >0 if size() > str.size() int compare (size_type pos1, size_type n1, const basic_string& str) const; int compare (size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) const; int compare (charT* s) const; int compare (size_type pos, size_type n1, charT* s) const; int compare (size_type pos, size_type n1, charT* s, size_type n2) const; Return the result of a lexicographical comparison between elements of this string and a given comparison string. The members return, respectively: compare (str) compare (basic_string (str, pos2, n2)) compare (basic_string(s)) compare (basic_string(s, npos)) compare (basic_string (s,n2)) size_type copy (charT* s, size_type n, size_type pos = 0) const; Replaces elements in memory with copies of elements from this string. An out_of_range exception will be thrown if pos > size(). The lesser of n and size() - pos elements of this string, starting at position pos are copied into the array pointed to by s. No terminating null is appended to s. const charT* c_str () const; const charT* data () const; Return a pointer to the initial element of an array whose first size() elements are copies of the elements in this string. A traits::eos() element is appended to the end. The elements of the array may not be altered, and the returned pointer is only valid until a non-const member function of this string is called. If size() is zero, the data() function returns a NULL pointer. bool empty () const; Returns size() == 0. basic_string& erase (size_type pos = 0, size_type n = npos); iterator erase (iterator p); iterator erase (iterator first, iterator last); This function removes elements from the string, collapsing the remaining elements, as necessary, to remove any space left empty. The first version of the function removes the smaller of n and size() - pos starting at position pos. An out_of_range exception will be thrown if pos > size(). The second version requires that p is a valid iterator on this string, and removes the character referred to by p. The last version of erase requires that both first and last are valid iterators on this string, and removes the characters defined by the range [first,last). The destructors for all removed characters are called. All versions of erase return a reference to this string after completion. size_type find (const basic_string& str, size_type pos = 0) const; Searches for the first occurrence of the substring specified by str in this string, starting at position pos. If found, it returns the index of the first character of the matching substring. If not found, returns npos. Equality is defined by traits::eq(). size_type find (const charT* s, size_type pos, size_type n) const; size_type find (const charT* s, size_type pos = 0) const; size_type find (charT c, size_type pos = 0) const; Search for the first sequence of characters in this string that match a specified string. The variations of this function return, respectively: find(basic_string(s,n), pos) find(basic_string(s), pos) find(basic_string(1, c), pos) size_type find_first_not_of (const basic_string& str, size_type pos = 0) const; Searches for the first element of this string at or after position pos that is not equal to any element of str. If found, find_first_not_of returns the index of the non-matching character. If all of the characters match, the function returns npos. Equality is defined by traits::eq(). size_type find_first_not_of (const charT* s, size_type pos, size_type n) const; size_type find_first_not_of (const charT* s, size_type pos = 0) const; size_type find_first_not_of (charT c, size_type pos = 0) const; Search for the first element in this string at or after position pos that is not equal to any element of a given set of characters. The members return, respectively: find_first_not_of(basic_string(s,n), pos) find_first_not_of(basic_string(s), pos) find_first_not_of(basic_string(1, c), pos) size_type find_first_of(const basic_string& str, size_type pos = 0) const; Searches for the first occurrence at or after position pos of any element of str in this string. If found, the index of this matching character is returned. If not found, npos is returned. Equality is defined by traits::eq(). size_type find_first_of(const charT* s, size_type pos, size_type n) const; size_type find_first_of(const charT* s, size_type pos = 0) const; size_type find_first_of (charT c, size_type pos = 0) const; Search for the first occurrence in this string of any element in a specified string. The find_first_of variations return, respectively: find_first_of(basic_string(s,n), pos) find_first_of(basic_string(s), pos) find_first_of(basic_string(1, c), pos) size_type find_last_not_of(const basic_string& str, size_type pos = npos) const; Searches for the last element of this string at or before position pos that is not equal to any element of str. If find_last_not_of finds a non-matching element, it returns the index of the character. If all the elements match, the function returns npos. Equality is defined by traits::eq(). size_type find_last_not_of(const charT* s, size_type pos, size_type n) const; size_type find_last_not_of(const charT* s, size_type pos = npos) const; size_type find_last_not_of(charT c, size_type pos = npos) const; Search for the last element in this string at or before position pos that is not equal to any element of a given set of characters. The members return, respectively: find_last_not_of(basic_string(s,n), pos) find_last_not_of(basic_string(s), pos) find_last_not_of(basic_string(1, c), pos) size_type find_last_of(const basic_string& str, size_type pos = npos) const; Searches for the last occurrence of any element of str at or before position pos in this string. If found, find_last_of returns the index of the matching character. If not found find_last_of returns npos. Equality is defined by traits::eq(). size_type find_last_of(const charT* s, size_type pos, size_type n) const; size_type find_last_of(const charT* s, size_type pos = npos) const; size_type find_last_of(charT c, size_type pos = npos) const; Search for the last occurrence in this string of any element in a specified string. The members return, respectively: find_last_of(basic_string(s,n), pos) find_last_of(basic_string(s), pos) find_last_of(basic_string(1, c), pos) basic_string& insert(size_type pos1, const basic_string& s); basic_string& insert(size_type pos, const basic_string& s, size_type pos2 = 0, size_type n = npos); basic_string& insert(size_type pos, const charT* s, size_type n); basic_string& insert(size_type pos, const charT* s); basic_string& insert(size_type pos, size_type n, charT c); Insert additional elements at position pos in this string. All of the variants of this function will throw an out_of_range exception if pos > size(). All variants will also throw a length_error if the resulting string will exceed max_size(). Elements of this string will be moved apart as necessary to accommodate the inserted elements. All return a reference to this string after completion. The second variation of this function inserts the lesser of n and s.size() - pos2 characters of s, beginning at position pos2 in this string. This version will throw an out_of_range exception if pos2 > s.size(). The third version inserts n characters of the array pointed to by s. The fourth inserts elements from the array pointed to by s up to, but not including, a traits::eos() character. Finally, the fifth variation inserts n repetitions of c. iterator insert(iterator p, charT c = charT()); void insert(iterator p, size_type n, charT c); template void insert(iterator p, InputIterator first, InputIterator last); Insert additional elements in this string immediately before the character referred to by p. All of these versions of insert require that p is a valid iterator on this string. The first version inserts a copy of c. The second version inserts n repetitions of c. The third version inserts characters in the range [first, last). The first version returns p. size_type length() const; Return the number of elements contained in this string. size_type max_size() const; Returns the maximum possible size of the string. size_type rfind (const basic_string& str, size_type pos = npos) const; Searches for the last occurrence of the substring specified by str in this string, starting at position pos. Note that only the first character of the substring must be <= pos; the remaining characters may extend beyond pos. If found, the index of the first character of that matches substring is returned. If not found, npos is returned. Equality is defined by traits::eq(). size_type rfind(const charT* s, size_type pos, size_type n) const; size_type rfind(const charT* s, size_type pos = npos) const; size_type rfind(charT c, size_type pos = npos) const; Searches for the last sequence of characters in this string matching a specified string. The rfind variations return, respectively: rfind(basic_string(s,n), pos) rfind(basic_string(s), pos) rfind(basic_string(1, c), pos) basic_string& replace(size_type pos, size_type n1, const basic_string& s); basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s); basic_string& replace(size_type pos, size_type n1, size_type n2, charT c); The replace function replaces selected elements of this string with an alternate set of elements. All of these versions insert the new elements in place of n1 elements in this string, starting at position pos. They each throw an out_of_range exception if pos1 > size()and a length_error exception if the resulting string size exceeds max_size(). The second version replaces elements of the original string with n2 characters from string s starting at position pos2. It will throw the out_of_range exception if pos2 > s.size(). The third variation of the function replaces elements in the original string with n2 elements from the array pointed to by s. The fourth version replaces elements in the string with elements from the array pointed to by s, up to, but not including, a traits::eos() character. The fifth replaces n elements with n2 repetitions of character c. basic_string& replace(iterator i1, iterator i2, const basic_string& str); basic_string& replace(iterator i1, iterator i2, const charT* s, size_type n); basic_string& replace(iterator i1, iterator i2, const charT* s); basic_string& replace(iterator i1, iterator i2, size_type n, charT c); template basic_string& replace(iterator i1, iterator i2, InputIterator j1, InputIterator j2); Replace selected elements of this string with an alternative set of elements. All of these versions of replace require iterators i1 and i2 to be valid iterators on this string. The elements specified by the range [i1, i2) are replaced by the new elements. The first version shown here replaces with all members in str. The second version starts at position i1, and replaces the next n characters with n characters of the array pointed to by s. The third variation replaces string elements with elements from the array pointed to by s up to, but not including, a traits::eos() character. The fourth version replaces string elements with n repetitions of c. The last variation shown here replaces string elements with the members specified in the range [j1, j2). void reserve(size_type res_arg); Assures that the storage capacity is at least res_arg. void resize(size_type n, charT c); void resize(size_type n); Changes the capacity of this string to n. If the new capacity is smaller than the current size of the string, then it is truncated. If the capacity is larger, then the string is padded with c characters. The latter resize member pads the string with default characters specified by traits::eos(). size type size() const; Return the number of elements contained in this string. basic_string substr(size_type pos = 0, size_type n = npos) const; Returns a string composed of copies of the lesser of n and size() characters in this string starting at index pos. Throws an out_of_range exception if pos <= size(). void swap(basic_string& s); Swaps the contents of this string with the contents of s. NON-MEMBER OPERATORS template basic_string operator+(const basic_string& lhs, const basic_string& rhs); Returns a string of length lhs.size() + rhs.size(), where the first lhs.size() elements are copies of the elements of lhs, and the next rhs.size() elements are copies of the elements of rhs. template basic_string operator+(const charT* lhs, const basic_string& rhs); template basic_string operator+(charT lhs, const basic_string& rhs); template basic_string operator+(const basic_string& lhs, const charT* rhs); template basic_string operator+(const basic_string& lhs, charT rhs); Returns a string that represents the concatenation of two string-like entities. These functions return, respectively: basic_string(lhs) + rhs basic_string(1, lhs) + rhs lhs + basic_string(rhs) lhs + basic_string(1, rhs) template bool operator==(const basic_string& lhs, const basic_string& rhs); Returns a boolean value of true if lhs and rhs are equal, and false if they are not. Equality is defined by the compare() member function. template bool operator==(const charT* lhs, const basic_string& rhs); template bool operator==(const basic_string& lhs, const charT* rhs); Returns a boolean value indicating whether lhs and rhs are equal. Equality is defined by the compare() member function. These functions return, respectively: basic_string(lhs) == rhs lhs == basic_string(rhs) template bool operator!=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function. template bool operator!=(const charT* lhs, const basic_string& rhs); template bool operator!=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function. The functions return, respectively: basic_string(lhs) != rhs lhs != basic_string(rhs) template bool operator<(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical less-than relationship of lhs and rhs. Less-than is defined by the compare() member. template bool operator<(const charT* lhs, const basic_string& rhs); template bool operator<(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical less-than relationship of lhs and rhs. Less-than is defined by the compare() member function. These functions return, respectively: basic_string(lhs) < rhs lhs < basic_string(rhs) template bool operator>(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical greater-than relationship of lhs and rhs. Greater-than is defined by the compare() member function. template bool operator>(const charT* lhs, const basic_string& rhs); template bool operator>(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical greater-than relationship of lhs and rhs. Greater-than is defined by the compare() member. The functions return, respectively: basic_string(lhs) > rhs lhs > basic_string(rhs) template bool operator<=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical less-than-or-equal relationship of lhs and rhs. Less-than-or-equal is defined by the compare() member function. template bool operator<=(const charT* lhs, const basic_string& rhs); template bool operator<=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical less-than-or-equal relationship of lhs and rhs. Less-than-or-equal is defined by the compare() member function. These functions return, respectively: basic_string(lhs) <= rhs lhs <= basic_string(rhs) template bool operator>=(const basic_string& lhs, const basic_string& rhs); Returns a boolean value representing the lexicographical greater-than-or-equal relationship of lhs and rhs. Greater-than-or-equal is defined by the compare() member function. template bool operator>=(const charT* lhs, const basic_string& rhs); template bool operator>=(const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexicographical greater-than-or-equal relationship of lhs and rhs. Greater-than-or-equal is defined by the compare() member. The functions return, respectively: basic_string(lhs) >= rhs lhs >= basic_string(rhs) template void swap(basic_string& a, basic_string& b); Swaps the contents of a and b by calling a's swap function on b. template istream& operator>>(istream& is, basic_string& str); Reads str from is using traits::char_in until a traits::is_del() element is read. All elements read, except the delimiter, are placed in str. After the read, the function returns is. template ostream& operator<<(ostream& os, const basic_string& str); Writes all elements of str to os in order from first to last, using traits::char_out(). After the write, the function returns os. NON-MEMBER FUNCTION template Stream& getline(Stream& is, basic_string& str, charT delim); An unformatted input function that extracts characters from is into str until npos - 1 characters are read, the end of the input sequence is reached, or the character read is delim. The characters are read using traits::char_in(). EXAMPLE // // string.cpp // #include #include int main() { string test; //Type in a string over five characters long while(test.empty() || test.size() <= 5) { cout << "Type a string between 5 and 100 characters long. " << endl; cin >> test; } //Test operator[] access cout << "Changing the third character from " << test[2] << " to * " << endl; test[2] = '*'; cout << "now its: " << test << endl << endl; //Try the insertion member function cout << "Identifying the middle: "; test.insert(test.size() / 2, "(the middle is here!)"); cout << test << endl << endl; //Try replacement cout << "I didn't like the word 'middle',so instead,I'll say:" << endl; test.replace(test.find("middle",0), 6, "center"); cout << test << endl; return 0; } Output : Type a string between 5 and 100 characters long. roguewave Changing the third character from g to * now its: ro*uewave Identifying the middle: ro*u(the middle is here!)ewave I didn't like the word 'middle', so instead, I'll say: ro*u(the center is here!)ewave SEE ALSO Allocators, string, wstring STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_stringbuf Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_stringbuf SYNOPSIS #include template, class Allocator = allocator > class basic_stringbuf : public basic_streambuf DESCRIPTION The class basic_stringbuf is derived from basic_streambuf. Its purpose is to associate the input or output sequence with a sequence of arbitrary characters. The sequence can be initialized from, or made available as, an object of class basic_string. Each object of type basic_stringbuf controls two character sequences: + A character input sequence; + A character output sequence. Note: see basic_streambuf. The two sequences are related to each other, but are manipulated separately. This allows you to read and write characters at different positions in objects of type basic_stringbuf without any conflict (as opposed to the basic_filebuf objects, in which a joint file position is maintained). INTERFACE template, class allocator > class basic_stringbuf : public basic_streambuf { public: typedef basic_ios ios_type; typedef basic_string string_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_stringbuf(ios_base::openmode which = (ios_base::in | ios_base::out)); explicit basic_stringbuf(const string_type& str, ios_base::openmode which = (ios_base::in | ios_base::out)); virtual ~basic_stringbuf(); string_type str() const; void str(const string_type& str_arg); protected: virtual int_type overflow(int_type c = traits::eof()); virtual int_type pbackfail(int_type c = traits::eof()); virtual int_type underflow(); virtual basic_streambuf* setbuf(char_type *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); virtual streamsize xsputn(const char_type* s, streamsize n); }; TYPES char_type The type char_type is a synonym for the template parameter charT. ios_type The type ios_type is an instantiation of class basic_ios on type charT. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. string_type The type string_type is an instantiation of class basic_string on type charT. stringbuf The type stringbuf is an instantiation of class basic_stringbuf on type char: typedef basic_stringbuf stringbuf; traits_type The type traits_type is a synonym for the template parameter traits. wstringbuf The type wstringbuf is an instantiation of class basic_stringbuf on type wchar_t: typedef basic_stringbuf wstringbuf; CONSTRUCTORS explicit basic_stringbuf(ios_base::openmode which = ios_base::in | ios_base::out); Constructs an object of class basic_stringbuf, initializing the base class with basic_streambuf(), and initializing the open mode with which. explicit basic_stringbuf(const string_type& str, ios_base::openmode which = ios_base::in | ios_base::out); Constructs an object of class basic_stringbuf, initializing the base class with basic_streambuf(), and initializing the open mode with which. The string object str is copied to the underlying buffer. If the opening mode is in, initialize the input sequence to point at the first character of the buffer. If the opening mode is out, it initializes the output sequence to point at the first character of the buffer. If the opening mode is out | app, it initializes the output sequence to point at the last character of the buffer. DESTRUCTOR virtual ~basic_stringbuf(); Destroys an object of class basic_stringbuf. MEMBER FUNCTIONS int_type overflow(int_type c = traits::eof() ); If the output sequence has a put position available, and c is not traits::eof(), then this functions writes c into it. If there is no position available, the function increases the size of the buffer by allocating more memory and then writes c at the new current put position. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). int_type pbackfail( int_type c = traits::eof() ); Puts back the character designated by c into the input sequence. If traits::eq_int_type(c,traits::eof()) returns true, the function moves the input sequence one position backward. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, this function alters the stream position of both the input and the output sequences. If the open mode is in, it alters the stream position of only the input sequence, and if it is out, it alters the stream position of the output sequence. The new position is calculated by combining the two parameters off (displacement) and way (reference point). If the current position of the sequence is invalid before repositioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. pos_type seekpos(pos_type sp,ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, seekpos() alters the stream position of both the input and the output sequences. If the open mode is in, it alters the stream position of the input sequence only, and if the open mode is out, it alters the stream position of the output sequence only. If the current position of the sequence is invalid before repositioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. basic_streambuf* setbuf(char_type*s, streamsize n); If the string buffer object is opened in output mode, proceed as follows: if s is not a null pointer and n is greater than the content of the current buffer, replace it (copy its contents) by the buffer of size n pointed at by s. In the case where s is a null pointer and n is greater than the content of the current buffer, resize it to size n. If the function fails, it returns a null pointer. string_type str() const; Returns a string object of type string_type whose content is a copy of the underlying buffer contents. void str(const string_type& str_arg); Clears the underlying buffer and copies the string object str_arg into it. If the opening mode is in, initializes the input sequence to point at the first character of the buffer. If the opening mode is out, the function initializes the output sequence to point at the first character of the buffer. If the opening mode is out | app, it initializes the out- put sequence to point at the last character of the buffer. int_type underflow(); If the input sequence has a read position available, the function returns the contents of this position. Otherwise it tries to expand the input sequence to match the output sequence and if possible returns the content of the new current position. The function returns traits::eof() to indicate failure. streamsize xsputn(const char_type* s, streamsize n); Writes up to n characters to the output sequence. The characters written are obtained from successive elements of the array whose first element is designated by s. The function returns the number of characters written. EXAMPLES // // stdlib/examples/manual/stringbuf.cpp // #include #include #include void main ( ) { using namespace std; // create a read/write string-stream object on tiny char // and attach it to an ostringstream object ostringstream out_1(ios_base::in | ios_base::out); // tie the istream object to the ostringstream object istream in_1(out_1.rdbuf()); // output to out_1 out_1 << "Here is the first output"; // create a string object on tiny char string string_ex("l'heure est grave !"); // open a read only string-stream object on tiny char // and initialize it istringstream in_2(string_ex); // output in_1 to the standard output cout << in_1.str() << endl; // output in_2 to the standard output cout << in_2.rdbuf() << endl; // reposition in_2 at the beginning in_2.seekg(0); stringbuf::pos_type pos; // get the current put position // equivalent to // out_1.tellp(); pos = out_1.rdbuf()->pubseekoff(0,ios_base::cur, ios_base::out); // append the content of stringbuffer // pointed at by in_2 to the one // pointed at by out_1 out_1 << ' ' << in_2.rdbuf(); // output in_1 to the standard output cout << in_1.str() << endl; // position the get sequence // equivalent to // in_1.seekg(pos); in_1.rdbuf()->pubseekpos(pos, ios_base::in); // output "l'heure est grave !" cout << in_1.rdbuf() << endl << endl; } SEE ALSO char_traits, ios_base, basic_ios, basic_streambuf, basic_string, basic_istringstream, basic_ostringstream, basic_stringstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.7.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 2 IOStreams 3 iostream_intro Name iostream_intro - Introduction to the HP C++ Standard Library iostream Package This page is an introduction to the ANSI I/O stream classes. If you would like information on the pre-ANSI I/O stream package, use the command: help cxxl Description Compatibility The ANSI Standard Library provides two macros that enable or disable use of the ANSI iostream package at compile time. The ANSI iostream package may cause compile time and/or run time behavior incompatibilities that require source code changes to resolve. These macros allow users to choose the iostream package they want. Check the C++ documentation for a description of the default settings of these macros in different compiler modes. The -D HP C++ compiler switch can be used on the compile command line without requiring source code changes while the #define line should be added to the source code prior to any #include statement. All source modules within the same application must be compiled in the same mode. ________________________________________________________________ __USE_STD_IOSTREAM Usage Description ________________________________________________________________ cxx -D__USE_STD_IOSTREAM Use ANSI iostream package #define __USE_STD_IOSTREAM Use ANSI iostream package ________________________________________________________________ __NO_USE_STD_IOSTREAM Usage Description ________________________________________________________________ cxx -D__NO_USE_STD_IOSTREAM Use pre-ANSI iostream package #define __NO_USE_STD_IOSTREAM Use pre-ANSI iostream package ________________________________________________________________ See Also basic_iostream 3 basic_filebuf Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_filebuf,filebuf This page describes the ANSI basic_filebuf class. If you would like information on the pre-ANSI filebuf class, use the command: help cxxl SYNOPSIS #include template > class basic_filebuf : public basic_streambuf DESCRIPTION The template class basic_filebuf is derived from basic_streambuf. It associates the input or output sequence with a file. Each object of type basic_filebuf controls two character sequences: + a character input sequence + a character output sequence The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library files. If the file is not open for reading the input sequence cannot be read. If the file is not open for writing the output sequence cannot be written. A joint file position is maintained for both the input and output sequences. A file provides byte sequences. So the basic_filebuf class treats a file as the external source (or sink) byte sequence. In order to provide the contents of a file as wide character sequences, a wide-oriented file buffer called wfilebuf converts wide character sequences to multibytes character sequences (and vice versa) according to the current locale being used in the stream buffer. INTERFACE template > class basic_filebuf : public basic_streambuf { public: typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; basic_filebuf(); basic_filebuf(int fd); virtual ~basic_filebuf(); bool is_open() const; basic_filebuf* open(const char *s, ios_base::openmode, long protection = 0666); basic_filebuf* open(int fd); basic_filebuf* close(); protected: virtual int showmanyc(); virtual int_type overflow(int_type c = traits::eof()); virtual int_type pbackfail(int_type c = traits::eof()); virtual int_type underflow(); virtual basic_streambuf* setbuf(char_type *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); virtual int sync(); virtual streamsize xsputn(const char_type* s, streamsize n); }; TYPES char_type The type char_type is a synonym for the template parameter charT. filebuf The type filebuf is an instantiation of class basic_filebuf on type char: typedef basic_filebuf filebuf; int_type The type int_type is a synonym of type traits::in_type. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wfilebuf The type wfilebuf is an instantiation of class basic_filebuf on type wchar_t: typedef basic_filebuf wfilebuf; CONSTRUCTORS basic_filebuf(); Constructs an object of class basic_filebuf, initializing the base class with basic_streambuf(). basic_filebuf(int fd); Constructs an object of class basic_filebuf, initializing the base class with basic_streambuf(), then calls open(fd). This function is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. DESTRUCTOR virtual ~basic_filebuf(); Calls close() and destroys the object. MEMBER FUNCTIONS basic_filebuf* close(); If is_open() == false, returns a null pointer. Otherwise, closes the file, and returns *this. bool is_open() const; Returns true if the associated file is open. basic_filebuf* open(const char* s, ios_base::openmode mode, long protection = 0666); If is_open() == true, returns a null pointer. Otherwise opens the file, whose name is stored in the null-terminated byte-string s. The file open modes are given by their C-equivalent description (see the C function fopen): in "w" in|binary "rb" out "w" out|app "a" out|binary "wb" out|binary|app "ab" out|in "r+" out|in|app "a+" out|in|binary "r+b" out|in|binary|app "a+b" trunc|out "w" trunc|out|binary "wb" trunc|out|in "w+" trunc|out|in|binary "w+b" The third argument, protection, is used as the file permission. It does not appear in the Standard C++ description of the function open and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. If the open function fails, it returns a null pointer. basic_filebuf* open(int fd); Attaches the file previously opened and identified by its file descriptor fd, to the basic_filebuf object. This function is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. int_type overflow(int_type c = traits::eof() ); If the output sequence has a put position available, and c is not traits::eof(), then write c into it. If there is no position available, the function output the content of the buffer to the associated file and then write c at the new current put position. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). In wide characters file buffer, overflow converts the internal wide characters to their external multibytes representation by using the locale::codecvt facet located in the locale object imbued in the stream buffer. int_type pbackfail(int_type c = traits::eof() ); Puts back the character designated by c into the input sequence. If traits::eq_int_type(c,traits::eof()) returns true, move the input sequence one position backward. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, alters the stream position of both the input and the output sequence. If the open mode is in, alters the stream position of only the input sequence, and if it is out, alters the stream position of only the output sequence. The new position is calculated by combining the two parameters off (displacement) and way (reference point). If the current position of the sequence is invalid before repo- sitioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. File buffers using locale::codecvt facet performing state dependent conversion, only support seeking to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions. pos_type seekpos(pos_type sp,ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, alters the stream position of both the input and the output sequence. If the open mode is in, alters the stream position of only the input sequence, and if it is out, alters the stream position of only the output sequence. If the current position of the sequence is invalid before repositioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. File buffers using locale::codecvt facet performing state dependent conversion, only support seeking to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions. basic_filebuf* setbuf(char_type*s, streamsize n); If s is not a null pointer, output the content of the current buffer to the associated file, then delete the current buffer and replace it by s. Otherwise resize the current buffer to size n after outputting its content to the associated file if necessary. int sync(); Synchronizes the content of the external file, with its image maintained in memory by the file buffer. If the function fails, it returns -1, otherwise it returns 0. int_type underflow(); If the input sequence has a read position available, returns the content of this position. Otherwise fills up the buffer by reading characters from the associated file and if it succeeds, returns the content of the new current position. The function returns traits::eof() to indicate failure. In wide characters file buffer, underflow converts the external mutltibytes characters to their wide character representation by using the locale::codecvt facet located in the locale object imbued in the stream buffer. streamsize xsputn(const char_type* s, streamsize n); Writes up to n characters to the output sequence. The characters written are obtained from successive elements of the array whose first element is designated by s. The function returns the number of characters written. EXAMPLES // // stdlib/examples/manual/filebuf.cpp // #include #include void main ( ) { using namespace std; // create a read/write file-stream object on tiny char // and attach it to the file "filebuf.out" ofstream out("filebuf.out",ios_base::in | ios_base::out); // tie the istream object to the ofstream object istream in(out.rdbuf()); // output to out out << "Il errait comme un ame en peine"; // seek to the beginning of the file in.seekg(0); // output in to the standard output cout << in.rdbuf() << endl; // close the file "filebuf.out" out.close(); // open the existing file "filebuf.out" // and truncate it out.open("filebuf.out",ios_base::in | ios_base::out | ios_base::trunc); // set the buffer size out.rdbuf()->pubsetbuf(0,4096); // open the source code file ifstream ins("filebuf.cpp"); //output it to filebuf.out out << ins.rdbuf(); // seek to the beginning of the file out.seekp(0); // output the all file to the standard output cout << out.rdbuf(); } SEE ALSO char_traits, ios_base, basic_ios, basic_streambuf, basic_ifstream, basic_ofstream, basic_fstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.8.1.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_fstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_fstream,fstream,ofstream This page describes the ANSI basic_fstream class. If you would like information on the pre-ANSI fstream class, use the command: help cxxl SYNOPSIS #include template > class basic_fstream : public basic_iostream DESCRIPTION The template class basic_fstream supports reading and writing to named files or other devices associated with a file descriptor. It uses a basic_filebuf object to control the associated sequences. It inherits from basic_iostream and can therefore use all the formatted and unformatted input and output functions. INTERFACE template > class basic_fstream : public basic_iostream { public: typedef basic_ios ios_type; typedef charT char_type; typedef traits traits_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; basic_fstream(); explicit basic_fstream(const char *s, ios_base::openmode mode = ios_base::in | ios_base::out, long protection = 0666); explicit basic_fstream(int fd); basic_fstream(int fd, char_type *buf, int len); virtual ~basic_fstream(); basic_filebuf *rdbuf() const; bool is_open(); void open(const char *s, ios_base::openmode mode = ios_base::in | ios_base::out, long protection = 0666); void close(); }; TYPES char_type The type char_type is a synonym for the template parameter charT. fstream The type fstream is an instantiation of class basic_fstream on type char: typedef basic_fstream fstream; int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wfstream The type wfstream is an instantiation of class basic_fstream on type wchar_t: typedef basic_fstream wfstream; CONSTRUCTORS basic_fstream(); Constructs an object of class basic_fstream, initializing the base class basic_iostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). After construction, a file can be attached to the basic_ftream object by using the open() member function. basic_fstream(const char* s, ios_base::openmode mode= ios_base::in | iosw_base::out, long protection= 0666); Constructs an object of class basic_fstream, initializing the base class basic_iostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the open function open(s,mode,protection) in order to attach the file, whose name is pointed at by s, to the basic_ftream object. The third argument, protection, is used as the file permission. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. explicit basic_fstream(int fd); Constructs an object of class basic_fstream, initializing the base class basic_iostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_ftream object. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. If the function fails, it sets ios_base::failbit. basic_fstream(int fd, char_type* buf,int len); Constructs an object of class basic_fstream, initializing the base class basic_iostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_ftream object. The underlying buffer is then replaced by calling the basic_filebuf member function, setbuf(), with parameters buf and len. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets, or other UNIX devices that can be accessed through file descriptors. It also maintains compatibility with the old iostreams library. If the function fails, it sets ios_base::failbit. DESTRUCTOR virtual ~basic_fstream(); Destroys an object of class basic_fstream. MEMBER FUNCTIONS void close(); Calls the associated basic_filebuf function close() and if this function fails, it calls the basic_ios member function setstate(failbit). bool is_open(); Calls the associated basic_filebuf function is_open() and return its result. void open(const char* s,ios_base::openmode = ios_base::out | ios_base::in, long protection = 0666); Calls the associated basic_filebuf function open(s,mode,protection) and, if this function fails at opening the file, calls the basic_ios member function setstate(failbit). The third argument protection is used as the file permissions. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. basic_filebuf* rdbuf() const; Returns a pointer to the basic_filebuf associated with the stream. EXAMPLES // // stdlib/examples/manual/fstream.cpp // #include #include void main ( ) { using namespace std; // create a bi-directional fstream object fstream inout("fstream.out"); // output characters inout << "Das ist die rede von einem man" << endl; inout << "C'est l'histoire d'un home" << endl; inout << "This is the story of a man" << endl; char p[100]; // seek back to the beginning of the file inout.seekg(0); // extract the first line inout.getline(p,100); // output the first line to stdout cout << endl << "Deutch :" << endl; cout << p; fstream::pos_type pos = inout.tellg(); // extract the seconf line inout.getline(p,100); // output the second line to stdout cout << endl << "Francais :" << endl; cout << p; // extract the third line inout.getline(p,100); // output the third line to stdout cout << endl << "English :" << endl; cout << p; // move the put sequence before the second line inout.seekp(pos); // replace the second line inout << "This is the story of a man" << endl; // replace the third line inout << "C'est l'histoire d'un home"; // seek to the beginning of the file inout.seekg(0); // output the all content of the fstream object to stdout cout << endl << endl << inout.rdbuf(); } SEE ALSO char_traits, ios_base, basic_ios, basic_filebuf, basic_ifstream, basic_ofstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.8.1.11 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_ifstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_ifstream,fstream This page describes the ANSI basic_ifstream class. If you would like information on the pre-ANSI ifstream class, use the command: help cxxl SYNOPSIS #include template > class basic_ifstream : public basic_istream DESCRIPTION The template class basic_ifstream supports reading from named files or other devices associated with a file descriptor. It uses a basic_filebuf object to control the associated sequences. It inherits from basic_istream and can therefore use all the formatted and unformatted input functions. INTERFACE template > class basic_ifstream : public basic_istream { public: typedef basic_ios ios_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; basic_ifstream(); explicit basic_ifstream(const char *s, ios_base::openmode mode = ios_base::in, long protection = 0666); explicit basic_ifstream(int fd); basic_ifstream(int fd, char_type* buf, int len); virtual ~basic_ifstream(); basic_filebuf *rdbuf() const; bool is_open(); void open(const char *s, ios_base::openmode mode = ios_base::in, long protection = 0666); void close(); }; TYPES char_type The type char_type is a synonym for the template parameter charT. ifstream The type ifstream is an instantiation of class basic_ifstream on type char: typedef basic_ifstream ifstream; int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wifstream The type wifstream is an instantiation of class basic_ifstream on type wchar_t: typedef basic_ifstream wifstream; CONSTRUCTORS basic_ifstream(); Constructs an object of class basic_ifstream, initializing the base class basic_istream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). After construction, a file can be attached to the basic_iftream object by using the open member function. basic_ifstream(const char* s, ios_base::openmode mode= ios_base::in, long protection= 0666); Constructs an object of class basic_ifstream, initializing the base class basic_istream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the open function open(s,mode,protection) in order to attach the file whose name is pointed at by s, to the basic_iftream object. The third argument protection provides file permissions. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. explicit basic_ifstream(int fd) Constructs an object of class basic_ifstream, initializing the base class basic_istream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_iftream object. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. If the function fails, it sets ios_base::failbit. basic_ifstream(int fd, char_type* buf,int len); Constructs an object of class basic_ifstream, initializing the base class basic_istream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_iftream object. The underlying buffer is then replaced by calling the basic_filebuf member function setbuf with parameters buf and len. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. It also maintains compatibility with the old iostreams library. If the function fails, it sets ios_base::failbit. DESTRUCTOR virtual ~basic_ifstream(); Destroys an object of class basic_ifstream. MEMBER FUNCTIONS void close(); Calls the associated basic_filebuf function close() and if this function fails, it calls the basic_ios member function setstate(failbit). bool is_open(); Calls the associated basic_filebuf function is_open() and return its result. void open(const char* s,ios_base::openmode = ios_base::in, long protection = 0666); Calls the associated basic_filebuf function open(s,mode,protection). If this function fails opening the file, it calls the basic_ios member function setstate(failbit). The third argument protection provides file permissions. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. basic_filebuf* rdbuf() const; Returns a pointer to the basic_filebuf associated with the stream. EXAMPLES // // stdlib/examples/manual/ifstream.cpp // #include #include #include void main ( ) { using namespace std; long l= 20; char *ntbs="Le minot passait la piece a frotter"; char c; char buf[50]; try { // create a read/write file-stream object on char // and attach it to an ifstream object ifstream in("ifstream.out",ios_base::in | ios_base::out | ios_base::trunc); // tie the ostream object to the ifstream object ostream out(in.rdbuf()); // output ntbs in out out << ntbs << endl; // seek to the beginning of the file in.seekg(0); // output each word on a separate line while ( in.get(c) ) { if ( char_traits::eq(c,' ') ) cout << endl; else cout << c; } cout << endl << endl; // move back to the beginning of the file in.seekg(0); // clear the state flags in.clear(); // does the same thing as the previous code // output each word on a separate line while ( in >> buf ) cout << buf << endl; cout << endl << endl; // output the base info before each integer out << showbase; ostream::pos_type pos= out.tellp(); // output l in hex with a field with of 20 out << hex << setw(20) << l << endl; // output l in oct with a field with of 20 out << oct << setw(20) << l << endl; // output l in dec with a field with of 20 out << dec << setw(20) << l << endl; // move back to the beginning of the file in.seekg(0); // output the all file cout << in.rdbuf(); // clear the flags in.clear(); // seek the input sequence to pos in.seekg(pos); int a,b,d; // read the previous outputted integer in >> a >> b >> d; // output 3 times 20 cout << a << endl << b << endl << d << endl; } catch( ios_base::failure& var ) { cout << var.what(); } } SEE ALSO char_traits, ios_base, basic_ios, basic_filebuf, basic_ofstream, basic_fstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.8.1.5 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_ios Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_ios,ios This page describes the ANSI ios class. If you would like information on the pre-ANSI ios class, use the command: help cxxl SYNOPSIS #include template > class basic_ios : public ios_base DESCRIPTION The class basic_ios is a base class that provides the common functionality required by all streams. It maintains state information that reflects the integrity of the stream and stream buffer. It also maintains the link between the stream classes and the stream buffers classes via the rdbuf member functions. Classes derived from basic_ios specialize operations for input, and output. INTERFACE template > class basic_ios : public ios_base { public: typedef basic_ios ios_type; typedef basic_streambuf streambuf_type; typedef basic_ostream ostream_type; typedef typename traits::char_type char_type; typedef traits traits_type; typedef typename traits::int_type int_type; typedef typename traits::off_type off_type; typedef typename traits::pos_type pos_type; explicit basic_ios(basic_streambuf *sb_arg); virtual ~basic_ios(); char_type fill() const; char_type fill(char_type ch); void exceptions(iostate except); iostate exceptions() const; void clear(iostate state = goodbit); void setstate(iostate state); iostate rdstate() const; operator void*() const; bool operator!() const; bool good() const; bool eof() const; bool fail() const; bool bad() const; ios_type& copyfmt(const ios_type& rhs); ostream_type *tie() const; ostream_type *tie(ostream_type *tie_arg); streambuf_type *rdbuf() const; streambuf_type *rdbuf( streambuf_type *sb); locale imbue(const locale& loc); char narrow(charT, char) const; charT widen(char) const; protected: basic_ios(); void init(basic_streambuf *sb); }; TYPES char_type The type char_type is a synonym of type traits::char_type. ios The type ios is an instantiation of basic_ios on char: typedef basic_ios ios; int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is a synonym for basic_ios . off_type The type off_type is a synonym of type traits::off_type. ostream_type The type ostream_type is a synonym for basic_ostream . pos_type The type pos_type is a synonym of type traits::pos_type. streambuf_type The type streambuf_type is a synonym for basic_streambuf . traits_type The type traits_type is a synonym for the template parameter traits. wios The type wios is an instantiation of basic_ios on wchar_t: typedef basic_ios wios; PUBLIC CONSTRUCTORS explicit basic_ios(basic_streambuf* sb); Constructs an object of class basic_ios, assigning initial values to its member objects by calling init(sb). If sb is a null pointer, the stream is positioned in error state, by triggering its badbit. basic_ios(); Constructs an object of class basic_ios leaving its member objects uninitialized. The object must be initialized by calling the init member function before using it. PUBLIC DESTRUCTOR virtual ~basic_ios(); Destroys an object of class basic_ios. PUBLIC MEMBER FUNCTIONS bool bad() const; Returns true if badbit is set in rdstate(). void clear(iostate state = goodbit); If (state & exception()) == 0, returns. Otherwise, the function throws an object of class ios_base::failure. After the call returns state == rdstate(). basic_ios& copyfmt(const basic_ios& rhs); Assigns to the member objects of *this the corresponding member objects of rhs, with the following exceptions: + rdstate() and rdbuf() are left unchanged + calls ios_base::copyfmt + exceptions() is altered last by calling exceptions(rhs.exceptions()) bool eof() const; Returns true if eofbit is set in rdstate(). iostate exceptions() const; Returns a mask that determines what elements set in rdstate() cause exceptions to be thrown. void exceptions(iostate except); Set the exception mask to except then calls clear(rdstate()). bool fail() const; Returns true if failbit or badbit is set in rdstate(). char_type fill() const; Returns the character used to pad (fill) an output conversion to the specified field width. char_type fill(char_type fillch); Saves the field width value then replaces it by fillch and returns the previously saved value. bool good() const; Returns rdstate() == 0. locale imbue(const locale& loc); Saves the value returned by getloc() then assigns loc to a private variable and if rdbuf() != 0 calls rdbuf()->pubimbue(loc) and returns the previously saved value. void init(basic_streambuf* sb); Performs the following initialization: rdbuf() sb tie() 0 rdstate() goodbit if sb is not null otherwise badbit exceptions() goodbit flags() skipws | dec width() 0 precision() 6 fill() the space character getloc() locale::locale() char narrow(charT c, char dfault) const; Uses the stream's locale to convert the wide character c to a tiny character, and then returns it. If no conversion exists, it returns the character dfault. bool operator!() const; Returns fail() ? 1 : 0; streambuf_type* rdbuf() const; Returns a pointer to the stream buffer associated with the stream. streambuf_type* rdbuf(streambuf_type* sb); Associates a stream buffer with the stream. All the input and output will be directed to this stream buffer. If sb is a null pointer, the stream is positioned in error state, by triggering its badbit. iostate rdstate() const; Returns the control state of the stream. void setstate(iostate state); Calls clear(rdstate() | state). ostream_type* tie() const; Returns an output sequence that is tied to (synchronized with) the sequence controlled by the stream buffer. ostream_type* tie(ostream_type* tiestr); Saves the tie() value then replaces it by tiestr and returns the value previously saved. operator void*() const; Returns fail() ? 0 : 1; charT widen(char c) const; Uses the stream's locale to convert the tiny character c to a wide character, then returns it. SEE ALSO ios_base, basic_istream, basic_ostream, basic_streambuf, char_traits Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_iostream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_iostream,iostream This page describes the ANSI basic_iostream class. If you would like information on the pre-ANSI iostream class, use the command: help cxxl SYNOPSIS #include template > class basic_iostream : public basic_istream, public basic_ostream DESCRIPTION The class basic_iostream inherits a number of functions from classes basic_ostream and basic_istream. They assist in formatting and interpreting sequences of characters controlled by a stream buffer. Two groups of functions share common properties, the formatted functions and the unformatted functions. INTERFACE template class basic_iostream : public basic_istream, public basic_ostream { public: explicit basic_iostream(basic_streambuf *sb); virtual ~basic_iostream(); protected: explicit basic_iostream(); }; PUBLIC CONSTRUCTORS explicit basic_iostream(basic_streambuf* sb); Constructs an object of class basic_iostream, assigning initial values to the base class by calling basic_istream(sb) and basic_ostream(sb). explicit basic_iostream(); Constructs an object of class basic_iostream, assigning initial values to the base class by calling basic_istream() and basic_ostream(). After construction the object has its badbit set. DESTRUCTOR virtual ~basic_iostream(); Destroys an object of class basic_iostream. EXAMPLES See basic_istream and basic_ostream examples. COMPATIBILITY [Digital] The ANSI Standard Library provides two macros which enable or disable use of the ANSI iostream package at compile time. ______________________________________________________________ Macro Description ______________________________________________________________ __USE_STD_IOSTREAM Use the ANSI Standard iostream package __NO_USE_STD_IOSTREAM Use the pre-ANSI iostream package ______________________________________________________________ See ios_intro(help cxxl) or iostream_intro(help cxxlstd) for more details. SEE ALSO char_traits, ios_base, basic_ios, basic_streambuf, basic_istream, basic_ostream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.6.1.4.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_istream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_istream,istream This page describes the ANSI basic_istream class. If you would like information on the pre-ANSI istream class, use the command: help cxxl SYNOPSIS #include template > class basic_istream : virtual public basic_ios DESCRIPTION The class basic_istream defines a number of member function signatures that assist in reading and interpreting input from sequences controlled by a stream buffer. Two groups of member function signatures share common properties: the formatted input functions (or extractors) and the unformatted input functions. Both groups of input functions obtain (or extract) input characters by calling basic_streambuf member functions. They both begin by constructing an object of class basic_istream::sentry and, if this object is in good state after construction, the function endeavors to obtain the requested input. The sentry object performs exception safe initialization, such as controlling the status of the stream or locking it in multithread environment. Some formatted input functions parse characters extracted from the input sequence, converting the result to a value of some scalar data type, and storing the converted value in an object of that scalar type. The conversion behavior is locale dependent, and directly depend on the locale object imbued in the stream. INTERFACE template > class basic_istream : virtual public basic_ios { public: typedef basic_istream istream_type; typedef basic_ios ios_type; typedef basic_streambuf streambuf_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_istream(basic_streambuf *sb); virtual ~basic_istream(); class sentry { public: inline explicit sentry(basic_istream&, bool noskipws = 0); ~sentry(); operator bool (); }; istream_type& operator>>(istream_type& (*pf)(istream_type&)); istream_type& operator>>(ios_base& (*pf)(ios_base&)); istream_type& operator>>(ios_type& (*pf)(ios_type&)); istream_type& operator>>(bool& n); istream_type& operator>>(short& n); istream_type& operator>>(unsigned short& n); istream_type& operator>>(int& n); istream_type& operator>>(unsigned int& n); istream_type& operator>>(long& n); istream_type& operator>>(unsigned long& n); istream_type& operator>>(float& f); istream_type& operator>>(double& f); istream_type& operator>>(long double& f); istream_type& operator>>(void*& p); istream_type& operator>>(streambuf_type& sb); istream_type& operator>>(streambuf_type *sb); int_type get(); istream_type& get(char_type *s, streamsize n, char_type delim); istream_type& get(char_type *s, streamsize n); istream_type& get(char_type& c); istream_type& get(streambuf_type& sb,char_type delim); istream_type& get(streambuf_type& sb); istream_type& getline(char_type *s, streamsize n,char_type delim); istream_type& getline(char_type *s, streamsize n); istream_type& ignore(streamsize n = 1, int_type delim = traits::eof()); istream_type& read(char_type *s, streamsize n); streamsize readsome(char_type *s, streamsize n); int peek(); pos_type tellg(); istream_type& seekg(pos_type&); istream_type& seekg(off_type&, ios_base::seekdir); istream_type& putback(char_type c); istream_type& unget(); streamsize gcount() const; int sync(); protected: explicit basic_istream( ); }; //global function template basic_istream& ws(basic_istream&); template basic_istream& operator>> (basic_istream&, charT&); template basic_istream& operator>> (basic_istream&, charT*); template basic_istream& operator>> (basic_istream&, unsigned char&); template basic_istream& operator>> (basic_istream&, signed char&); template basic_istream& operator>> (basic_istream&, unsigned char*); template basic_istream& operator>> (basic_istream&, signed char*); TYPES char_type The type char_type is a synonym for them template parameter charT. int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is a synonym for basic_ios . istream The type istream is an instantiation of class basic_istream on type char: typedef basic_istream istream; istream_type The type istream_type is a synonym for basic_istream. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. streambuf_type The type streambuf_type is a synonym for basic_streambuf. traits_type The type traits_type is a synonym for the template parameter traits. wistream The type wistream is an instantiation of class basic_istream on type wchar_t: typedef basic_istream wistream; PUBLIC CONSTRUCTOR explicit basic_istream(basic_streambuf* sb); Constructs an object of class basic_istream, assigning initial values to the base class by calling basic_ios::init(sb). PUBLIC DESTRUCTOR virtual ~basic_istream(); Destroys an object of class basic_istream. SENTRY CLASS explicit sentry(basic_istream&, bool noskipws=0); Prepares for formatted or unformatted input. First if the basic_ios member function tie() is not a null pointer, the function synchronizes the output sequence with any associated stream. If noskipws is zero and the ios_base member function flags() & skipws is nonzero, the function extracts and discards each character as long as the next available input character is a white space character. If after any preparation is completed the basic_ios member function good() is true, the sentry conversion function operator bool() will return true. Otherwise it will return false. In multithread environment the sentry object constructor is responsible for locking the stream and the stream buffer associated with the stream. ~sentry(); Destroys an object of class sentry. In multithread environment, the sentry object destructor is responsible for unlocking the stream and the stream buffer associated with the stream. operator bool(); If after any preparation is completed the basic_ios member function good() is true, the sentry conversion function operator bool() will return true else it will return false. EXTRACTORS istream_type& operator>>(istream_type& (*pf) (istream_type&)); Calls pf(*this), then return *this. See, for example, the function signature ws(basic_istream&). istream_type& operator>>(ios_type& (*pf) (ios_type&)); Calls pf(*this), then return *this. istream_type& operator>>(ios_base& (*pf) (ios_base&)); Calls pf(*this), then return *this. See, for example, the function signature dec(ios_base&). istream_type& operator>>(bool& n); Converts a Boolean value, if one is available, and stores it in n. If the ios_base member function flag() & ios_base::boolalpha is false it tries to read an integer value, which if found must be 0 or 1. If the boolalpha flag is true, it reads characters until it determines whether the characters read are correct according to the locale function numpunct<>::truename() or numpunct<>::falsename(). If no match is found, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. istream_type& operator>>(short& n); Converts a signed short integer, if one is available, and stores it in n, then returns *this. istream_type& operator>>(unsigned short& n); Converts an unsigned short integer, if one is available, and stores it in n, then return *this. istream_type& operator>>(int& n); Converts a signed integer, if one is available, and stores it in n, then return *this. istream_type& operator>>(unsigned int& n); Converts an unsigned integer, if one is available, and stores it in n, then return *this. istream_type& operator>>(long& n); Converts a signed long integer, if one is available, and stores it in n, then returns *this. istream_type& operator>>(unsigned long& n); Converts an unsigned long integer, if one is available, and stores it in n, then returns *this. istream_type& operator>>(float& f); Converts a float, if one is available, and stores it in f, then returns *this. istream_type& operator>>(double& f); Converts a double, if one is available, and stores it in f, then returns *this. istream_type& operator>>(long double& f); Converts a long double, if one is available, and stores it in f, then returns *this. istream_type& operator>>(void*& p); Extracts a void pointer, if one is available, and stores it in p, then return *this. istream_type& operator>>(streambuf_type* sb); If sb is null, calls the basic_ios member function setstate(badbit), which may throw ios_base::failure. Otherwise extracts characters from *this and inserts them in the output sequence controlled by sb. Characters are extracted and inserted until any of the following occurs: + end-of-file occurs on the input sequence + inserting in the output sequence fails + an exception occurs If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. If failure was due to catching an exception thrown while extracting characters from sb and failbit is on in exception(), then the caught exception is rethrown. istream_type& operator>>(streambuf_type& sb); Extracts characters from *this and inserts them in the output sequence controlled by sb. Characters are extracted and inserted until and of the following occurs: + end-of-file occurs on the input sequence + inserting in the output sequence fails + an exception occurs If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. If failure was due to catching an exception thrown while extracting characters from sb and failbit is on in exception(), then the caught exception is rethrown. UNFORMATTED FUNCTIONS streamsize gcount() const; Returns the number of characters extracted by the last unformatted input member function called. int_type get(); Extracts a character, if one is available. Otherwise, the function calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. Returns the character extracted or traits::eof() if none is available. istream_type& get(char_type& c); Extracts a character, if one is available, and assigns it to c. Otherwise, the function calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. istream_type& get(char_type* s, streamsize n,char_type delim); Extracts characters and stores them into successive locations of an array whose first element is designated by s. Characters are extracted and stored until any of the following occurs: + n-1 characters are stored + end-of-file occurs on the input sequence + the next available input character == delim. If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. In any case, it stores a null character into the next successive location of the array. istream_type& get(char_type* s, streamsize n); Calls get(s,n,widen('0)). istream_type& get(streambuf_type& sb,char_type delim); Extracts characters and inserts them in the output sequence controlled by sb. Characters are extracted and inserted until any of the following occurs: + end-of-file occurs on the input sequence + inserting in the output sequence fails + the next available input character == delim. + an exception occurs If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. If failure was due to catching an exception thrown while extracting characters from sb and failbit is on in exception(), then the caught exception is rethrown. istream_type& get(streambuf_type& sb); Calls get(sb,widen('0)). istream_type& getline(char_type* s, streamsize n, char_type delim); Extracts characters and stores them into successive locations of an array whose first element is designated by s. Characters are extracted and stored until any of the following occurs: + n-1 characters are stored + end-of-file occurs on the input sequence + the next available input character == delim. If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. In any case, it stores a null character into the next successive location of the array. istream_type& getline(char_type* s, streamsize n); Calls getline(s,n,widen('0)). istream_type& ignore(streamsize n=1, int_type delim=traits::eof()); Extracts characters and discards them. Characters are extracted until any of the following occurs: + n characters are extracted + end-of-file occurs on the input sequence + the next available input character == delim. int_type peek(); Returns traits::eof() if the basic_ios member function good() returns false. Otherwise, returns the next available character. Does not increment the current get pointer. istream_type& putback(char_type c); Insert c in the putback sequence. istream_type& read(char_type* s, streamsize n); Extracts characters and stores them into successive locations of an array whose first element is designated by s. Characters are extracted and stored until any of the following occurs: + n characters are stored + end-of-file occurs on the input sequence If the function does not store n characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. streamsize readsome(char_type* s, streamsize n); Extracts characters and stores them into successive locations of an array whose first element is designated by s. If rdbuf()->in_avail() == -1, calls the basic_ios member function setstate(eofbit). + If rdbuf()->in_avail() == 0, extracts no characters + If rdbuf()->in_avail() > 0, extracts min( rdbuf()->in_avail(), n) In any case the function returns the number of characters extracted. istream_type& seekg(pos_type& pos); If the basic_ios member function fail() returns false, executes rdbuf()->pubseekpos(pos), which will position the current pointer of the input sequence at the position designated by pos. istream_type& seekg(off_type& off, ios_base::seekdir dir); If the basic_ios member function fail() returns false, executes rdbuf()->pubseekpos(off,dir), which will position the current pointer of the input sequence at the position designated by off and dir. int sync(); If rdbuf() is a null pointer, return -1. Otherwise, calls rdbuf()- >pubsync() and if that function returns -1 calls the basic_ios member function setstate(badbit). The purpose of this function is to synchronize the internal input buffer, with the external sequence of characters. pos_type tellg(); If the basic_ios member function fail() returns true, tellg() returns pos_type(off_type(-1)) to indicate failure. Otherwise it returns the current position of the input sequence by calling rdbuf()- >pubseekoff(0,cur,in). istream_type& unget(); If rdbuf() is not null, calls rdbuf()->sungetc(). If rdbuf() is null or if sungetc() returns traits::eof(), calls the basic_ios member function setstate(badbit). NON MEMBER FUNCTIONS template basic_istream& operator>>(basic_istream& is, charT& c); Extracts a character if one is available, and stores it in c. Otherwise the function calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. template basic_istream& operator>>(basic_istream& is, charT* s); Extracts characters and stores them into successive locations of an array whose first element is designated by s. If the ios_base member function is.width() is greater than zero, then is.width() is the maximum number of characters stored. Characters are extracted and stored until any of the following occurs: + if is.witdh()>0, is.witdh()-1 characters are extracted + end-of-file occurs on the input sequence + the next available input character is a white space. If the function stores no characters, it calls the basic_ios member function setstate(failbit), which may throw ios_base::failure. In any case, it then stores a null character into the next successive location of the array and calls width(0). Template basic_istream& operator>>(basic_istream& is, unsigned char& c); Returns is >> (char&)c. Template basic_istream& operator>>(basic_istream& is, signed char& c); Returns is >> (char&)c. Template basic_istream& operator>>(basic_istream& is, unsigned char* c); Returns is >> (char*)c. Template basic_istream& operator>>(basic_istream& is, signed char* c); Returns is >> (char*)c. template basic_istream& ws(basic_istream& is); Skips any white space in the input sequence and returns is. EXAMPLES // // stdlib/examples/manual/istream1.cpp // #include #include #include void main ( ) { using namespace std; float f= 3.14159; int i= 3; char s[200]; // open a file for read and write operations ofstream out("example", ios_base::in | ios_base::out | ios_base::trunc); // tie the istream object to the ofstream filebuf istream in (out.rdbuf()); // output to the file out << "Annie is the Queen of porting" << endl; out << f << endl; out << i << endl; // seek to the beginning of the file in.seekg(0); f = i = 0; // read from the file using formatted functions in >> s >> f >> i; // seek to the beginning of the file in.seekg(0,ios_base::beg); // output the all file to the standard output cout << in.rdbuf(); // seek to the beginning of the file in.seekg(0); // read the first line in the file // "Annie is the Queen of porting" in.getline(s,100); cout << s << endl; // read the second line in the file // 3.14159 in.getline(s,100); cout << s << endl; // seek to the beginning of the file in.seekg(0); // read the first line in the file // "Annie is the Queen of porting" in.get(s,100); // remove the newline character in.ignore(); cout << s << endl; // read the second line in the file // 3.14159 in.get(s,100); cout << s << endl; // remove the newline character in.ignore(); // store the current file position istream::pos_type position = in.tellg(); out << "replace the int" << endl; // move back to the previous saved position in.seekg(position); // output the remain of the file // "replace the int" // this is equivalent to // cout << in.rdbuf(); while( !char_traits::eq_int_type(in.peek(), char_traits::eof()) ) cout << char_traits::to_char_type(in.get()); cout << "0 << flush; } // // istream example two // #include void main ( ) { using namespace std; char p[50]; // remove all the white spaces cin >> ws; // read characters from stdin until a newline // or 49 characters have been read cin.getline(p,50); // output the result to stdout cout << p; } SEE ALSO char_traits, ios_base, basic_ios, basic_streambuf, basic_iostream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.6.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_istringstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_istringstream SYNOPSIS #include template, class Allocator = allocator > class basic_istringstream : public basic_istream DESCRIPTION The template class basic_istringstream provides functionality to read from an array in memory. It supports reading objects of class basic_string. It uses a basic_stringbuf object to control the associated storage. It inherits from basic_istream and therefore can use all the formatted and unformatted input functions. INTERFACE template, class Allocator = allocator > class basic_istringstream : public basic_istream { public: typedef basic_stringbuf sb_type; typedef basic_ios ios_type; typedef basic_string string_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_istringstream(ios_base::openmode which = ios_base::in); explicit basic_istringstream(const string_type& str, ios_base::openmode which = ios_base::in); virtual ~basic_istringstream(); basic_stringbuf *rdbuf() const; string_type str() const; void str(const string_type& str); }; TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. istringstream The type istringstream is an instantiation of class basic_istringstream on type char: typedef basic_istringstream istringstream; off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. sb_type The type sb_type is an instantiation of class basic_stringbuf on type charT. string_type The type string_type is an instantiation of class basic_string on type charT. traits_type The type traits_type is a synonym for the template parameter traits. wistringstream The type wistringstream is an instantiation of class basic_istringstream on type wchar_t: typedef basic_istringstream wistringstream; CONSTRUCTORS explicit basic_istringstream(ios_base::openmode which = ios_base::in); Constructs an object of class basic_istringstream, initializing the base class basic_istream with the associated string buffer. The string buffer is ini- tialized by calling the basic_stringbuf constructor basic_stringbuf(which). explicit basic_istringstream(const string_type& str, ios_base::openmode which = ios_base::in); Constructs an object of class basic_istringstream, initializing the base class basic_istream with the associated string buffer. The string buffer is ini- tialized by calling the basic_stringbuf constructor basic_stringbuf(str,which). DESTRUCTOR virtual ~basic_istringstream(); Destroys an object of class basic_istringstream. MEMBER FUNCTIONS basic_stringbuf* rdbuf() const; Returns a pointer to the basic_stringbuf associated with the stream. string_type str() const; Returns a string object of type string_type, which contains a copy of the underlying buffer contents. void str(const string_type& str); Clears the string buffer and copies the string object str into it. If the opening mode is in, initialize the input sequence to point at the first character of the buffer. If the opening mode is out, initialize the output sequence to point at the first character of the buffer. If the opening mode is out | app, initialize the output sequence to point at the last character of the buffer. EXAMPLES // // stdlib/examples/manual/istringstream.cpp // #include #include #include #include void main ( ) { using namespace std; long l= 20; wchar_t *ntbs=L"Il avait l'air heureux"; wchar_t c; wchar_t buf[50]; // create a read/write string-stream object on wide char // and attach it to an wistringstream object wistringstream in(ios_base::in | ios_base::out); // tie the ostream object to the wistringstream object wostream out(in.rdbuf()); // output ntbs in out out << ntbs; // output each word on a separate line while ( in.get(c) ) { if ( c == L' ' ) wcout << endl; else wcout << c; } wcout << endl << endl; // move back the input sequence to the beginning in.seekg(0); // clear the state flags in.clear(); // does the same thing as the previous code // output each word on a separate line while ( in >> buf ) wcout << buf << endl; wcout << endl << endl; // create a tiny string object string test_string("Il dormait pour l'eternite"); // create a read/write string-stream object on char // and attach it to an istringstream object istringstream in_bis(ios_base:: in | ios_base::out | ios_base::app ); // create an ostream object ostream out_bis(in_bis.rdbuf()); // initialize the string buffer with test_string in_bis.str(test_string); out_bis << endl; // output the base info before each integer out_bis << showbase; ostream::pos_type pos= out_bis.tellp(); // output l in hex with a field with of 20 out_bis << hex << setw(20) << l << endl; // output l in oct with a field with of 20 out_bis << oct << setw(20) << l << endl; // output l in dec with a field with of 20 out_bis << dec << setw(20) << l << endl; // output the all buffer cout << in_bis.rdbuf(); // seek the input sequence to pos in_bis.seekg(pos); int a,b,d; // read the previous outputted integer in_bis >> a >> b >> d; // output 3 times 20 cout << a << endl << b << endl << d << endl; } SEE ALSO char_traits, ios_base, basic_ios, basic_stringbuf, basic_string, basic_ostringstream, basic_stringstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.7.2 STANDARDS CONFORMANC ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_ofstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_ofstream,ofstream This page describes the ANSI basic_ofstream class. If you would like information on the pre-ANSI ofstream class, use the command: help cxxl SYNOPSIS #include template > class basic_ofstream : public basic_ostream DESCRIPTION The template class basic_ofstream supports writing into named files or other devices associated with a file descriptor. It uses a basic_filebuf object to control the associated sequences. It inherits from basic_ostream and can therefore use all the formatted and unformatted output functions. INTERFACE template > class basic_ofstream : public basic_ostream { public: typedef basic_ios ios_type; typedef charT char_type; typedef traits traits_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; basic_ofstream(); explicit basic_ofstream(const char *s, ios_base::openmode mode = ios_base::out, long protection = 0666); explicit basic_ofstream(int fd); basic_ofstream(int fd, char_type* buf, int len); virtual ~basic_ofstream(); basic_filebuf *rdbuf() const; bool is_open(); void open(const char *s, ios_base::openmode mode = ios_type::out, long protection = 0666); void close(); }; TYPES char_type The type char_type is a synonym for the template parameter charT. off_type The type off_type is a synonym of type traits::off_type. ofstream The type ofstream is an instantiation of class basic_ofstream on type char: typedef basic_ofstream ofstream; int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wofstream The type wofstream is an instantiation of class basic_ofstream on type wchar_t: typedef basic_ofstream wofstream; CONSTRUCTORS basic_ofstream(); Constructs an object of class basic_ofstream, initializing the base class basic_ostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). After construction a file can be attached to the basic_oftream object using the open member function. basic_ofstream(const char* s, ios_base::openmode mode= ios_base::in, long protection= 0666); Constructs an object of class basic_ofstream, initializing the base class basic_ostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the open function open(s,mode,protection) in order to attach the file whose name is pointed at by s, to the basic_oftream object. The third argument, protection, is used as the file permissions. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. explicit basic_ofstream(int fd); Constructs an object of class basic_ofstream, initializing the base class basic_ostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_oftream object. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. If the function fails, it sets ios_base::failbit. basic_ofstream(int fd, char_type* buf,int len); Constructs an object of class basic_ofstream, initializing the base class basic_ostream with the associated file buffer, which is initialized by calling the basic_filebuf constructor basic_filebuf(). The constructor then calls the basic_filebuf open function open(fd) in order to attach the file descriptor fd to the basic_oftream object. The underlying buffer is then replaced by calling the basic_filebuf member function setbuf with parameters buf and len. This constructor is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. It also maintains compatibility with the old iostreams library. If the function fails, it sets ios_base::failbit. DESTRUCTOR virtual ~basic_ofstream(); Destroys an object of class basic_ofstream. MEMBER FUNCTIONS void close(); Calls the associated basic_filebuf function close() and if this function fails, it calls the basic_ios member function setstate(failbit). bool is_open(); Calls the associated basic_filebuf function is_open() and return its result. void open(const char* s,ios_base::openmode = ios_base::out, long protection = 0666); Calls the associated basic_filebuf function open(s,mode,protection) and, if this function fails opening the file, calls the basic_ios member function setstate(failbit). The third argument, protection, is used as the file permis- sions. It does not appear in the Standard C++ description and is provided as an extension. It determines the file read/write/execute permissions under UNIX, and is more limited under DOS since files are always readable and do not have special execute permission. basic_filebuf* rdbuf() const; Returns a pointer to the basic_filebuf associated with the stream. EXAMPLES See basic_fstream, basic_ifstream and basic_filebuf examples. SEE ALSO char_traits, ios_base, basic_ios, basic_filebuf, basic_ifstream, basic_fstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.8.1.8 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_ostream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_ostream SYNOPSIS #include template > class basic_ostream : virtual public basic_ios DESCRIPTION The class basic_ostream defines a number of member function signatures that assist in formatting and writing output to sequences controlled by a stream buffer. Two groups of member function signatures share common properties: the formatted output functions (or insertors) and the unformatted output functions. Both groups of functions insert characters by calling basic_streambuf member functions. They both begin by constructing an object of class basic_ostream::sentry and, if this object is in good state after construction, the function tries to perform the requested output. The sentry object performs exception-safe initialization, such as controlling the status of the stream or locking it in multithread environment. Some formatted output functions generate the requested output by converting a value from some scalar to text form and inserting the converted text in the output sequence. The conversion behavior is locale dependent, and directly depend on the locale object imbued in the stream. INTERFACE template > class basic_ostream :virtual public basic_ios { public: typedef basic_ostream ostream_type; typedef basic_ios ios_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_ostream(basic_streambuf *sb); virtual ~basic_ostream(); class sentry { public: explicit sentry(basic_ostream&); ~sentry(); operator bool (); }; ostream_type& operator<<(ostream_type& (*pf)(ostream_type&)); ostream_type& operator<<(ios_base& (*pf)(ios_base&)); ostream_type& operator<<(ios_type& (*pf)(ios_type&)); ostream_type& operator<<(bool n); ostream_type& operator<<(short n); ostream_type& operator<<(unsigned short n); ostream_type& operator<<(int n); ostream_type& operator<<(unsigned int n); ostream_type& operator<<(long n); ostream_type& operator<<(unsigned long n); ostream_type& operator<<(float f); ostream_type& operator<<(double f); ostream_type& operator<<(long double f); ostream_type& operator<<(void *p); ostream_type& operator<<(basic_streambuf& sb); ostream_type& operator<<(basic_streambuf *sb); ostream_type& put(char_type c); ostream_type& write(const char_type *s, streamsize n); ostream_type& flush(); ostream_type& seekp(pos_type ); ostream_type& seekp(off_type , ios_base::seekdir ); pos_type tellp(); protected: basic_ostream(); }; //global functions template basic_ostream& operator<<(basic_ostream&, charT); template basic_ostream& operator<<(basic_ostream&, char); template basic_ostream& operator<<(basic_ostream&, char); template basic_ostream& operator<<(basic_ostream&, const charT*); template basic_ostream& operator<<(basic_ostream&, const char*); template basic_ostream& operator<<(basic_ostream&, const char*); template basic_ostream& operator<<(basic_ostream&, unsigned char); template basic_ostream& operator<<(basic_ostream&, signed char); template basic_ostream& operator<<(basic_ostream&, const unsigned char*); template basic_ostream& operator<<(basic_ostream&, const signed char*); template basic_ostream& endl(basic_ostream& os); template basic_ostream& ends(basic_ostream& os); template basic_ostream& flush(basic_ostream& os); TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is a synonym for basic_ios. off_type The type off_type is a synonym of type traits::off_type. ostream The type ostream is an instantiation of class basic_ostream on type char: typedef basic_ostream ostream; ostream_type The type ostream_type is a synonym for basic_ostream. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wostream The type wostream is an instantiation of class basic_ostream on type wchar_t: typedef basic_ostream wostream; CONSTRUCTOR explicit basic_ostream(basic_streambuf* sb); Constructs an object of class basic_ostream, assigning initial values to the base class by calling basic_ios::init(sb). DESTRUCTOR virtual ~basic_ostream(); Destroys an object of class basic_ostream. SENTRY CLASS explicit sentry(basic_ostream&); Prepares for formatted or unformatted output. First if the basic_ios member function tie() is not a null pointer, the function synchronizes the output sequence with any associated stream. If after any preparation is completed the basic_ios member function good() is true, the sentry conversion function operator bool () will return true. Otherwise it will return false. In multithread environment the sentry object constructor is responsible for locking the stream and the stream buffer associated with the stream. ~sentry(); Destroys an object of class sentry. If the ios_base member function flags() & unitbuf == true, then flush the buffer. In multithread environment the sentry object destructor is responsible for unlocking the stream and the stream buffer associated with the stream. operator bool(); If after any preparation is completed the ios_base member function good() is true, the sentry conversion function operator bool() will return true else it will return false. INSERTORS ostream_type& operator<<(ostream_type& (*pf) (ostream_type&)); Calls pf(*this), then return *this. See, for example, the function signature endl(basic_ostream&). ostream_type& operator<<(ios_type& (*pf) (ios_type&)); Calls pf(*this), then return *this. ostream_type& operator<<(ios_base& (*pf) (ios_base&)); Calls pf(*this), then return *this. See, for example, the function signature dec(ios_base&). ostream_type& operator<<(bool n); Converts the boolean value n, and outputs it into the basic_ostream object's buffer. If the ios_base member function flag() & ios_base::boolalpha is false it tries to write an integer value, which must be 0 or 1. If the boolalpha flag is true, it writes characters according to the locale function numpunct<>::truename() or numpunct<>::falsename(). ostream_type& operator<<(short n); Converts the signed short integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(unsigned short n); Converts the unsigned short integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(int n); Converts the signed integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(unsigned int n); Converts the unsigned integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(long n); Converts the signed long integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(unsigned long n); Converts the unsigned long integer n, and output it into the stream buffer, then return *this. ostream_type& operator<<(float f); Converts the float f and output it into the stream buffer, then return *this. ostream_type& operator<<(double f); Converts the double f and output it into the stream buffer, then return *this. ostream_type& operator<<(long double f); Converts the long double f and output it into the stream buffer, then return *this. ostream_type& operator<<(void *p); Converts the pointer p, and output it into the stream buffer, then return *this. ostream_type& operator<<(basic_streambuf *sb); If sb is null calls the basic_ios member function setstate(badbit). Otherwise gets characters from sb and inserts them into the stream buffer until any of the following occurs: + end-of-file occurs on the input sequence. + inserting in the output sequence fails + an exception occurs while getting a character from sb If the function inserts no characters or if it stopped because an exception was thrown while extracting a character, it calls the basic_ios member function setstate(failbit). If an exception was thrown while extracting a character it is rethrown. ostream_type& operator<<(basic_streambuf& sb); Gets characters from sb and inserts them into the stream buffer until any of the following occurs: + end-of-file occurs on the input sequence. + inserting in the output sequence fails + an exception occurs while getting a character from sb If the function inserts no characters or if it stopped because an exception was thrown while extracting a character, it calls the basic_ios member function setstate(failbit). If an exception was thrown while extracting a character it is rethrown. UNFORMATTED FUNCTIONS ostream_type& flush(); If rdbuf() is not a null pointer, calls rdbuf()->pubsync() and returns *this. If that function returns -1 calls setstate(badbit). ostream_type& put(char_type c); Inserts the character c. If the operation fails, calls the basic_ios member function setstate(badbit). ostream_type& seekp(pos_type pos); If the basic_ios member function fail() returns false, executes rdbuf()->pubseekpos(pos), which will position the current pointer of the output sequence at the position designated by pos. ostream_type& seekp(off_type off, ios_base::seekdir dir); If the basic_ios member function fail() returns false, executes rdbuf()->pubseekpos(off,dir), which will position the current pointer of the output sequence at the position designated by off and dir. pos_type tellp(); If the basic_ios member function fail() returns true, tellp() returns pos_type(off_type(-1)) to indicate failure. Otherwise it returns the current position of the output sequence by calling rdbuf()-> pubseekoff(0,cur, out). ostream_type& write(const char_type* s, streamsize n); Obtains characters to insert from successive locations of an array whose first element is designated by s. Characters are inserted until either of the following occurs: + n characters are inserted + inserting in the output sequence fails In the second case the function calls the basic_ios member function setstate(badbit). The function returns *this. NON MEMBER FUNCTIONS template basic_ostream& endl(basic_ostream& os); Outputs a newline character and flush the buffer, then returns os. template basic_ostream& ends(basic_ostream& os); Inserts a null character into the output sequence, then returns os. template basic_ostream& flush(basic_ostream& os); Flushes the buffer, then returns os. template basic_ostream& operator<<(basic_ostream& os, charT c); Outputs the character c of type charT into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type charT. Padding is not ignored. template basic_ostream& operator<<(basic_ostream& os, char c); Outputs the character c of type char into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type charT. Conversion from characters of type char to characters of type charT is performed by the basic_ios member function widen. padding is not ignored. template basic_ostream& operator<<(basic_ostream& os, char c); Outputs the character c of type char into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type char. Padding is not ignored. template basic_ostream& operator<<(basic_ostream& os, const charT* s); Outputs the null-terminated-byte-string s of type charT* into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type charT. template basic_ostream& operator<<(basic_ostream& os, const char* s); Outputs the null-terminated-byte-string s of type char* into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type charT. Conversion from characters of type char to characters of type charT is performed by the basic_ios member function widen. template basic_ostream& operator<<(basic_ostream& os, const char* s); Outputs the null-terminated-byte-string s of type char* into the basic_ostream object's buffer. Both the stream and the stream buffer are instantiated on type char. template basic_ostream& operator<<(basic_ostream& os, unsigned char c); Returns os << (char)c. template basic_ostream& operator<<(basic_ostream& os, signed char c); Returns os << (char)c. template basic_ostream& operator<<(basic_ostream& os, unsigned char* c); Returns os << (char*)c. template basic_ostream& operator<<(basic_ostream& os, signed char* c); Returns os << (char*)c. FORMATTING The formatting is done through member functions or manipulators. Manipulators Member Functions showpos setf(ios_base::showpos) noshowpos unsetf(ios_base::showpos) showbase setf(ios_base::showbase) noshowbase unsetf(ios_base::showbase) uppercase setf(ios_base::uppercase) nouppercase unsetf(ios_base::uppercase) showpoint setf(ios_base::showpoint) noshowpoint unsetf(ios_base::showpoint) boolalpha setf(ios_base::boolalpha) noboolalpha unsetf(ios_base::boolalpha) unitbuf setf(ios_base::unitbuf) nounitbuf unsetf(ios_base::unitbuf) internal setf(ios_base::internal, ios_base::adjustfield) left setf(ios_base::left, ios_base::adjustfield) right setf(ios_base::right, ios_base::adjustfield) dec setf(ios_base::dec, ios_base::basefield) hex setf(ios_base::hex, ios_base::basefield) oct setf(ios_base::oct, ios_base::basefield) fixed setf(ios_base::fixed, ios_base::floatfield) scientific setf(ios_base::scientific, ios_base::floatfield) resetiosflags (ios_base::fmtflags flag) setf(0,flag) setiosflags (ios_base::fmtflags flag) setf(flag) setbase(int base) See above setfill(char_type c) fill(c) setprecision(int n) precision(n) setw(int n) width(n) DESCRIPTION showpos Generates a + sign in non-negative generated numeric output showbase Generates a prefix indicating the numeric base of generated integer output uppercase Replaces certain lowercase letters with their uppercase equivalents in generated output showpoint Generates a decimal-point character unconditionally in gen- erated floating-point output boolalpha Insert and extract bool type in alphabetic format unitbuf Flushes output after each output operation internal Adds fill characters at a designated internal point in certain generated output, or identical to right if no such point is designated left Adds fill characters on the right (final positions) of certain generated output right Adds fill characters on the left (initial positions) of certain generated output dec Converts integer input or generates integer output in decimal base hex Converts integer input or generates integer output in hexadecimal base oct Converts integer input or generates integer output in octal base fixed Generates floating-point output in fixed-point notation scientific Generates floating-point output in scientific notation resetiosflagss (ios_base::fmtflags flag) Resets the fmtflags field flag setiosflags (ios_base::fmtflags flag) Set up the flag flag setbase(int base) Converts integer input or generates integer output in base base. The parameter base can be 8, 10 or 16. setfill(char_type c) Set the character used to pad (fill) an output conversion to the specified field width setprecision(int n) Set the precision (number of digits after the decimal point) to generate on certain output conversions setw(int n) Set the field with (number of characters) to generate on certain output conversions EXAMPLES // // stdlib/examples/manual/ostream1.cpp // #include #include #include #include void main ( ) { using namespace std; float f= 3.14159; int i= 22; char* s= "Randy is the king of stdlib"; // create a read/write stringbuf object on tiny char // and attach it to an istringstream object istringstream in( ios_base::in | ios_base::out ); // tie the ostream object to the istringstream object ostream out(in.rdbuf()); out << "test beginning !" << endl; // output i in hexadecimal out << hex << i < #include #include void main ( ) { using namespace std; float f= 3.14159; wchar_t* s= L"Kenavo !"; // create a read/write stringbuf object on wide char // and attach it to an wistringstream object wistringstream in( ios_base::in | ios_base::out ); // tie the wostream object to the wistringstream object wostream out(in.rdbuf()); out << L"test beginning !" << endl; // output f in scientific format out << scientific << f < template, class Allocator = allocator > class basic_ostringstream : public basic_ostream DESCRIPTION The template class basic_ostringstream provides functionality to write to an array in memory. It supports writing objects of class basic_string. It uses a basic_stringbuf object to control the associated storage. It inherits from basic_ostream and therefore can use all the formatted and unformatted output functions. INTERFACE template, class Allocator = allocator > class basic_ostringstream : public basic_ostream { public: typedef basic_stringbuf sb_type; typedef basic_ios ios_type; typedef basic_string string_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_ostringstream(ios_base::openmode which = ios_base::out); explicit basic_ostringstream(const string_type& str, ios_base::openmode which = ios_base::out); virtual ~basic_ostringstream(); basic_stringbuf *rdbuf() const; string_type str() const; void str(const string_type& str); }; TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. off_type The type off_type is a synonym of type traits::off_type. ostringstream The type ostringstream is an instantiation of class basic_ostringstream on type char: typedef basic_ostringstream ostringstream; pos_type The type pos_type is a synonym of type traits::pos_type. sb_type The type sb_type is an instantiation of class basic_stringbuf on type charT. string_type The type string_type is an instantiation of class basic_string on type charT. traits_type The type traits_type is a synonym for the template parameter traits. wostringstream The type wostringstream is an instantiation of class basic_ostringstream on type wchar_t: typedef basic_ostringstream wostringstream; CONSTRUCTORS explicit basic_ostringstream(ios_base::openmode which = ios_base::out); Constructs an object of class basic_ostringstream, initializing the base class basic_ostream with the associated string buffer. The string buffer is initial- ized by calling the basic_stringbuf con- structor basic_stringbuf(which). explicit basic_ostringstream(const string_type& str, ios_base::openmode which = ios_base::out); Constructs an object of class basic_ostringstream, initializing the base class basic_ostream with the associated string buffer. The string buffer is initial- ized by calling the basic_stringbuf con- structor basic_stringbuf(str,which). DESTRUCTOR virtual ~basic_ostringstream(); Destroys an object of class basic_ostringstream. MEMBER FUNCTIONS basic_stringbuf* rdbuf() const; Returns a pointer to the basic_stringbuf associated with the stream. string_type str() const; Returns a string object of type string_type whose contents is a copy of the underlying buffer contents. void str(const string_type& str); Clears the underlying string buffer and copies the string object str into it. If the opening mode is in, initialize the input sequence to point at the first character of the buffer. If the opening mode is out, initialize the output sequence to point at the first character of the buffer. If the opening mode is out | app, initialize the output sequence to point at the last character of the buffer. EXAMPLES See basic_stringstream, basic_istringstream and basic_stringbuf examples. SEE ALSO char_traits, ios_base, basic_ios, basic_stringbuf, basic_string, basic_istringstream, basic_stringstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.7.2.3 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_streambuf Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_streambuf,streambuf This page describes the ANSI streambuf class. If you would like information on the pre-ANSI streambuf class, use the command: help cxxl SYNOPSIS #include template > class basic_streambuf; DESCRIPTION The class template basic_streambuf serves as an abstract base class for deriving various stream buffers whose objects each control two character sequences: + A character input sequence; + A character output sequence. Each sequence is characterized by three pointers which, if non-null, all point into the same charT array object. The array object represents, at any moment, a subsequence of characters from the sequence. Operations performed on a sequence alter the values stored in these pointers, perform reads and writes directly to or from associated sequences, and alter "the stream position" and conversion state as needed to maintain this subsequence rela- tionship. The three pointers are: + The beginning pointer, or lowest element address in the array; + The next pointer, or next element address that is a current candidate for reading or writing; + The end pointer, or first element address beyond the end of the array. Stream buffers can impose various constraints on the sequences they control, including: + The controlled input sequence may be unreadable; + The controlled output sequence may be unwritable; + The controlled sequences can be associated with the contents of other representations for character sequences, such as external files; + The controlled sequences can impose limitations on how the program can read characters from a sequence, write characters to a sequence, put characters back into an input sequence, or alter the stream position. INTERFACE template > class basic_streambuf { public: typedef charT char_type; typedef traits traits_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; virtual ~basic_streambuf(); locale pubimbue( const locale& loc); locale getloc() const; basic_streambuf * pubsetbuf(char_type *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(); ios_base::openmode which_open_mode(); streamsize in_avail(); int_type snextc(); int_type sbumpc(); int_type sgetc(); streamsize sgetn(char_type *s, streamsize n); int_type sputbackc(char_type c); int sungetc(); int_type sputc(char_type c); streamsize sputn(const char_type *s, streamsize n); protected: basic_streambuf(); char_type *eback() const; char_type *gptr() const; char_type *egptr() const; void gbump(int n); void setg(char_type *gbeg_arg,char_type *gnext_arg, char_type *gend_arg); char_type *pbase() const; char_type *pptr() const; char_type *epptr() const; void pbump(int n); void setp(char_type *pbeg_arg,char_type *pend_arg); virtual void imbue( const locale& loc); virtual int_type overflow(int_type c = traits::eof()); virtual int_type pbackfail(int_type c = traits::eof()); virtual int showmanyc(); virtual int_type underflow(); virtual int_type uflow(); virtual streamsize xsgetn(char_type *s, streamsize n); virtual streamsize xsputn(const char_type *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); virtual basic_streambuf* setbuf(char_type *s, streamsize n); virtual int sync(); }; TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. streambuf The type streambuf is an instantiation of class basic_streambuf on type char: typedef basic_streambuf streambuf; traits_type The type traits_type is a synonym for the template parameter traits. wstreambuf The type wstreambuf is an instantiation of class basic_streambuf on type wchar_t: typedef basic_streambuf wstreambuf; PUBLIC CONSTRUCTOR basic_streambuf(); Constructs an object of class basic_streambuf and initializes all its pointer member objects to null pointers and the getloc() member function to return the value of locale::locale(). PUBLIC DESTRUCTOR virtual ~basic_streambuf(); Destroys an object of class basic_streambuf. PUBLIC MEMBER FUNCTIONS locale getloc() const; If pubimbue() has ever been called, returns the last value of loc supplied, otherwise, the default locale locale::locale() in effect at the time of construction. streamsize in_avail(); If a read position is available, returns the number of available character in the input sequence. Otherwise calls the protected function showmanyc(). locale pubimbue(const locale& loc); Calls the protected function imbue(loc). pos_type pubseekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out ); Calls the protected function seekoff(off,way,which). pos_type pubseekpos(pos_type sp, ios_base::openmode which= ios_base::in | ios_base::out ); Calls the protected function seekpos(sp,which). basic_streambuf* pubsetbuf(char_type* s,streamsize n); Calls the protected function setbuf(s,n) . int pubsync(); Calls the protected function sync(). int_type sbumpc(); If the input sequence read position is not available, calls the function uflow(), otherwise returns *gptr() and increments the next pointer for the input sequence. int_type sgetc(); If the input sequence read position is not available, calls the protected function underflow(), otherwise returns *gptr() . streamsize sgetn(char_type* s, streamsize n); Calls the protected function xsgetn(s,n). int_type snextc(); Calls the function sbumpc() and if it returns traits::eof(), returns traits::eof(); otherwise calls the function sgetc() . int_type sputbackc(char_type c); If the input sequence putback position is not available, or if traits::eq(c,gptr() [-1]) returns false, calls the protected function pbackfail(c), otherwise decrements the next pointer for the input sequence and returns *gptr(). int_type sputc(char_type c); If the output sequence write position is not available, calls the protected function overflow(traits::to_int_type( c )). Otherwise, stores c at the next pointer for the output sequence, increments the pointer, and returns *pptr() . streamsize sputn(const char_type* s, streamsize n); Calls the protected function xsputn(s,n). int_type sungetc(); If the input sequence putback position is not available, calls the protected function pbackfail(). Otherwise decrements the next pointer for the input sequence and returns *gptr(). ios_base::openmode which_open_mode(); Returns the mode in which the stream buffer is opened. This function is not described in the C++ standard. PROTECTED MEMBER FUNCTIONS char_type* eback() const; Returns the beginning pointer for the input sequence. char_type* egptr() const; Returns the end pointer for the input sequence. char_type* epptr() const; Returns the end pointer for the output sequence. void gbump(int n); Advances the next pointer for the input sequence by n. char_type* gptr() const; Returns the next pointer for the input sequence. void imbue(const locale&); Changes any translations based on locale. The default behavior is to do nothing, this function has to be overloaded in the classes derived from basic_streambuf. The purpose of this function is to allow the derived class to be informed of changes in locale at the time they occur. The new imbued locale object is only used by the stream buffer, it does not affect the stream itself. int_type overflow(int_type c = traits::eof() ); The member functions sputc() and sputn() call this function in case that not enough room can be found in the put buffer to accommodate the argument character sequence. The function returns traits::eof() if it fails to make more room available, or to empty the buffer by writing the characters to their output device. int_type pbackfail(int_type c = traits::eof() ); If c is equal to traits::eof(), gptr() is moved back one position otherwise c is prepended. The function returns traits::eof() to indicate failure. char_type* pbase() const; Returns the beginning pointer for the output sequence. void pbump(int n); Advances the next pointer for the output sequence by n. char_type* pptr() const; Returns the next pointer for the output sequence. pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out ); Alters the stream positions within one or more of the controlled sequences in a way that is defined separately for each class derived from basic_streambuf. The default behavior is to return an object of type pos_type that stores an invalid stream posi- tion. pos_type seekpos(pos_type sp, ios_base::openmode which= ios_base::in | ios_base::out ); Alters the stream positions within one or more of the controlled sequences in a way that is defined separately for each class derived from basic_streambuf. The default behavior is to return an object of class pos_type that stores an invalid stream posi- tion. basic_streambuf* setbuf(char_type* s, streamsize n); Performs an operation that is defined separately for each class derived from basic_streambuf. The purpose of this function is to allow the user to provide his own buffer, or to resize the current buffer. void setg(char_type* gbeg, char_type* gnext, char_type* gend); Sets up private member for the following to be true: eback() == gbeg, gptr() == gnext and egptr() == gend void setp(char_type* pbeg, char_type* pend); Sets up private member for the following to be true: pbase() == pbeg, pptr() == pbeg and epptr() == pend int showmanyc(); Returns the number of characters available in the internal buffer, or -1. int sync(); Synchronizes the controlled sequences with the internal buffer, in a way that is defined separately for each class derived from basic_streambuf. The default behavior is to do nothing. On failure the return value is -1. int_type underflow(); The public members of basic_streambuf call this function only if gptr() is null or gptr() >= egptr(). This function returns the character pointed at by gptr() if gptr() is not null and if gptr() < egptr(). Otherwise the function try to read character into the buffer, and if it fails return traits::eof(). int_type uflow(); Calls underflow() and if underflow() returns traits::eof(), returns traits::eof(). Otherwise, does gbump(1) and returns the value of *gptr(). streamsize xsgetn(char_type* s, streamsize n); Assigns up to n characters to successive elements of the array whose first element is designated by s. The characters are read from the input sequence. Assigning stops when either n characters have been assigned or a call to sbumpc() would return traits::eof(). The function returns the number of characters read. streamsize xsputn(const char_type* s, streamsize n); Writes up to n characters to the output sequence. The characters written are obtained from successive elements of the array whose first element is designated by s. Writing stops when either n characters have been written or a call to sputc() would return traits::eof(). The function returns the number of characters written. SEE ALSO char_traits, basic_filebuf, basic_stringbuf, strstreambuf Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.5 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 basic_stringstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_stringstream SYNOPSIS #include template, class Allocator = allocator > class basic_stringstream : public basic_iostream DESCRIPTION The template class basic_stringstream provides functionality to read and write to an array in memory. It supports writing and reading objects of class basic_string. It uses a basic_stringbuf object to control the associated storage. It inherits from basic_iostream and therefore can use all the formatted and unformatted output and input functions. INTERFACE template, class Allocator = allocator > class basic_stringstream : public basic_iostream { public: typedef basic_stringbuf sb_type; typedef basic_ios ios_type; typedef basic_string string_type; typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; explicit basic_stringstream(ios_base::openmode which = ios_base::out | ios_base::in); explicit basic_stringstream(const string_type& str, ios_base::openmode which = ios_base::out | ios_base::in); virtual ~basic_stringstream(); basic_stringbuf *rdbuf() const; string_type str() const; void str(const string_type& str); }; TYPES char_type The type char_type is a synonym for the template parameter charT. int_type The type int_type is a synonym of type traits::in_type. ios_type The type ios_type is an instantiation of class basic_ios on type charT. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. sb_type The type sb_type is an instantiation of class basic_stringbuf on type charT. string_type The type string_type is an instantiation of class basic_string on type charT. stringstream The type stringstream is an instantiation of class basic_stringstream on type char: typedef basic_stringstream stringstream; traits_type The type traits_type is a synonym for the template parameter traits. wstringstream The type wstringstream is an instantiation of class basic_stringstream on type wchar_t: typedef basic_stringstream wstringstream; CONSTRUCTORS explicit basic_stringstream(ios_base::openmode which = ios_base::in | ios_base::out); Constructs an object of class basic_stringstream, ini- tializing the base class basic_iostream with the asso- ciated string buffer. The string buffer is initialized by calling the basic_stringbuf constructor basic_stringbuf(which). explicit basic_stringstream(const string_type& str, ios_base::openmode which = ios_base::in | ios_base::out); Constructs an object of class basic_stringstream, ini- tializing the base class basic_iostream with the asso- ciated string buffer. The string buffer is initialized by calling the basic_stringbuf constructor basic_stringbuf(str,which). DESTRUCTOR virtual ~basic_stringstream(); Destroys an object of class basic_stringstream. MEMBER FUNCTIONS basic_stringbuf* rdbuf() const; Returns a pointer to the basic_stringbuf associated with the stream. string_type str() const; Returns a string object of type string_type whose contents is a copy of the underlying buffer contents. void str(const string_type& str); Clears the string buffer and copies the string object str into it. If the opening mode is in, initializes the input sequence to point at the first character of the buffer. If the opening mode is out, initializes the output sequence to point at the first character of the buffer. If the opening mode is out | app, initializes the output sequence to point at the last character of the buffer. EXAMPLES // // stdlib/examples/manual/stringstream.cpp // #include #include void main ( ) { using namespace std; // create a bi-directional wstringstream object wstringstream inout; // output characters inout << L"Das ist die rede von einem man" << endl; inout << L"C'est l'histoire d'un home" << endl; inout << L"This is the story of a man" << endl; wchar_t p[100]; // extract the first line inout.getline(p,100); // output the first line to stdout wcout << endl << L"Deutch :" << endl; wcout << p; // extract the seconf line inout.getline(p,100); // output the second line to stdout wcout << endl << L"Francais :" << endl; wcout << p; // extract the third line inout.getline(p,100); // output the third line to stdout wcout << endl << L"English :" << endl; wcout << p; // output the all content of the //wstringstream object to stdout wcout << endl << endl << inout.str(); } SEE ALSO char_traits, ios_base, basic_ios, basic_stringbuf, basic_string, basic_istringstream, basic_ostringstream(3c++) Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.7.3 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 cerr Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME cerr SYNOPSIS #include extern ostream cerr; DESCRIPTION ostream cerr; The object cerr controls output to an unbuffered stream buffer associated with the object stderr declared in . By default, the standard C and C++ streams are synchronized, but you may improve performance by using the ios_base member function synch_with_stdio to desynchronize them. FORMATTING The formatting is done through member functions or manipulators. See cout or basic_ostream for details. EXAMPLES // // cerr example // #include #include void main ( ) { using namespace std; // open the file "file_name.txt" // for reading ifstream in("file_name.txt"); // output the all file to stdout if ( in ) cout << in.rdbuf(); else // if the ifstream object is in a bad state // output an error message to stderr cerr << "Error while opening the file" << endl; } SEE ALSO basic_ostream, iostream, basic_filebuf, cout, cin, clog, wcin, wcout, wcerr, wclog, iomanip, ios_base, basic_ios Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.3.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 char_traits Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME char_traits_ - A traits class providing types and operations to the basic_string container and iostream classes. SYNOPSIS #include template struct char_traits struct char_traits; . struct char_traits; DESCRIPTION The char_traits struct provides elementary operations to instantiations of basic_string and iostream classes. As with all traits classes, char_traits is used to specialize the behavior of a template. In this case, the traits class provides functions based on character type to the basic_string template and to the templates that are part of the iostreams library. Specializations of char_traits are provided for char and wchar_t. These are used to define, respectively, string and wstring, cout and wcout, etc. INTERFACE template struct char_traits . { typedef charT char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; typedef mbstate_t state_type; static void assign (char_type&, const char_type&); static char_type* assign (char_type*, size_t, const char_type&); static bool eq (const char_type&, const char_type&); static bool lt (const char_type&, const char_type&); static int compare (const char_type*, const char_type*, size_t); static size_t length (const char_type * s); static const char_type* find (const char_type*, int, const char_type&); static char_type* move (char_type*, const char_type*, size_t); static char_type* copy (char_type*, const char_type*, size_t); static int_type not_eof(const int_type& c); static char_type to_char_type(const int_type& c); static int_type to_int_type(const char_type& c); static bool eq_int_type(const int_type& c1, const int_type& c2); static int_type eof(); }; TYPE char_type The basic character type. Same as the template parameter. int_type A type that can represent all the character values of char_type as well as and end of file value. pos_type A type used to represent a position within a stream buffer. off_type A type used to represent an offset to a position within a stream buffer. state_type A type used to represent the state class or type that is applied to the codecvt facet. This type is only relevant for streams with a underlying character type that is multi-byte. OPERATIONS static void assign(char_type& c1, const char_type& c2) Assigns one character value to another. The value of c2 is assigned to c1. static char_type* assign(char_type* s, size_t n, const char_type& a) Assigns one character value to n elements of a character array. The value of a is assigned to n elements of s. static bool eq(const char_type& c1, const char_type& c2) Returns true if c1 equals c2. static bool lt(const char_type& c1, const char_type& c2) Returns true if c1 is less than c2. static int compare(const char_type* s1, const char_type* s2, size_t n) Compares n values from s1 with n values from s2. Return 1 if s1 is greater than s2, -1 if s1 is less than s2, or 0 if they are equal. static size_t length(const char_type * s) Returns the length of the null terminated character array s. The eos terminator is not counted. static const char_type* find(const char_type* s, int n, const char_type& a) Looks for the value of a in s. Only n elements of s are examined. Returns a pointer to the matched element if one is found. Otherwise returns s + n. static char_type* move(char_type* s1, const char_type* s2, size_t n) Moves n values from s1 to s2. The ranges of (s1,s1+n) and (s2,s2+n) may overlap. static char_type* copy(char_type* s1, const char_type* s2, size_t n) Copy n values from s1 to s2. The ranges of (s1,s1+n) and (s2,s2+n) may not overlap. static int_type not_eof(const int_type& c) Returns c if c is not equal to eof(), otherwise returns 0. static int_type to_char_type(const int_type& c) Returns the char_type representation of c. This value may not be useful if no such representation exists. static int_type to_int_type(const char_type& c) Returns the int_type representation of c. static bool eq_int_type(const int_type& c1, const int_type& c2) Returns true if c1 equals c2. static int_type eof() Returns EOF. SEE ALSO basic_string, traits, basic_ostream, basic_istream, cout, cin, wcout, wcin STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 cin Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME cin SYNOPSIS #include extern istream cin; DESCRIPTION istream cin; The object cin controls input from a stream buffer associated with the object stdin declared in . By default, the standard C and C++ streams are syn chronized, but you can improve performance by using the ios_base member function synch_with_stdio to desynchronize them. After the object cin is initialized, cin.tie() returns &cout, which implies that cin and cout are synchronized. EXAMPLES // // cin example one // #include void main ( ) { using namespace std; int i; float f; char c; //read an integer, a float and a character from stdin cin >> i >> f >> c; // output i, f and c to stdout cout << i << endl << f << endl << c << endl; } // // cin example two // #include void main ( ) { using namespace std; char p[50]; // remove all the white spaces cin >> ws; // read characters from stdin until a newline // or 49 characters have been read cin.getline(p,50); // output the result to stdout cout << p; } When inputting " Grendel the monster" (newline) in the previous test, the output will be "Grendel the monster". The manipulator ws removes spaces. SEE ALSO basic_istream, iostream, basic_filebuf, cout, cerr, clog, wcin, wcout, wcerr, wclog, ios_base, basic_ios Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.3.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 cout Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME cout SYNOPSIS #include extern ostream cout; DESCRIPTION ostream cout; The object cout controls output to a stream buffer associated with the object stdout declared in . By default the standard C and C++ streams are synchronized, but performance improvement can be achieved by using the ios_base member function synch_with_stdio to desynchronize them. After the object cin is initialized, cin.tie() returns &cout, which implies that cin and cout are synchronized. FORMATTING The formatting is done through member functions or manipulators. Manipulators Member functions showpos setf(ios_base::showpos) noshowpos unsetf(ios_base::showpos) showbase setf(ios_base::showbase) noshowbase unsetf(ios_base::showbase) uppercase setf(ios_base::uppercase) nouppercase unsetf(ios_base::uppercase) showpoint setf(ios_base::showpoint) noshowpoint unsetf(ios_base::showpoint) boolalpha setf(ios_base::boolalpha) noboolalpha unsetf(ios_base::boolalpha) unitbuf setf(ios_base::unitbuf) nounitbuf unsetf(ios_base::unitbuf) internal setf(ios_base::internal, ios_base::adjustfield) left setf(ios_base::left, ios_base::adjustfield) right setf(ios_base::right, ios_base::adjustfield) dec setf(ios_base::dec, ios_base::basefield) hex setf(ios_base::hex, ios_base::basefield) oct setf(ios_base::oct, ios_base::basefield) fixed setf(ios_base::fixed, ios_base::floatfield) scientific setf(ios_base::scientific, ios_base::floatfield) resetiosflags (ios_base::fmtflags flag) setf(0,flag) setiosflags (ios_base::fmtflags flag) setf(flag) setbase(int base) See above setfill(char_type c) fill(c) setprecision(int n) precision(n) setw(int n) width(n) endl ends flush flush( ) DESCRIPTION showpos Generates a + sign in non-negative generated numeric output. showbase Generates a prefix indicating the numeric base of generated integer output. uppercase Replaces certain lowercase letters with their uppercase equivalents in generated output. showpoint Generates a decimal-point character unconditionally in generated floating-point output. boolalpha Insert and extract bool type in alphabetic format. unitbuf Flushes output after each output operation. internal Adds fill characters at a designated internal point in certain generated output, or identical to right if no such point is designated. left Adds fill characters on the right (final positions) of certain generated output. right Adds fill characters on the left (initial positions) of certain generated output. dec Converts integer input or generates integer output in decimal base. hex Converts integer input or generates integer output in hexadecimal base. oct Converts integer input or generates integer output in octal base. fixed Generates floating-point output in fixed-point notation. scientific Generates floating-point output in scientific notation. resetiosflagss (ios_base::fmtflags flag) Resets the fmtflags field flag. setiosflags (ios_base::fmtflags flag) Sets up the flag flag. setbase(int base) Converts integer input or generates integer output in base base. The parameter base can be 8, 10 or 16. setfill(char_type c) Sets the character used to pad (fill) an output conversion to the specified field width. setprecision(int n) Set the precision (number of digits after the decimal point) to generate on certain output conversions. setw(int n) Sets the field with (number of characters) to generate on certain output conversions endl Inserts a newline character into the output sequence and flush the output buffer. ends Inserts a null character into the output sequence. flush Flush the output buffer. DEFAULT VALUES precision() 6 width() 0 fill() the space character flags() skipws | dec getloc() locale::locale() EXAMPLES // // cout example one // #include #include void main ( ) { using namespace std; int i; float f; // read an integer and a float from stdin cin >> i >> f; // output the integer and goes at the line cout << i << endl; // output the float and goes at the line cout << f << endl; // output i in hexa cout << hex << i << endl; // output i in octal and then in decimal cout << oct << i << dec << i << endl; // output i preceded by its sign cout << showpos << i << endl; // output i in hexa cout << setbase(16) << i << endl; // output i in dec and pad to the left with character // @ until a width of 20 // if you input 45 it outputs 45@@@@@@@@@@@@@@@@@@ cout << setfill('@') << setw(20) << left << dec << i; cout << endl; // output the same result as the code just above // but uses member functions rather than manipulators cout.fill('@'); cout.width(20); cout.setf(ios_base::left, ios_base::adjustfield); cout.setf(ios_base::dec, ios_base::basefield); cout << i << endl; // outputs f in scientific notation with // a precision of 10 digits cout << scientific << setprecision(10) << f << endl; // change the precision to 6 digits // equivalents to cout << setprecision(6); cout.precision(6); // output f and goes back to fixed notation cout << f << fixed << endl; } // // cout example two // #include void main ( ) { using namespace std; char p[50]; cin.getline(p,50); cout << p; } // // cout example three // #include #include void main ( ) { using namespace std; // open the file "file_name.txt" // for reading ifstream in("file_name.txt"); // output the all file to stdout if ( in ) cout << in.rdbuf(); else { cout << "Error while opening the file"; cout << endl; } } WARNINGS Keep in mind that the manipulator endl flushes the stream buffer. Therefore it is recommended to use '0 if your only intent is to go at the line. It will greatly improve performance when C and C++ streams are not synchronized. SEE ALSO basic_ostream, iostream, basic_filebuf, cin, cerr, clog, wcin, wcout, wcerr, wclog, iomanip Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.3.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 ctype Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME ctype, ctype - A facet that provides character classification facilities. (The description for ctype, a specialization of ctype, follows the ctype description.) SYNOPSIS #include class ctype_base; template class ctype; SPECIALIZATION class ctype; DESCRIPTION ctype is the character classification facet. This facet provides facilities for classifying characters and performing simple conversions. ctype provides conversions for upper to lower and lower to upper case. The facet also provides conversions between charT, and char. ctype relies on ctype_base for a set of masks that identify the various classes of characters. These classes are: space print cntrl upper lower alpha digit punct xdigit alnum graph The masks are passed to member functions of ctype in order to obtain verify the classifications of a character or range of characters. INTERFACE class ctype_base { public: enum mask { space, print, cntrl, upper, lower, alpha, digit, punct, xdigit, alnum=alpha|digit, graph=alnum|punct }; }; template class ctype : public locale::facet, public ctype_base { public: typedef charT char_type; explicit ctype(size_t); bool is(mask, charT) const; const charT* is(const charT*, const charT*, mask*) const; const charT* scan_is(mask, const charT*, const charT*) const; const charT* scan_not(mask, const charT*, const charT*) const; charT toupper(charT) const; const charT* toupper(charT*, const charT*) const; charT tolower(charT) const; const charT* tolower(charT*, const charT*) const; charT widen(char) const; const char* widen(const char*, const char*, charT*) const; char narrow(charT, char) const; const charT* narrow(const charT*, const charT*, char, char*) const; static locale::id id; protected: ~ctype(); // virtual virtual bool do_is(mask, charT) const; virtual const charT* do_is(const charT*, const charT*, mask*) const; virtual const charT* do_scan_is(mask, const charT*, const charT*) const; virtual const charT* do_scan_not(mask, const charT*, const charT*) const; virtual charT do_toupper(charT) const; virtual const charT* do_toupper(charT*, const charT*) const; virtual charT do_tolower(charT) const; virtual const charT* do_tolower(charT*, const charT*) const; virtual charT do_widen(char) const; virtual const char* do_widen(const char*, const char*, charT*) const; virtual char do_narrow(charT, char) const; virtual const charT* do_narrow(const charT*, const charT*, char, char*) const; }; TYPE char_type Type of character the facet is instantiated on. CONSTRUCTOR AND DESTRUCTOR explicit ctype(size_t refs = 0) Construct a ctype facet. If the refs argument is 0 then destruction of the object is delegated to the locale, or locales, containing it. This allows the user to ignore lifetime management issues. On the other had, if refs is 1 then the object must be explicitly deleted; the locale will not do so. In this case, the object can be maintained across the lifetime of multiple locales. ~ctype(); // virtual and protected Destroy the facet. PUBLIC MEMBER FUNCTIONS The public members of the ctype facet provide an interface to protected members. Each public member xxx has a corresponding virtual protected member do_xxx. All work is delagated to these protected members. For instance, the public widen function simply calls its protected cousin do_widen. bool is(mask m, charT c) const; const charT* is(const charT* low, const charT* high, mask* vec) const; Returns do_is(m,c) or do_is(low,high,vec). char narrow(charT c, char dfault) const; const charT* narrow(const charT* low, const charT*, char dfault, char* to) const; Returns do_narrow(c,dfault) or do_narrow(low,high,dfault,to). const charT* scan_is(mask m, const charT*, const charT* high) const; Returns do_scan_is(m,low,high). const charT* scan_not(mask m, const charT* low, const charT* high) const; Returns do_scan_not(m,low,high). charT tolower(charT c) const; const charT* tolower(charT* low, const charT* high) const; Returns do_tolower(c) or do_tolower(low,high). charT toupper(charT) const; const charT* toupper(charT* low, const charT* high) const; Returns do_toupper(c) or do_toupper(low,high). charT widen(char c) const; const char* widen(const char* low, const char* high, charT* to) const; Returns do_widen(c) or do_widen(low,high,to). FACET ID static locale::id id; Unique identifier for this type of facet. PROTECTED MEMBER FUNCTIONS virtual bool do_is(mask m, charT c) const; Returns true if c matches the classification indicated by the mask m, where m is one of the values available from ctype_base. For instance, the following call returns true since 'a' is an alphabetic character: ctype().is(ctype_base::alpha,'a'); See ctype_base for a description of the masks. virtual const charT* do_is(const charT* low, const charT* high, mask* vec) const; Fills vec with every mask from ctype_base that applies to the range of characters indicated by [low,high). See ctype_base for a description of the masks. For instance, after the following call v would contain {alpha, lower, print,alnum ,graph}: char a[] = "abcde"; ctype_base::mask v[12]; ctype().is(a,a+5,v); This function returns high. virtual char do_narrow(charT, char dfault) const; Returns the appropriate char representation for c, if such exists. Otherwise do_narrow returns dfault. virtual const charT* do_narrow(const charT* low, const charT* high, char dfault, char* dest) const; Converts each character in the range [low,high) to its char representation, if such exists. If a char representation is not available then the character will be converted to dfault. Returns high. virtual const charT* do_scan_is(mask m, const charT* low, const charT* high) const; Finds the first character in the range [low,high) that matches the classification indicated by the mask m. virtual const charT* do_scan_not(mask m, const charT* low, const charT* high) const; Finds the first character in the range [low,high) that does not match the classification indicated by the mask m. virtual charT do_tolower(charT) const; Returns the lower case representation of c, if such exists, otherwise returns c; virtual const charT* do_tolower(charT* low, const charT* high) const; Converts each character in the range [low,high) to its lower case representation, if such exists. If a lower case representation does not exist then the character is not changed. Returns high. virtual charT do_toupper(charT c) const; Returns the upper case representation of c, if such exists, otherwise returns c; virtual const charT* do_toupper(charT* low, const charT* high) const; Converts each character in the range [low,high) to its upper case representation, if such exists. If an upper case representation does not exist then the character is not changed. Returns high. virtual charT do_widen(char c) const; Returns the appropriate charT representation for c. virtual const char* do_widen(const char* low, const char* high,charT* dest) const; Converts each character in the range [low,high) to its charT representation. Returns high. EXAMPLE // // ctype.cpp // #include int main () { using namespace std; locale loc; string s1("blues Power"); // Get a reference to the ctype facet const ctype& ct = #ifndef _RWSTD_NO_TEMPLATE_ON_RETURN_TYPE use_facet >(loc); #else use_facet(loc,(ctype*)0); #endif // Check the classification of the 'a' character cout << ct.is(ctype_base::alpha,'a') << endl; cout << ct.is(ctype_base::punct,'a') << endl; // Scan for the first upper case character cout << (char)*(ct.scan_is(ctype_base::upper, s1.begin(),s1.end())) << endl; // Convert characters to upper case ct.toupper(s1.begin(),s1.end()); cout << s1 << endl; return 0; } SEE ALSO locale, facets, collate, ctype, ctype_byname NAME ctype - A specialization of the ctype facet. SYNOPSIS #include class ctype; DESCRIPTION This specialization of the ctype template provides inline versions of ctype's member functions. The facet provides the same public interface, and uses the same set of masks, as the ctype template. INTERFACE template <> class ctype : public locale::facet, public ctype_base { public: typedef char char_type; explicit ctype(const mask* = 0, bool = false, size_t = 0); bool is(mask, char) const; const charT* is(const char*, const char*, mask*) const; const charT* scan_is(mask, const char*, const char*) const; const charT* scan_not(mask, const char*, const char*) const; charT toupper(char) const; const charT* toupper(char*, const charT*) const; charT tolower(char) const; const charT* tolower(char*, const char*) const; charT widen(char) const; const char* widen(const char*, const char*, char*) const; char narrow(char, char) const; const charT* narrow(const char*, const char*, char, char*) const; static locale::id id; static const size_t table_size = 256; protected: const mask* table() const throw(); static const mask* classic_table() throw(); ~ctype(); // virtual virtual charT do_toupper(charT) const; virtual const charT* do_toupper(charT*, const charT*) const; virtual charT do_tolower(charT) const; virtual const charT* do_tolower(charT*, const charT*) const; }; TYPE char_type Type of character the facet is instantiated on. CONSTRUCTORS AND DESTRUCTORS explicit ctype(const mask* tbl = 0, bool del = false, size_t refs = 0) Construct a ctype facet. The three parameters set up the following conditions: + The tbl argument must be either 0 or an array of at least table_size elements. If tbl is non zero then the supplied table will be used for character classification. + If tbl is non zero, and del is true then the tbl array will be deleted by the destructor, so the calling program need not concern itself with the lifetime of the facet. + If the refs argument is 0 then destruction of the object itself is delegated to the locale, or locales, containing it. This allows the user to ignore lifetime management issues. On the other had, if refs is 1 then the object must be explicitly deleted; the locale will not do so. In this case, the object can be maintained across the lifetime of multiple locales. ~ctype(); // virtual and protected Destroy the facet. If the constructor was called with a non-zero tbl argumentand a true del argument, then the array supplied by the tbl argument will be deleted PUBLIC MEMBER FUNCTIONS The public members of the ctype facet specialization do not all serve the same purpose as the functions in the template. In many cases these functions implement functionality, rather than just forwarding a call to a protected implementation function. static const mask* classic_table() throw(); Returns a pointer to a table_size character array that represents the classifications of characters in the "C" locale. bool is(mask m, charT c) const; Determines if the character c has the classification indicated by the mask m. Returns table()[(unsigned char)c] & m. const charT* is(const charT* low, const charT* high, mask* vec) const; Fills vec with every mask from ctype_base that applies to the range of characters indicated by [low,high). See ctype_base for a description of the masks. For instance, after the following call v would contain {alpha, lower, print,,alnum ,graph}: char a[] = "abcde"; ctype_base::mask v[12]; ctype().do_is(a,a+5,v); This function returns high. char narrow(charT c, char dfault) const; Returns c. const charT* narrow(const charT* low, const charT*, char dfault, char* to) const; Performs ::memcpy(to,low,high-low). Returns high. const charT* scan_is(mask m, const charT*, const charT* high) const; Finds the first character in the range [low,high) that matches the classification indicated by the mask m. The classification is matched by checking for table()[(unsigned char) p] & m, where p is in the range [low,high). Returns the first p that matches, or high if none do. const charT* scan_not(mask m, const charT* low, const charT* high) const; Finds the first character in the range [low,high) that does not match the classification indicated by the mask m. The classification is matched by checking for !(table()[(unsigned char) p] & m), where p is in the range [low,high). Returns the first p that matches, or high if none do. const mask* table() const throw(); If the tbl argument that was passed to the constructor was non-zero, then this function returns that argument, otherwise it returns classic_table(). charT tolower(charT c) const; const charT* tolower(charT* low, const charT* high) const; Returns do_tolower(c) or do_tolower(low,high). charT toupper(charT) const; const charT* toupper(charT* low, const charT* high) const; Returns do_toupper(c) or do_toupper(low,high). charT widen(char c) const; Returns c. const char* widen(const char* low, const char* high, charT* to) const; Performs ::memcpy(to,low,high-low. Returns high. FACET ID static locale::id id; Unique identifier for this type of facet. PROTECTED MEMBER FUNCTIONS virtual charT do_tolower(charT) const; Returns the lower case representation of c, if such exists, otherwise returns c; virtual const charT* do_tolower(charT* low, const charT* high) const; Converts each character in the range [low,high) to its lower case representation, if such exists. If a lower case representation does not exist then the character is not changed. Returns high. virtual charT do_toupper(charT c) const; Returns the upper case representation of c, if such exists, otherwise returns c; virtual const charT* do_toupper(charT* low, const charT* high) const; Converts each character in the range [low,high) to its upper case representation, if such exists. If an upper case representation does not exist then the character is not changed. Returns high. SEE ALSO locale, facets, collate, ctype, ctype_byname STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 filebuf Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_filebuf,filebuf This page describes the ANSI basic_filebuf class. If you would like information on the pre-ANSI filebuf class, use the command: help cxxl SYNOPSIS #include template > class basic_filebuf : public basic_streambuf DESCRIPTION The template class basic_filebuf is derived from basic_streambuf. It associates the input or output sequence with a file. Each object of type basic_filebuf controls two character sequences: + a character input sequence + a character output sequence The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library files. If the file is not open for reading the input sequence cannot be read. If the file is not open for writing the output sequence cannot be written. A joint file position is maintained for both the input and output sequences. A file provides byte sequences. So the basic_filebuf class treats a file as the external source (or sink) byte sequence. In order to provide the contents of a file as wide character sequences, a wide-oriented file buffer called wfilebuf converts wide character sequences to multibytes character sequences (and vice versa) according to the current locale being used in the stream buffer. INTERFACE template > class basic_filebuf : public basic_streambuf { public: typedef traits traits_type; typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; basic_filebuf(); basic_filebuf(int fd); virtual ~basic_filebuf(); bool is_open() const; basic_filebuf* open(const char *s, ios_base::openmode, long protection = 0666); basic_filebuf* open(int fd); basic_filebuf* close(); protected: virtual int showmanyc(); virtual int_type overflow(int_type c = traits::eof()); virtual int_type pbackfail(int_type c = traits::eof()); virtual int_type underflow(); virtual basic_streambuf* setbuf(char_type *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); virtual int sync(); virtual streamsize xsputn(const char_type* s, streamsize n); }; TYPES char_type The type char_type is a synonym for the template parameter charT. filebuf The type filebuf is an instantiation of class basic_filebuf on type char: typedef basic_filebuf filebuf; int_type The type int_type is a synonym of type traits::in_type. off_type The type off_type is a synonym of type traits::off_type. pos_type The type pos_type is a synonym of type traits::pos_type. traits_type The type traits_type is a synonym for the template parameter traits. wfilebuf The type wfilebuf is an instantiation of class basic_filebuf on type wchar_t: typedef basic_filebuf wfilebuf; CONSTRUCTORS basic_filebuf(); Constructs an object of class basic_filebuf, initializing the base class with basic_streambuf(). basic_filebuf(int fd); Constructs an object of class basic_filebuf, initializing the base class with basic_streambuf(), then calls open(fd). This function is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. DESTRUCTOR virtual ~basic_filebuf(); Calls close() and destroys the object. MEMBER FUNCTIONS basic_filebuf* close(); If is_open() == false, returns a null pointer. Otherwise, closes the file, and returns *this. bool is_open() const; Returns true if the associated file is open. basic_filebuf* open(const char* s, ios_base::openmode mode, long protection = 0666); If is_open() == true, returns a null pointer. Otherwise opens the file, whose name is stored in the null-terminated byte-string s. The file open modes are given by their C-equivalent description (see the C func- tion fopen): in "w" in|binary "rb" out "w" out|app "a" out|binary "wb" out|binary|app "ab" out|in "r+" out|in|app "a+" out|in|binary "r+b" out|in|binary|app "a+b" trunc|out "w" trunc|out|binary "wb" trunc|out|in "w+" trunc|out|in|binary "w+b" The third argument, protection, is used as the file permission. It does not appear in the Standard C++ description of the function open and is provided as an extension. It determines the file read/write/execute permissions under UNIX. It is more limited under DOS since files are always readable and do not have special execute permission. If the open function fails, it returns a null pointer. basic_filebuf* open(int fd); Attaches the file previously opened and identified by its file descriptor fd, to the basic_filebuf object. This function is not described in the C++ standard, and is provided as an extension in order to manipulate pipes, sockets or other UNIX devices, that can be accessed through file descriptors. int_type overflow(int_type c = traits::eof() ); If the output sequence has a put position available, and c is not traits::eof(), then write c into it. If there is no position available, the function output the content of the buffer to the associated file and then write c at the new current put position. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). In wide characters file buffer, overflow converts the internal wide characters to their external multibytes representation by using the locale::codecvt facet located in the locale object imbued in the stream buffer. int_type pbackfail(int_type c = traits::eof() ); Puts back the character designated by c into the input sequence. If traits::eq_int_type(c,traits::eof()) returns true, move the input sequence one position backward. If the operation fails, the function returns traits::eof(). Otherwise it returns traits::not_eof(c). pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, alters the stream position of both the input and the output sequence. If the open mode is in, alters the stream position of only the input sequence, and if it is out, alters the stream position of only the output sequence. The new position is calculated by combining the two parameters off (displacement) and way (reference point). If the current position of the sequence is invalid before repo- sitioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. File buffers using locale::codecvt facet performing state dependent conversion, only support seeking to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions. pos_type seekpos(pos_type sp,ios_base::openmode which = ios_base::in | ios_base::out); If the open mode is in | out, alters the stream position of both the input and the output sequence. If the open mode is in, alters the stream position of only the input sequence, and if it is out, alters the stream position of only the output sequence. If the current position of the sequence is invalid before repositioning, the operation fails and the return value is pos_type(off_type(-1)). Otherwise the function returns the current new position. File buffers using locale::codecvt facet performing state dependent conversion, only support seeking to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions. basic_filebuf* setbuf(char_type*s, streamsize n); If s is not a null pointer, output the content of the current buffer to the associated file, then delete the current buffer and replace it by s. Otherwise resize the current buffer to size n after outputting its content to the associated file if necessary. int sync(); Synchronizes the content of the external file, with its image maintained in memory by the file buffer. If the function fails, it returns -1, otherwise it returns 0. int_type underflow(); If the input sequence has a read position available, returns the content of this position. Otherwise fills up the buffer by reading characters from the associated file and if it succeeds, returns the content of the new current position. The function returns traits::eof() to indicate failure. In wide characters file buffer, underflow converts the external mutltibytes characters to their wide character representation by using the locale::codecvt facet located in the locale object imbued in the stream buffer. streamsize xsputn(const char_type* s, streamsize n); Writes up to n characters to the output sequence. The characters written are obtained from successive elements of the array whose first element is designated by s. The function returns the number of characters written. EXAMPLES // // stdlib/examples/manual/filebuf.cpp // #include #include void main ( ) { using namespace std; // create a read/write file-stream object on tiny char // and attach it to the file "filebuf.out" ofstream out("filebuf.out",ios_base::in | ios_base::out); // tie the istream object to the ofstream object istream in(out.rdbuf()); // output to out out << "Il errait comme un ame en peine"; // seek to the beginning of the file in.seekg(0); // output in to the standard output cout << in.rdbuf() << endl; // close the file "filebuf.out" out.close(); // open the existing file "filebuf.out" // and truncate it out.open("filebuf.out",ios_base::in | ios_base::out | ios_base::trunc); // set the buffer size out.rdbuf()->pubsetbuf(0,4096); // open the source code file ifstream ins("filebuf.cpp"); //output it to filebuf.out out << ins.rdbuf(); // seek to the beginning of the file out.seekp(0); // output the all file to the standard output cout << out.rdbuf(); } SEE ALSO char_traits, ios_base, basic_ios, basic_streambuf, basic_ifstream, basic_ofstream, basic_fstream Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.8.1.1 STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 fpos Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME fpos SYNOPSIS #include template class fpos DESCRIPTION The template class fpos is used by the iostream classes to maintain positioning information. It maintains three kinds of information: the absolute position, the conversion state and the validity of the stored position. Streams instantiated on tiny characters use streampos as their positioning type, whereas streams instantiated on wide characters use wstreampos, but both are defined as fpos. INTERFACE template class fpos { public: typedef stateT state_type; fpos(long off = 0); fpos(state_type); state_type state(state_type); state_type state () const; }; TYPES state_type The type state_type holds the conversion state, and is compatible with the function locale::codecvt(). By default it is defined as mbstate_t. PUBLIC CONSTRUCTORS fpos(long off =0); Constructs an fpos object, initializing its position with off and its conversion state with the default stateT constructor. This function is not described in the C++ standard. fpos(state_type st); Construct an fpos object, initializing its conversion state with st, its position with the start position, and its status to good. PUBLIC MEMBER FUNCTIONS state_type state() const; Returns the conversion state stored in the fpos object. state_type state(state_type st); Store st as the new conversion state in the fpos object and return its previous value. VALID OPERATIONS In the following, + P refers to type fpos + p and q refer to an value of type fpos + O refers to the offset type ( streamoff, wstreamoff, long _) + o refers to a value of the offset type + i refers to a value of type int Valid operations: P p( i ); Constructs from int. P p = i; Assigns from int. P( o ) Converts from offset. O( p ) Converts to offset. p == q Tests for equality. p != q Tests for inequality. q = p + o Adds offset. p += o Adds offset. q = p -o Subtracts offset. q -= o Subtracts offset. o = p - q Returns offset. SEE ALSO iosfwd, char_traits Working Paper for Draft Proposed International Standard for Information Systems--Programming Language C++, Section 27.4. Amendment 1 to the C Standard. STANDARDS CONFORMANCE ANSI X3J16/ISO WG21 Joint C++ Committee 3 fstream Standard C++ Library Copyright 1996, Rogue Wave Software, Inc. NAME basic_fstream,fstream,ofstream This page describes the ANSI basic_fstream class. If you would like information on the pre-ANSI fstream class, use the command: help cxxl SYNOPSIS #include