═══ 1. About this Online Reference ═══ This reference describes the classes and class members that are included in IBM Open Class Library. Notices Trade/Service Marks What is IBM Open Class? About Examples Using this Book Contextual Help Finding Descriptions Using the TOC Getting More Information Action Bar Choices Cutting and Pasting Other Helpful Information Sending Comments to IBM ═══ 1.1. Notices ═══ Copyright International Business Machines Corporation, 1992, 1995. All rights reserved. Note to U.S. Government Users - Documentation related to restricted rights - Use, duplication, or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp. First Edition, May 1995 This edition applies to Version 3.0 of IBM VisualAge C ++ for OS/2 ( 30H1664, 30H1665, 30H1666) and to all subsequent releases and modifications until otherwise indicated in new editions. Make sure you are using the correct edition for the level of the product. This publication could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; any such changes will be reported in subsequent revisions. Requests for publications and for technical information about IBM products should be made to your IBM Authorized Dealer or your IBM Marketing Representative. When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in any ways it believes appropriate without incurring any obligation to you. Any reference to an IBM licensed program in this publication is not intended to state or imply that only IBM's licensed program may be used. Any functionally equivalent product, program, or service that does not infringe any of IBM's intellectual property rights may be used instead of the IBM product, program, or service. Evaluation and verification of operation in conjunction with other products, except those expressly designated by IBM, is the user's responsibility. IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to the IBM Director of Licensing, IBM Corporation, 500 Columbus Avenue, Thornwood, NY, 10594, USA. ═══ 1.2. Trademarks and Service Marks ═══ The following terms used in this publication are trademarks or service marks of IBM Corporation in the United States or other countries: AIX BookManager C/2 C Set/2 C Set ++ Common User Access CUA IBM Open Class Operating System/2 OS/2 Personal System/2 Presentation Manager PS/2 VisualAge WorkFrame Windows is a trademark of Microsoft Corporation. UNIX is a registered trademark in the United States and other countries licensed exclusively through X/Open Company Limited. Other company, product, and service names, which may be denoted by a double asterisk(**), may be trademarks or service marks of others. ═══ 1.3. What is IBM Open Class Library? ═══ IBM Open Class Library (or IBM Open Class) consists of classes in the following categories:  Complex Mathematics  I/O Streams  Collections  Data Types  Exceptions  Database Access Builder  User Interface, including the following: - Windows, Menus, Handlers, and Events - Advanced Controls, Dialogs, and their Handlers - Direct Manipulation Classes - Dynamic Data Exchange (DDE) Classes - 2-Dimensional Graphic Classes - Multimedia Classes This book is intended for skilled C++ programmers who understand the concept of classes and who are familiar with using C++ templates when working with individual class libraries. Use this book if you want to do any of the following in your C++ programs:  Manipulate complex numbers (numbers with both a real and an imaginary part)  Perform input and output to console or files using a typesafe, object-oriented programming approach  Implement commonly used abstract data types, including sets, maps, sequences, trees, stacks, queues, and sorted or keyed collections  Manipulate strings with greater ease and flexibility than the standard C++ method of using character pointers and the string functions of the C string.h library  Use date and time information and apply member functions to date and time objects  Use Data Access Builder generated source code in conjunction with the Data Access Builder class library to access a DB2/2 relational database.  Simplify the development of portable applications containing graphical user interfaces (GUI).  Simulate Common User Access (CUA) workplace look and feel and take advantage of Presentation Manager features. Before you begin to use this information, it would be helpful to understand how to navigate through it. You can use the Table of Contents and Index facility to locate topics and the Search facility to search the text of this document. You can use hypertext links to acquire related information on the current topic. Hypertext links appear in a different color (which you can customize using the OS/2 Scheme Palette). For example, here is a link to another panel: Communicating Your Comments to IBM. By double-clicking on the text of the link or by pressing Enter on a highlighted link, you will open a panel of related information. When you open a panel, the first link has the focus; to shift the focus to other links, use the Tab key. You should also understand:  How to Use the Contents  How to Obtain Additional Information  How to Use Action Bar Choices  How to Cut and Paste Examples ═══ 1.4. A Note about Examples ═══ The examples in this book explain elements of the C++ class libraries. They are coded in a simple style. They do not try to conserve storage, check for errors, achieve fast run times, or demonstrate all possible uses of a library, class, or member function. Source Files for Samples This online reference contains links to the runnable sample programs that are shipped as separate files with IBM Open Class. There can be up to five links for each member function. Functions with multiple overloads may have links to the samples for each overload. When you select a sample, the sample is loaded into the editor defined in your WorkFrame profile at the function's line and column. Collection Class Library samples are included in this online document as well. All of these sample source files are located in the following directory: \ibmcpp\samples\ioc Examples are code excerpts or runnable programs that are not shipped as separate files with IBM Open Class; they exist only in this reference. ═══ 1.5. How to Use the Features of this Book ═══ The IBM Open Class Library classes are grouped into major categories. These groups comprise the majority of this document. You can use this information as a guide when choosing classes. You can quickly locate and learn more about any class using the alphabetical reference in Classes by Name. The header file on many class description panels is a link that brings up your WorkFrame editor and loads the appropriate .HPP file. You can link to the .HPP for all classes from the Class to Header File Cross-Reference found at the end of this book. Also in this book, classes, member functions, and enumerations might have the following sections: Portability Considerations Motif Information Presentation Manager Information These sections contain information that is specific to a particular platform or suggestions for developing portable applications. Note that some members have a Platform Support Table. If a member function is overloaded, one overload might have one condition, while a second overload has a different condition. For example, in IBaseSpinButton::initialize, one implementation is for both AIX and OS/2, while another implementation is for OS/2 only. This table lists each platform in the heading and the table entries explain if the function is supported, not supported, or silently ignored. ═══ 1.6. The Contextual Help Feature ═══ IBM Open Class provides contextual help for each class and member function. To access contextual help:  Install the CPP*.INF and CPP.NDX and CPPBRS.NDX files  Use the VisualAge Editor or the Enhanced System Editor provided by OS/2 Access contextual help by positioning the cursor over the name of a class or member function in the text you are editing, and then pressing Ctrl-H. This opens the online version of the IBM Open Class Library Reference and displays information about that class or member function. Refer to the product installation instructions for complete details on setting the environment variables needed to use the contextual help feature. ═══ 1.7. How to Find Class or Function Descriptions ═══ You can use this online reference to find individual class or member function documentation. If you know what library or group a class is in, expand the table of contents entry for that library or group, and select the class from there. When you select a class entry from the table of contents, the lefthand panel contains a list of hypertext links including one for member functions. Select that link and a list of member functions is displayed. You can then select the member function you want information on. You can also search on a member function name, or on a fully qualified name: Class::function. For flat collections, search only on the function name if you want information on a particular function; the Class::function syntax will not work for these functions. You can also use the Source Code Browser or an editor to find information on any function, if you use the CPPBRS.NDX help index file. ═══ 1.8. How to Use the Contents ═══ When the Contents window first appears, some topics have a plus (+) sign beside them. The plus sign indicates that additional topics are available. To expand the Contents if you are using a mouse, click on the plus sign. If you are using the keyboard, use the Up or Down Arrow key to highlight the topic, and press the plus (+) key. For example, How to Use the Contents has a plus sign beside it. To see additional topics for that heading, click on the plus sign or highlight that topic and press the plus (+) key. To view a topic, double-click on the topic (or press the Up or Down Arrow key to highlight the topic, and then press the Enter key). ═══ 1.9. How to Obtain Additional Information ═══ After you select a topic, the information for that topic appears in a window. Highlighted words or phrases indicate that additional information is available. Certain words and phrases are highlighted in a different color from the surrounding text. These are called hypertext terms. If you are using a mouse, double-click on the highlighted word. If you are using a keyboard, press the Tab key to move to the highlighted word, and then press the Enter key. Additional information then appears in a window. ═══ 1.10. How to Use Action Bar Choices ═══ Several choices are available for managing the information presented in this document. There are three menus on the action bar: the Services menu, the Options menu, and the Help menu. The actions that are selectable from the Services menu operate on the active window currently displayed on the screen. These actions include the following: Placing Bookmarks You can set a placeholder so you can retrieve information of interest to you. Searching for Information You can find occurrences of a word or phrase in the current topic, selected topics, or all topics. Printing Information You can print one or more topics. You can also print a set of topics by first marking the topics in the Contents list. Copying Information to a File You can copy a topic that you are viewing to the System Clipboard or to a file that you can edit. This method is particularly useful for copying syntax definitions and program samples into the application that you are developing. Using the actions that are selectable from the Options menu, you can change the way your Contents list is displayed. To expand the Contents and show all levels for all topics, choose Expand all from the Options pull-down. You can also press the Ctrl and * keys together. The actions that are selectable from the Help menu allow you to select different types of help information. For information about any of the menu choices, highlight the choice in the menu and press F1. ═══ 1.10.1. Placing Bookmarks ═══ When you place a bookmark on a topic, it is added to a list of bookmarks you have previously set. You can view the list, and you can remove one or all bookmarks from the list. If you have not set any bookmarks, the list is empty. To set a bookmark, do the following: 1. Select a topic from the Contents. 2. When that topic appears, select the Bookmark option from the Services menu. 3. If you want to change the name used for the bookmark, type the new name in the field. 4. Click on the Place radio button (or press the Up or Down Arrow key to select it). 5. Click on OK (or select it and press Enter). The bookmark is then added to the bookmark list. ═══ 1.10.2. Searching for Information ═══ You can specify a word or phrase to be searched. You can also limit the search to a set of topics by first marking the topics in the Contents list. To search for a word or phrase in all topics, do the following: 1. Select the Search option from the Services menu. 2. Type the word or words to be searched for. 3. Click on All sections (or press the Up or Down Arrow keys to select it). 4. Click on Search (or select it and press Enter) to begin the search. 5. The list of topics where the word or phrase appears is displayed. ═══ 1.10.3. Printing Information ═══ You can print one or more topics, the index, or the table of contents. Make sure that your printer is connected to the serial port, configured correctly, and ready for input. To print: 1. Select Print from the Services pull-down. 2. Select what you want to print. Note that the This section and Marked sections choices are only available if you are viewing a topic or if you have marked topics, respectively. To mark topics in the table of contents, press the Ctrl key and click on the topics, or use the arrow keys. 3. Select Print to print what you've chosen on your printer. ═══ 1.10.4. Copying Information to a File ═══ You can copy a topic that you are viewing in two ways:  Copy copies the topic that you are viewing into the System Clipboard. If you are using a Presentation Manager (PM) editor (for example, the Enhanced Editor) that copies or cuts (or both) to the System Clipboard, and pastes to the System Clipboard, you can easily add the copied information to your program source module.  Copy to file copies the topic that you are viewing into a temporary file named TEXT.TMP. You can later edit that file by using any editor. TEXT.TMP is placed in the directory where your viewable document resides. To copy a topic, do the following: 1. Expand the Contents list and select a topic. 2. When the topic appears, select Copy to file from the Services menu. 3. The system puts the text pertaining to that topic into the temporary file TEXT.TMP. ═══ 1.11. How to Cut and Paste Examples ═══ You can copy examples (or information) from this reference/guide/book to compile, link, and run them, or to paste them into your own code. To copy an example or information: 1. Make the topic you want to copy the active window. 2. From the Services menu, select Copy to file. The text in that topic is placed in the temporary file TEXT.TMP, in the same directory as this reference. 3. You can then modify or use TEXT.TMP as you want. Note: Because the system copies the entire contents of the topic to the file, you may need to edit it to remove additional text. Examples in this reference that have a main function are ready to compile, link, and run as they appear, and do not require any editing. ═══ 1.12. Other Information You Might Find Helpful ═══ This product provides a number of online guides and references that we hope you'll find helpful as you develop applications. This information includes User's Guides, References, and How Do I help that gives you specific instructions for performing common tasks. You can get to this online information from the Information folder inside the main product folder. You can also get to it from the Help menu in any of the components of the product. ═══ 1.13. Communicating Your Comments to IBM ═══ If there is something you like, or dislike, about this book, please let us know. You can use one of the methods listed below to send your comments to IBM. Please be sure to include the complete title of the publication that you are commenting on. The comments you send should only pertain to the information in this document and its presentation. To request additional publications or to ask questions or make comments about the functions of IBM products or systems, you should talk to your IBM representative or you authorized IBM remarketer. When you send comments to IBM, you grant IBM a nonexclusive right to use or distribute your comments in any way it believes appropriate without incurring any obligation to you. You can send your comments to IBM in the following ways:  By mail to the following address: IBM Canada Ltd. Laboratory Information Development 2G/345/1150/TOR 1150 EGLINTON AVENUE EAST NORTH YORK, ONTARIO CANADA M3C 1H7  By FAX to the following number: - United States and Canada: (416) 448-6161 - Other countries (+1) 416-448-6161  By electronic mail to one of the following IDs. Be sure to include your entire network address if you wish to get a reply. - Internet: torrcf@vnet.ibm.com - IBMLink: toribm(torrcf) - IBM/PROFS: torolab4(torrcf) - IBMMAIL: ibmmail(caibmwt9 ═══ 2. Classes by Name ═══ I0String I3StateCheckBox::Style I3StateCheckBox IAccelTblHandle IAccelerator IAccessError IAnchorBlockHandle IAnimatedButton::Style IAnimatedButton IApplication IAssertionFailure IAutoElemPointer IAutoPointer Bag IBase::Version IBase IBaseComboBox::Cursor IBaseComboBox::Style IBaseComboBox IBaseListBox::Cursor IBaseListBox::Style IBaseListBox IBaseSpinButton::Style IBaseSpinButton IBitFlag IBitmapControl::Style IBitmapControl IBitmapHandle IBuffer IButton::Style IButton IButtonNotifyHandler c_exception ICLibErrorInfo ICanvas::Style ICanvas ICheckBox::Style ICheckBox ICircularSlider::Style ICircularSlider ICircularSliderNotifyHandler IClipboard::Cursor IClipboard IClipboardHandler ICnrAllocator ICnrBeginEditEvent ICnrControlList ICnrDrawBackgroundEvent ICnrDrawHandler ICnrDrawItemEvent ICnrEditEvent ICnrEditHandler ICnrEmphasisEvent ICnrEndEditEvent ICnrEnterEvent ICnrEvent ICnrHandler ICnrHelpEvent ICnrMenuHandler ICnrObjectSet ICnrQueryDeltaEvent ICnrReallocStringEvent ICnrScrollEvent Collection ICollectionViewComboBox ICollectionViewConstants ICollectionViewListBox IColor IComboBox::Style IComboBox IComboBoxNotifyHandler ICommandEvent ICommandHandler complex Constant Iterator IContainerColumn IContainerControl::Attribute IContainerControl::ColumnCursor IContainerControl::CompareFn IContainerControl::FilterFn IContainerControl::Iterator IContainerControl::ObjectCursor IContainerControl::Style IContainerControl::TextCursor IContainerControl IContainerControlNotifyHandler IContainerObject IContextHandle IControl::Style IControl IControlEvent ICoordinateSystem ICritSec ICurrentApplication ICurrentThread Cursor ICustomButton::Style ICustomButton ICustomButtonDrawEvent ICustomButtonDrawHandler IDBCSBuffer IDDE IDDEAcknowledgeEvent IDDEAcknowledgeExecuteEvent IDDEAcknowledgePokeEvent IDDEActiveServer IDDEActiveServerSet IDDEBeginEvent IDDEClientAcknowledgeEvent IDDEClientConversation IDDEClientEndEvent IDDEClientHotLinkEvent IDDEClientHotLinkSet IDDEDataEvent IDDEEndEvent IDDEEvent IDDEExecuteEvent IDDEPokeEvent IDDERequestDataEvent IDDEServerAcknowledgeEvent IDDEServerHotLinkEvent IDDESetAcknowledgeInfoEvent IDDETopicServer IDM IDMCnrItem IDMEFItem IDMEvent IDMHandler IDMImage::Style IDMImage IDMItem IDMItemProvider IDMItemProviderFor IDMMLEItem IDMMenuItem IDMOperation IDMRenderer IDMSourceBeginEvent IDMSourceDiscardEvent IDMSourceEndEvent IDMSourceHandler IDMSourceOperation IDMSourcePrepareEvent IDMSourcePrintEvent IDMSourceRenderEvent IDMSourceRenderer IDMTBarButtonItem IDMTargetDropEvent IDMTargetEndEvent IDMTargetEnterEvent IDMTargetEvent IDMTargetHandler IDMTargetHelpEvent IDMTargetLeaveEvent IDMTargetOperation IDMTargetRenderer IDMToolBarItem IDate Deque IDeviceColor IDeviceError IDisplayHandle IDrawItemEvent IDrawingCanvas::Style IDrawingCanvas IDynamicLinkLibrary IEditHandler IElemPointer IEntryField::Style IEntryField IEntryFieldNotifyHandler IEnumHandle Equality Collection Equality Key Collection Equality Key Sorted Collection Equality Sequence Equality Sorted Collection IErrorInfo IEvent IEventData IEventParameter1 IEventParameter2 IEventResult IException::TraceFn IException IExceptionLocation filebuf IFileDialog::Settings IFileDialog::Style IFileDialog IFileDialogEvent IFileDialogHandler IFlyOverHelpHandler IFlyText IFocusHandler IFont::FaceNameCursor IFont::PointSizeCursor IFont IFontDialog::Settings IFontDialog::Style IFontDialog IFontDialogHandler IFrameEvent IFrameExtension IFrameExtensions IFrameFormatEvent IFrameHandler IFrameWindow::Style IFrameWindow IFrameWindowNotifyHandler fstream fstreambase IG3PointArc IGArc IGBitmap IGChord IGEllipse IGLine IGList::Cursor IGList IGPie IGPolygon IGPolyline IGRectangle IGRegion IGString IGUIColor IGUIErrorInfo IGraphic IGraphicBundle IGraphicContext IGraphicPushButton::Style IGraphicPushButton IGroupBox::Style IGroupBox IHandle IHandler Heap IHelpErrorEvent IHelpHandler IHelpHyperlinkEvent IHelpMenuBarEvent IHelpNotifyEvent IHelpSubitemNotFoundEvent IHelpTutorialEvent IHelpWindow::Settings IHelpWindow IHighEventParameter IIconControl::Style IIconControl ifstream IInfoArea IInvalidParameter IInvalidRequest ios iostream iostream_withassign istream istream_withassign istrstream Iterator Key Bag Key Collection Key Set Key Sorted Bag Key Sorted Collection Key Sorted Set IKeyboardEvent IKeyboardHandler IListBox::Style IListBox IListBoxDrawItemEvent IListBoxDrawItemHandler IListBoxNotifyHandler IListBoxSizeItemEvent ILowEventParameter IMM24FramesPerSecondTime IMM25FramesPerSecondTime IMM30FramesPerSecondTime IMMAmpMixer IMMAudioBuffer IMMAudioCD IMMAudioCDContents::Cursor IMMAudioCDContents IMMCDXA IMMConfigurableAudio IMMCuePointEvent IMMDevice IMMDeviceEvent IMMDeviceHandler IMMDigitalVideo IMMErrorInfo IMMFileMedia IMMHourMinSecFrameTime IMMHourMinSecTime IMMMasterAudio IMMMillisecondTime IMMMinSecFrameTime IMMNotifyEvent IMMPassDeviceEvent IMMPlayableDevice IMMPlayerPanel IMMPlayerPanelHandler IMMPositionChangeEvent IMMRecordable IMMRemovableMedia IMMRemovableMediaHandler IMMSequencer IMMSpeed IMMTime IMMTrackMinSecFrameTime IMMWaveAudio Manipulators Map IMenu::Cursor IMenu::Style IMenu IMenuBar::Style IMenuBar IMenuDrawItemEvent IMenuDrawItemHandler::DrawFlag IMenuDrawItemHandler IMenuEvent IMenuHandle IMenuHandler IMenuItem::Attribute IMenuItem::Style IMenuItem IMenuNotifyHandler IMessageBox::Style IMessageBox IMessageQueueHandle IMessageText IMngElemPointer IMngPointer IModuleHandle IMouseClickEvent IMouseEvent IMouseHandler IMousePointerEvent IMousePointerHandler IMultiCellCanvas::Style IMultiCellCanvas IMultiLineEdit::Style IMultiLineEdit IMultiLineEditNotifyHandler INotebook::Cursor INotebook::PageSettings::Attribute INotebook::PageSettings INotebook::Style INotebook INotebookDrawItemEvent INotebookNotifyHandler INotificationEvent INotifier INumericSpinButton::Style INumericSpinButton INumericSpinButtonNotifyHandler IObjectWindow IObserver IObserverList::Cursor IObserverList ofstream Ordered Collection ostream ostream_withassign ostrstream IOutOfMemory IOutOfSystemResource IOutOfWindowResource IOutlineBox::Style IOutlineBox IPageEvent IPageHandle IPageHandler IPageHelpEvent IPageRemoveEvent IPageSelectEvent IPaintEvent IPaintHandler IPair IPoint IPointArray Pointer Classes IPointerHandle IPopUpMenu IPresSpaceHandle Priority Queue IPrivateResource IProcedureAddress IProcessId IProfile::Cursor IProfile IProfileHandle IProgressIndicator::Style IProgressIndicator IProgressIndicatorNotifyHandler IPushButton::Style IPushButton Queue IRadioButton::Style IRadioButton IRange IRectangle IRefCounted IReference IRegionHandle Relation IResizeEvent IResizeHandler IResource IResourceExhausted IResourceId IResourceLibrary IResourceLock ISWP ISWPArray IScrollBar::Style IScrollBar IScrollBarNotifyHandler IScrollEvent IScrollHandler ISelectHandler ISemaphoreHandle Sequence Sequential Collection Set ISetCanvas::Style ISetCanvas ISettingButton ISettingButtonNotifyHandler ISharedResource IShowListHandler ISize ISlider::Style ISlider ISliderArmHandler ISliderDrawHandler Sorted Bag Sorted Collection Sorted Map Sorted Relation Sorted Set ISpinHandler ISplitCanvas::Style ISplitCanvas Stack IStandardNotifier IStaticText::Style IStaticText stdiobuf stdiostream streambuf IString IStringEnum IStringGenerator IStringGeneratorFn IStringGeneratorMemberFn IStringGeneratorRefMemberFn IStringHandle IStringParser::SkipWords IStringParser IStringTest IStringTestMemberFn strstream strstreambase strstreambuf ISubmenu::Cursor ISubmenu ISystemBitmapHandle ISystemErrorInfo ISystemMenu ISystemPointerHandle ITextControl ITextControlNotifyHandler ITextSpinButton::Cursor ITextSpinButton::Style ITextSpinButton ITextSpinButtonNotifyHandler IThread::Cursor IThread IThreadFn IThreadId IThreadMemberFn ITime ITimer::Cursor ITimer ITimerFn ITimerMemberFn0 ITimerMemberFn ITitle ITitleNotifyHandler IToolBar::FrameCursor IToolBar::Style IToolBar::WindowCursor IToolBar IToolBarButton::Style IToolBarButton IToolBarContainer::Style IToolBarContainer IToolBarFrameWindow ITrace ITransformMatrix Tree Tree Cursor IVBase IViewPort::Style IViewPort IWindow::BidiSettings IWindow::ChildCursor IWindow::ExceptionFn IWindow::Style IWindow IWindowHandle IWindowNotifyHandler IXLibErrorInfo ═══ 3. Complex Mathematics Classes ═══ The Complex Mathematics Library contains two classes: complex Class The class you can use to manipulate complex numbers. c_exception Class The class that provides runtime error-handling facilities for the functions and operations in the complex class. ═══ 3.1. complex Class ═══ Description Derivation Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 3.1.1. Class Description - complex ═══ This chapter describes the member functions of the complex class, the class that provides you with the facilities to manipulate complex numbers. ═══ Derivation ═══ complex does not derive from any class. ═══ Header File ═══ complex is declared in complex.h ═══ Members ═══ The following members are provided for complex:  Constructors for complex  Addition  Mathematical Assignment Operators  Inequality  Multiplication  Negation  Subtraction  Division  Input Operator  Output Operator  Equality  abs  arg  conj  cos  cosh  exp  imag  log  norm  polar  pow  real  sin  sinh  sqrt complex also defines a set of mathematical constants. ═══ 3.1.2. Constants Defined in complex.h ═══ The following table lists the mathematical constants that the Complex Mathematics Library defines (if they have not been previously defined): ┌─────────────────────────────────────────────────────────────────┐ │ Table 1. Constants Defined in complex.h │ ├──────────────────────────┬──────────────────────────────────────┤ │ CONSTANT NAME │ DESCRIPTION │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_E │ The constant e │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_LOG2E │ The logarithm of e to the base of 2 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_LOG10E │ The logarithm of e to the base of 10 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_LN2 │ The natural logarithm of 2 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_LN10 │ The natural logarithm of 10 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_PI │ pi │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_PI_2 │ pi / 2 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_PI_4 │ pi / 4 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_1_PI │ 1 / pi │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_2_PI │ 2 / pi │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_2_SQRTPI │ 2 divided by the square root of pi │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_SQRT2 │ The square root of 2 │ ├──────────────────────────┼──────────────────────────────────────┤ │ M_SQRT1_2 │ The square root of 1 / 2 │ └──────────────────────────┴──────────────────────────────────────┘ ═══ 3.1.3. Constructors for complex ═══ See also Initializing complex Arrays (next panel). There are two versions of the complex constructor: complex(); complex(double r, double i=0.0); If you declare a complex object without specifying any values for the real or imaginary part of the complex value, the constructor that takes no arguments is used and the complex value is initialized to (0, 0). For example, the following declaration gives the object comp the value (0, 0): complex comp; If you give either one or two values in your declaration, the constructor that takes two arguments is used. If you only give one value, the real part of the complex object is initialized to that value, and the imaginary part is initialized to 0. For example, the following declaration gives the object comp2 the value (3.14, 0): complex comp2(3.14); If you give two values in the declaration, the real part of the complex object is initialized to the first value and the imaginary part is initialized to the second value. For example, the following declaration gives the object comp3 the value (3.14, 6.44): complex comp3(3.14, 6.44); There is no explicit complex destructor. ═══ 3.1.3.1. Initializing complex Arrays ═══ You can use the complex constructor to initialize arrays of complex numbers. If the list of initial values is made up of complex values, each array element is initialized to the corresponding value in the list of initial values. If the list of initial values is not made up of complex values, the real parts of the array elements are initialized to these initial values and the imaginary parts of the array elements are initialized to 0. In the following example, the elements of array b are initialized to the values in the initial value list, but only the real parts of elements of array a are initialized to the values in the initial value list. #include void main() { complex a[3] = {1.0, 2.0, 3.0}; complex b[3] = {complex(1.0, 1.0), complex(2.0, 2.0), complex(3.0, 3.0)}; cout << "Here is the first element of a: " << a[0] << endl; cout << "Here is the first element of b: " << b[0] << endl; } This example produces the following output: Here is the first element of a: ( 1, 0) Here is the first element of b: ( 1, 1) ═══ 3.1.4. Mathematical Operators for complex ═══ The complex operators described in this section have the same precedence as the corresponding real operators. The following operators are described:  Addition operator  Subtraction operator  Negation operator  Multiplication operator  Division operator  Equality operator  Inequality operator  Mathematical assignment operators ═══ 3.1.4.1. Addition ═══ friend complex operator+(complex x, complex y); The addition operator returns the sum of x and y. ═══ 3.1.4.2. Subtraction ═══ friend complex operator-(complex x, complex y); The subtraction operator returns the difference between x and y. ═══ 3.1.4.3. Negation ═══ friend complex operator-(complex x); The negation operator returns (- a, - b) when its argument is (a, b). ═══ 3.1.4.4. Multiplication ═══ friend complex operator*(complex x, complex y); The multiplication operator returns the product of x and y. ═══ 3.1.4.5. Division ═══ friend complex operator/(complex x, complex y); The division operator returns the quotient of x divided by y. ═══ 3.1.4.6. Equality ═══ friend int operator==(complex x, complex y); The equality operator "==" returns a nonzero value if x equals y. This operator tests for equality by testing that the two real components are equal and that the two imaginary components are equal. Because both components are double values, the equality operator tests for an exact match between the two sets of values. If you want an equality operator that can test for an absolute difference within a certain tolerance between the two pairs of corresponding components, you can use a function such as the isequal function. ═══ 3.1.4.7. Inequality ═══ friend int operator!=(complex x, complex y); The inequality operator "! =" returns a nonzero value if x does not equal y. This operator tests for inequality by testing that the two real components are not equal and that the two imaginary components are not equal. Because both components are double values, the inequality operator returns false only when both the real and imaginary components of the two values are identical. If you want an inequality operator that can test for an absolute difference within a certain tolerance between the two pairs of corresponding components, you can use a function such as the is_not_equal function. ═══ 3.1.4.8. Mathematical Assignment Operators ═══ void operator+=(complex x); void operator-=(complex x); void operator*=(complex x); void operator/=(complex x); The following list describes the functions of the mathematical assignment operators:  x += y assigns the value of x + y to x.  x -= y assigns the value of x - y to x.  x *= y assigns the value of x * y to x.  x /= y assigns the value of x / y to x. Note: The assignment operators do not produce a value that can be used in an expression. The following code, for example, produces a compile-time error: complex x, y, z; // valid declaration x = (y += z); // invalid assignment causes a // compile-time error y += z; // correct method involves splitting x = y; // expression into separate statements ═══ 3.1.5. Input and Output Operators for complex ═══ The following topics are described:  The input operator  The output operator. You can also view the Open Class Library User's Guide section on complex input and output operators for an example of using them. ═══ 3.1.5.1. Input Operator ═══ istream& operator>>(istream& is, complex& c); The input (or extraction) operator >> takes complex value c from the stream is in the form (a,b). The parentheses and comma are mandatory delimiters for input when the imaginary part of the complex number being read is nonzero. Otherwise, they are optional. In both cases, white space is optional. ═══ 3.1.5.2. Output Operator ═══ ostream& operator<<(ostream& os, complex c); The output (or insertion) operator << writes complex value c to the stream os in the form (a,b). ═══ 3.1.6. Mathematical Functions for complex ═══ The following mathematical functions are described:  exp - Exponent  log - Logarithm  pow - Power  sqrt - Square Root You can also the Open Class Library User's Guide information on the complex mathematical functions for an example of using them. ═══ 3.1.6.1. exp ═══ friend complex exp(complex x); exp() returns the complex value equal to e to the power of x where x is the argument. Results of the Default Error-Handling Procedures shows the values returned by the default error-handling procedure for exp(). ═══ 3.1.6.2. log ═══ friend complex log(complex x); log() returns the natural logarithm of the argument x. Results of the Default Error-Handling Procedures shows the values returned by the default error-handling procedure for log(). ═══ 3.1.6.3. pow ═══ friend complex pow(double d, complex z); friend complex pow(complex c, int i); friend complex pow(complex c, double d); friend complex pow(complex c, complex z); Note: Exponents in the following text are shown in square brackets. pow() returns the complex value x[y], where x is the first argument and y is the second argument. pow() is overloaded four times. If d is a double value, i is an integer value, and c and z are complex values, then pow() can produce any of the following results:  d[z]  c[i]  c[d]  c[z] ═══ 3.1.6.4. sqrt ═══ friend complex sqrt(complex x); sqrt() returns the square root of its argument. If c and d are real values, then every complex number (a,b), where:  a = c - d  b = 2cd has two square roots:  (c,d)  (-c,-d ) sqrt() returns the square root that has a positive real part, that is, the square root that is contained in the first or fourth quadrants of the complex plane. ═══ 3.1.7. Trigonometric Functions for complex ═══ The following trigonometric functions are described:  cos - Cosine  cosh - Hyperbolic cosine  sin - Sine  sinh - Hyperbolic sine You can also view the Open Class Library User's Guide section on complex trigonometric functions for an example of using them. ═══ 3.1.7.1. cos ═══ friend complex cos(complex x); cos() returns the cosine of x. ═══ 3.1.7.2. cosh ═══ friend complex cosh(complex x); cosh() returns the hyperbolic cosine of x. Results of the Default Error-Handling Procedures shows the values returned by the default error-handling procedure for cosh(). ═══ 3.1.7.3. sin ═══ friend complex sin(complex x); sin() returns the sine of x. ═══ 3.1.7.4. sinh ═══ friend complex sinh(complex x); sinh() returns the hyperbolic sine of x. Results of the Default Error-Handling Procedures shows the values returned by the default error-handling procedure for sinh(). ═══ 3.1.8. Magnitude Functions for complex ═══ The following magnitude functions are described:  abs - Absolute value  norm - Square magnitude ═══ 3.1.8.1. abs ═══ friend double abs(complex x); abs() returns the absolute value or magnitude of its argument. The absolute value of a complex value (a,b) is the positive square root of a +b . ═══ 3.1.8.2. norm ═══ friend double norm(complex x); norm() returns the square of the magnitude of its argument. If the argument x is equal to the complex number (a,b), norm() returns the value a +b . norm() is faster than abs(), but it is more likely to cause overflow errors. ═══ 3.1.9. Conversion Functions for complex ═══ You can use the conversion functions in the Complex Mathematics Library to convert between the polar and standard complex representations of a value and to extract the real and imaginary parts of a complex value. The following conversion functions are described:  arg - Angle in radians  conj - Conjugation  polar - Polar to complex  real - Extract real part  imag - Extract imaginary part You can also view the Open Class Library User's Guide section on complex conversion functions for an example of using them. ═══ 3.1.9.1. arg ═══ friend double arg(complex x); arg() returns the angle (in radians) of the polar representation of its argument. If the argument x is equal to the complex number (a,b), the angle returned is the angle in radians on the complex plane between the real axis and the vector (a,b). The return value has a range of -pi to pi . Click here for an illustration of the polar representation of complex numbers. ═══ 3.1.9.2. conj ═══ friend complex conj(complex x); conj() returns the complex value equal to (a,-b) if the input argument x is equal to (a,b). ═══ 3.1.9.3. polar ═══ friend complex polar(double a, double b= 0); polar() returns the standard complex representation of the complex number that has a polar representation (a,b). ═══ 3.1.9.4. real ═══ friend double real(const complex& x); real() extracts the real part of the complex number x. ═══ 3.1.9.5. imag ═══ friend double imag(const complex& x); imag() extracts the imaginary part of the complex number x. ═══ 3.2. c_exception Class ═══ Description Derivation Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 3.2.1. Class Description - c_exception ═══ Use the c_exception class to handle errors that are created by the functions and operations in the complex class. In addition to topics shown in the lefthand panel, the following topics are discussed in this chapter:  Errors handled by the Complex Mathematics Library  Errors handled outside the library Note: The c_exception class is not related to the C++ exception handling mechanism that uses the try, catch, and throw statements. ═══ Derivation ═══ c_exception is not derived from any other class. ═══ Header File ═══ c_exception is declared in complex.h. ═══ Members ═══ The following members are provided for c_exception:  Constructor for c_exception  arg1, arg2  name  retval  type ═══ 3.2.2. Constructor for c_exception ═══ c_exception(char *n, const complex& a1, const complex& a2 = complex_zero); The c_exception constructor creates a c_exception object with name member equal to n, arg1 member equal to a1, and arg2 member equal to a2. ═══ 3.2.3. Data Members of c_exception ═══ The following data members are described:  arg1, arg2 - Arguments of the function that caused the error  name - Name of the function that caused the error  retval - Value returned by the default definition of the error handling function  type - Type of error that has occurred ═══ 3.2.3.1. arg1, arg2 ═══ complex arg1; complex arg2; arg1 and arg2 are the arguments with which the function that caused the error was called. ═══ 3.2.3.2. name ═══ char *name; name is a string that contains the name of the function where the error occurred. ═══ 3.2.3.3. retval ═══ complex retval; retval is the value that the default definition if the error handling function complex_error() returns. You can make your own definition of complex_error() return a different value. ═══ 3.2.3.4. type ═══ int type; type describes the type of error that has occurred. It can take the following values that are defined in the complex.h header file:  SING argument singularity  OVERFLOW overflow range error  UNDERFLOW underflow range error ═══ 3.2.4. Errors Handled by the Complex Mathematics Library ═══ The following topics are discussed:  complex_error  Default Error-Handling Procedures ═══ 3.2.4.1. complex_error ═══ friend int complex_error(c_exception& ce); complex_error() is invoked by member functions of the Complex Mathematics Library when errors are detected. The argument ce refers to the c_exception object that contains information about the error. You can define your own procedures for handling errors by defining a function called complex_error() with return type int and a single parameter of type c_exception&. If you define your own complex_error() function and this function returns a nonzero value, no error message will be generated and the external variable errno will not be set. If this function returns zero, errno is given the value of one of the following constants:  ERANGE if the result is too large or too small  EDOM if there is a domain error within a mathematical function These constants are defined in errno.h. If you define your own version of complex_error(), when you compile your program you must use the /NOE option. For example, if the source file containing your definition of complex_error() is source1.cpp, then you would invoke the compiler like this: icc source1.cpp /B"/NOE" ═══ 3.2.4.2. Default Error-Handling Procedures ═══ If you do not define your own complex_error(), the default error-handling procedures will be invoked when an error occurs. The results for a given input complex value (a, b) depend on the kind of error and the sign of the cosine and sine of b. The following table shows the return value of the default error-handling procedure and the value given to errno for each function with input equal to the complex value (a, b). Note: The following symbols appear in this table: 1. NA - not applicable. The result of the error depends on the sign of the cosine and sine of b (the imaginary part of the argument) unless "NA" appears in the Cosine b or Sine b columns. 2. HUGE - the maximum double value. This value is defined in math.h. Function Error Cosine b Sine b Return Value errno Value cosh a too large nonneg. nonneg. (+HUGE,+HUGE) ERANGE cosh a too large nonneg. nenneg. (+HUGE,-HUGE) ERANGE cosh a too small nonneg. nonneg. (+HUGE,-HUGE) ERANGE cosh a too small nonneg. nenneg. (+HUGE,+HUGE) ERANGE cosh a too small negative nonneg. (-HUGE,-HUGE) ERANGE cosh a too small negative nenneg. (-HUGE,+HUGE) ERANGE cosh b too large negative nonneg. (-HUGE,+HUGE) ERANGE cosh b too large negative nenneg. (-HUGE,-HUGE) ERANGE cosh b too small NA NA (0,0) ERANGE exp a too large positive positive (+HUGE,+HUGE) ERANGE exp a too large positive positive (+HUGE,-HUGE) ERANGE exp a too large nonpos. positive (-HUGE,+HUGE) ERANGE exp a too large nonpos. positive (-HUGE,-HUGE) ERANGE exp a too small NA NA (0,0) ERANGE exp b too large NA NA (0,0) ERANGE exp b too small NA NA (0,0) ERANGE log a too large positive positive (+HUGE,0) EDOM (a message is also produced) sinh a too large nonneg. nonneg. (+HUGE,+HUGE) ERANGE sinh a too large nonneg. negative (+HUGE,-HUGE) ERANGE sinh a too large negative nonneg. (-HUGE,+HUGE) ERANGE sinh a too large negative negative (-HUGE,-HUGE) ERANGE sinh a too small nonneg. nonneg. (-HUGE,+HUGE) ERANGE sinh a too small nonneg. negative (-HUGE,-HUGE) ERANGE sinh a too small negative nonneg. (+HUGE,+HUGE) ERANGE sinh a too small negative negative (+HUGE,-HUGE) ERANGE sinh b too large NA NA (0,0) ERANGE sinh b too small NA NA (0,0) ERANGE Note: errno is set to EDOM when the error for log() is detected. The message is stored in DDE4.MSG. The message number in DDE4.MSG is 90. When this message is displayed by the C/C++ Runtime Library, it is changed to 5090. For information on binding this message, see "Binding Runtime Messages" in the IBM VisualAge C++ for OS/2 User's Guide and Reference. ═══ 3.2.5. Errors Not Handled by the Complex Mathematics Library ═══ There are some cases where member functions of the Complex Mathematics Library call functions in the math library. These calls can cause underflow and overflow conditions that are handled by the matherr() function that is declared in the math.h header file. For example, the overflow conditions that are caused by the following calls are handled by matherr():  exp(complex(DBL_MAX, DBL_MAX))  pow(complex(DBL_MAX, DBL_MAX), INT_MAX)  norm(complex(DBL_MAX, DBL_MAX)) DBL_MAX is the maximum valid double value. INT_MAX is the maximum int value. Both these constants are defined in float.h. If you do not want the default error-handling defined by matherr(), you should define your own version of matherr(). ═══ 4. I/O Stream Classes ═══ With the I/O Stream Library you can perform input and output to console or files using a typesafe, object-oriented programming approach. The following classes or groups of classes are described in this section: filebuf Class Describes filebuf, the class that is used to associate stream buffers with files. fstream, ifstream, and ofstream Classes Describes fstream, ifstream, and ofstream, the classes that specialize istream, ostream, and iostream for use with files. ios Class Describes ios, the base class for the classes that format data that is extracted from or inserted into stream buffers. iostream and iostream_withassign Classes Describes iostream, the class derived from istream and ostream, and iostream_withassign, the class derived from istream_withassign and ostream_withassign. istream and istream_withassign Classes Describes istream, the class you can use to extract data from a stream buffer, and istream_withassign, a class derived from istream that includes an assignment operator. Manipulators Describes the parameterized manipulators you can use to use the input or operator to change the state of a stream. ostream and ostream_withassign Classes Describes ostream, the class you can use to insert data into a stream buffer, and ostream_withassign, a class derived from ostream that includes an assignment operator. stdiobuf and stdiostream Classes Describes stdiobuf, the class you can use to mix standard C input and output functions with C++ I/O Stream Library functions, and stdiostream, the class that uses stdiobuf objects as stream buffers. streambuf Class Describes streambuf, a class you can use to manipulate objects of its derived classes filebuf, stdiobuf, and strstreambuf, or derive other classes from it. strstream, istrstream, and ostrstream Classes Describes istrstream, ostrsteam, and strstream, the classes that specialize istream, ostream, and iostream (respectively) to use strstreambuf objects for stream buffers. These classes are called the array stream buffer classes because their stream buffers are arrays of bytes in memory. You can use these classes to perform input and output with strings in memory. strstreambuf Class Describes strstreambuf, the class that specializes streambuf to use an array of bytes in memory as the source or target of data. ═══ 4.1. filebuf Class ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.1.1. Class Description - filebuf ═══ This chapter describes the filebuf class, the class that specializes streambuf for using files as the ultimate producer or the ultimate consumer. In a filebuf object, characters are cleared out of the put area by doing write operations to the file, and characters are put into the get area by doing read operations from that file. The filebuf class supports seek operations on files that allow seek operations. A filebuf object that is attached to a file descriptor is said to be open. The stream buffer is allocated automatically if one is not specified explicitly with a constructor or a call to setbuf(). You can also create an unbuffered filebuf object by calling the constructor or setbuf() with the appropriate arguments. If the filebuf objec is unbuffered, a system call is made for each character that is read or written. The get and put pointers for a filebuf object behave as a single pointer. This single pointer is referred to as the get/put pointer. The file that is attached to the filebuf object also has a single pointer that indicates the current position where information is being read or written. In this chapter, this pointer is called the file get/put pointer. ═══ Derivation ═══ streambuf filebuf ═══ Header File ═══ filebuf is declared in fstream.h. ═══ 4.1.2. Public Members of filebuf ═══ See Using filebuf Functions to Move Through a File for an example of using the filebuf class. Note: The following descriptions assume that the functions are called as part of a filebuf object called fb. The following member functions are described:  Constructors for filebuf  Destructor for filebuf  attach - attach filebuf object to file  close - disconnect filebuf  detach - detach filebuf object from file  fd - return file descriptor  is_open - return status of filebuf  open - open file and attach to filebuf  seekoff - move the file get/put pointer  seekpos - move the file get/put pointer  setbuf - set up stream buffer  sync - synchronize file and stream buffer ═══ 4.1.2.1. Constructors for filebuf ═══ filebuf(); filebuf(int d); filebuf(int d, char* p, int len); The filebuf() constructor with no arguments constructs an initially closed filebuf object. The filebuf() constructor with one argument constructs a filebuf object that is attached to file descriptor d. The filebuf() constructor with three arguments constructs a filebuf object that is attached to file descriptor d. The object is initialized to use the stream buffer starting at the position pointed to by p with length equal to len. ═══ 4.1.2.2. Destructor for filebuf ═══ ~filebuf(); The filebuf destructor calls fb.close(). ═══ 4.1.2.3. attach ═══ filebuf* attach(int d); attach() attaches fb to the file descriptor d. fb is the filebuf object returned by attach(). If fb is already open or if d is not open, attach() returns NULL. Otherwise, attach() returns a pointer to fb. ═══ 4.1.2.4. detach ═══ int detach(); fb.detach() disconnects fb from the file without closing the file. If fb is not open, detach() returns -1. Otherwise, detach() flushes any output that is waiting in fb to be sent to the file, disconnects fb from the file, and returns the file descriptor. ═══ 4.1.2.5. close ═══ filebuf* close(); close() does the following: 1. Flushes any output that is waiting in fb to be sent to the file 2. Disconnects fb from the file 3. Closes the file that was attached to fb If an error occurs, close() returns 0. Otherwise, close() returns a pointer to fb. Even if an error occurs, close() performs the second and third steps listed above. ═══ 4.1.2.6. fd ═══ int fd(); fd() returns the file descriptor that is attached to fb. If fb is closed, fd() returns EOF. ═══ 4.1.2.7. is_open ═══ int is_open(); is_open() returns a nonzero value if fb is attached to a file descriptor. Otherwise, is_open() returns zero. ═══ 4.1.2.8. open ═══ filebuf* open(const char* fname, int omode, int prot=openprot); open() opens the file with the name fname and attaches fb to it. If fname does not already exist and omode does not equal ios::nocreate, open() tries to create it with protection mode equal to prot. The default value of prot is filebuf::openprot. An error occurs if fb is already open. If an error occurs, open() returns 0. Otherwise, open() returns a pointer to fb. The default protection mode for the filebuf class is S_IREAD | S_IWRITE. If you create a file with both S_IREAD and S_IWRITE set, the file is created with both read and write permission. If you create a file with only S_IREAD set, the file is created with read-only permission, and cannot be deleted later with the stdio.h library function remove(). S_IREAD and S_IWRITE are defined in sys\stat.h. ═══ 4.1.2.9. seekoff ═══ streampos seekoff(streamoff so, seek_dir sd, int omode); seekoff() moves the file get/put pointer to the position specified by sd with the offset so. sd can have the following values:  ios::beg: the beginning of the file  ios::cur: the current position of the file get/put pointer  ios::end: the end of the file seekoff() changes the position of the file get/put pointer to the position specified by the value sd + so. The offset so can be either positive or negative. seekoff() ignores the value of omode. If fb is attached to a file that does not support seeking, or if the value sd + so specifies a position before the beginning of the file, seekoff() returns EOF and the position of the file get/put pointer is undefined. Otherwise, seekoff() returns the new position of the file get/put pointer. ═══ 4.1.2.10. seekpos ═══ The filebuf class inherits the default definition of seekpos() from the streambuf class. The default definition defines seekpos() as a call to seekoff(). Thus, the following call to seekpos(): seekpos(pos, mode); is converted to a call to seekoff(): seekoff(streamoff(pos), ios::beg, mode); ═══ 4.1.2.11. setbuf ═══ streambuf* setbuf(char* pbegin, int len); setbuf() sets up a stream buffer with length in bytes equal to len, beginning at the position pointed to by pbegin. setbuf() does the following:  If pbegin is 0 or len is nonpositive, setbuf() makes fb unbuffered.  If fb is open and a stream buffer has been allocated, no changes are made to this stream buffer, and setbuf() returns NULL.  If neither of these cases is true, setbuf() returns a pointer to fb. ═══ 4.1.2.12. sync ═══ int sync(); sync() attempts to synchronize the get/put pointer and the file get/put pointer. sync() may cause bytes that are waiting in the stream buffer to be written to the file, or it may reposition the file get/put pointer if characters that have been read from the file are waiting in the stream buffer. If it is not possible to synchronize the get/put pointer and the file get/put pointer, sync() returns EOF. If they can be synchronized, sync() returns zero. ═══ 4.2. fstream, ifstream, and ofstream Classes ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.2.1. Class Description - fstream, ifstream, and ofstream ═══ The fstream, ifstream, and ofstream classes specialize istream, ostream, and iostream for use with files. ═══ Derivation ═══ ios istream ifstream ostream ofstream istream and ostream iostream fstream ═══ Header File ═══ fstream, ifstream, and ofstream are declared in fstream.h. ═══ Members ═══ The following members are provided for fstream, ifstream, ofstream, and fstreambase:  fstreambase: attach close detach setbuf  fstream: Constructors for fstream open rdbuf  ifstream: Constructors for ifstream open rdbuf  ofstream: Constructors for ofstream open rdbuf ═══ 4.2.2. fstreambase ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.2.3. Class Description - fstreambase ═══ Note: 1. The fstreambase class is an internal class that provides common functions for the classes that are derived from it. Do not use the fstreambase class directly. The following descriptions are provided so that you can use the functions as part of fstream, ifstream, and ofstream objects. 2. The following descriptions assume that the functions are called as part of an fstream, ifstream, or ofstream object called fb. ═══ 4.2.3.1. Members ═══ The following functions are described:  attach - connect fstream object to file descriptor  close - close associated filebuf object  detach - detach associated filebuf object  setbuf - set up stream buffer ═══ 4.2.3.1.1. attach ═══ void attach(int filedesc); attach() attaches fb to the file descriptor filedesc. If fb is already attached to a file descriptor, an error occurs and ios::failbit is set in the format state of fb. ═══ 4.2.3.1.2. close ═══ void close(); close() closes the filebuf object, breaking the connection between fb and the file descriptor. close() calls fb.rdbuf()->close(). If this call fails, the error state of fb is not cleared. ═══ 4.2.3.1.3. detach ═══ int detach(); detach detaches the filebuf object by calling fb.rdbuf()->detach(), and returns the value returned by fb.rdbuf()->detach(). ═══ 4.2.3.1.4. setbuf ═══ void setbuf(char* pbegin, int len); setbuf() sets up a stream buffer with length in bytes equal to len beginning at the position pointed to by pbegin. If pbegin is equal to 0 or len is nonpositive, fb will be unbuffered. If fb is open, or the call to fb.rdbuf()->setbuf() fails, setbuf() sets ios::failbit in the object's state. ═══ 4.2.4. fstream Class ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.2.5. Class Description - fstream ═══ The fstream class specializes iostream for use with files. Once an fstream object is associated with a file, you can either read to it or write to it, depending on the mode with which the file was opened. Once the file is closed, you can open another file (or the same file again) in a different mode using the same fstream object. The descriptions for fstream member functions assume that the functions are called as part of an fstream object called fs. ═══ 4.2.5.1. Members ═══ The following functions are described:  Constructors for fstream  open - open file and connect to fstream object  rdbuf - return pointer to filebuf object ═══ 4.2.5.1.1. Constructors for fstream ═══ fstream(); This version of the fstream constructor takes no arguments and constructs an unopened fstream object. fstream(int filedesc); This version takes one argument and constructs an fstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of fs. fstream(const char* fname, int mode, int prot=filebuf::openprot); This version constructs an fstream object and opens the file fname with open mode equal to mode and protection mode equal to prot. The default value for the argument prot is filebuf::openprot. If the file cannot be opened, the error state of the constructed fstream object is set. fstream(int filedesc, char* bufpos, int len); This version constructs an fstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of fs. This constructor also sets up an associated filebuf object with a stream buffer that has length len bytes and begins at the position pointed to by bufpos. If bufpos is equal to 0 or len is equal to 0, the associated filebuf object is unbuffered. ═══ 4.2.5.1.2. open ═══ void open(const char* fname, int mode, int prot=filebuf::openprot); open() opens the file with the name fname and attaches it to fs. If fname does not already exist, open() tries to create it with protection mode equal to prot, unless ios::nocreate is set. The default value for prot is filebuf::openprot. If fs is already attached to a file or if the call to fs.rdbuf()->open() fails, ios::failbit is set in the error state for fs. The members of the ios::open_mode enumeration are bits that can be ORed together. The value of mode is the result of such an OR operation. This result is an int value, and for this reason, mode has type int rather than open_mode. The elements of the open_mode enumeration have the following meanings: ios::app open() performs a seek to the end of the file. Data that is written is appended to the end of the file. This value implies that the file is open for output. ios::ate open() performs a seek to the end of the file. Setting ios::ate does not open the file for input or output. If you set ios::ate, you should explicitly set ios::in, ios::out, or both. ios::bin See ios::binary below. ios::binary The file is opened in binary mode. In the default (text) mode, carriage returns are discarded on input, as is an end-of-file (0x1a) character if it is the last character in the file. This means that a carriage return without an accompanying line feed causes the characters on either side of the carriage return to become adjacent. On output, a line feed is expanded to a carriage return and line feed. If you specify ios::binary, carriage returns and terminating end-of-file characters are not removed on input, and a line feed is not expanded to a carriage return and line feed on output. ios::binary and ios::bin provide identical functionality. ios::in The file is opened for input. If the file that is being opened for input does not exist, the open operation will fail. ios::noreplace is ignored if ios::in is set. ios::out The file is opened for output. ios::trunc If the file already exists, its contents will be discarded. If you specify ios::out and neither ios::ate nor ios::app, you are implicitly specifying ios::trunc. If you set ios::trunc, you should explicitly set ios::in, ios::out, or both. ios::nocreate If the file does not exist, the call to open() fails. ios::noreplace If the file already exists and ios::out is set, the call to open() fails. If ios::out is not set, ios::noreplace is ignored. ═══ 4.2.5.1.3. rdbuf ═══ filebuf* rdbuf(); rdbuf() returns a pointer to the filebuf object that is attached to fs. ═══ 4.2.6. ifstream Class ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.2.7. Class Description - ifstream ═══ The ifstream class specializes istream for use with files. When you create an ifstream object and associate it with a file, the file is opened for input. The advantage of using ifstream over fstream is that attempts to write data to an ifstream object are flagged as errors at compilation. For an example of using the ifstream class, click here. Note: The following descriptions assume that the functions are called as part of an ifstream object called ifs. ═══ 4.2.7.1. Members ═══  Constructors for ifstream  open - open file and connect to ifstream object  rdbuf - return pointer to filebuf object ═══ 4.2.7.1.1. Constructors for ifstream ═══ ifstream(); This version of the ifstream constructor takes no arguments and constructs an unopened ifstream object. ifstream(int filedesc); This version takes one argument and constructs an ifstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of ifs. ifstream(const char* fname, int mode=ios::in, int prot=filebuf::openprot); The third version constructs an ifstream object and opens the file fname with open mode equal to mode and protection mode equal to prot. The default value for mode is ios::in, and the default value for prot is filebuf::openprot. If the file cannot be opened, the error state of the constructed ifstream object is set. ifstream(int filedesc, char* bufpos, int len); This version constructs an ifstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of ifs. This constructor also sets up an associated filebuf object with a stream buffer that has length len bytes and begins at the position pointed to by bufpos. If bufpos is equal to 0 or len is equal to 0, the associated filebuf object is unbuffered. ═══ 4.2.7.1.2. open ═══ void open(const char* fname, int mode=ios::in, int prot=filebuf::openprot); open() opens the file with the name fname and attaches it to ifs. If fname does not already exist, open() tries to create it with protection mode equal to prot, unless ios::nocreate is set in mode. The default value for mode is ios::in. The default value for prot is filebuf::openprot. If ifs is already attached to a file, or if the call to ifs.rdbuf()->open() fails, ios::failbit is set in the error status for ifs. The members of the ios::open_mode enumeration are bits that can be ORed together. The value of mode is the result of such an OR operation. This result is an int value, and for this reason mode has type int rather than type open_mode. See open for a list of the possible values for mode. ═══ 4.2.7.1.3. rdbuf ═══ filebuf* rdbuf(); rdbuf() returns a pointer to the filebuf object that is attached to ifs. ═══ 4.2.8. ofstream Class ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.2.9. Class Description - ofstream ═══ The ofstream class specializes ostream for use with files. When you create an ofstream object and associate it with a file, the file is opened for output. The advantage of using ofstream over fstream is that attempts to read data from an ofstream object are flagged as errors at compilation. For an example of using the ofstream class, select this hypertext link. Note: The following descriptions assume that the functions are called as part of an ofstream object called ofs. ═══ Members ═══  Constructors for ofstream  open - open file and connect to ofstream object  rdbuf - return pointer to filebuf object ═══ 4.2.9.1. Constructors for ofstream ═══ ofstream(); This version of the ofstream constructor takes no arguments and constructs an unopened ofstream object. ofstream(int filedesc); This version takes one argument and constructs an ofstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of ofs. ofstream(const char* fname, int mode=ios::out, int prot=filebuf::openprot); This version constructs an ofstream object and opens the file fname with open mode equal to mode and protection mode equal to prot. The default value for mode is ios::out, and the default value for prot is filebuf::openprot. If the file cannot be opened, the error state of the constructed ofstream object is set. ofstream(int filedesc, char* bufpos, int len); This version constructs an ofstream object that is attached to the file descriptor filedesc. If filedesc is not open, ios::failbit is set in the format state of ofs. This constructor also sets up an associated filebuf object with a stream buffer that has length len bytes and begins at the position pointed to by bufpos. If p is equal to 0 or len is equal to 0, the associated filebuf object is unbuffered. ═══ 4.2.9.2. open ═══ void open(const char* fname, int mode, int prot=filebuf::openprot); open() opens the file with the name fname and attaches it to ofs. If fname does not already exist, open() tries to create it with protection mode equal to prot, unless ios::nocreate is set. The default value for mode is ios::out. The default value for the argument prot is filebuf::openprot. If ofs is already attached to a file, or if the call to the function ofs.rdbuf()->open() fails, ios::failbit is set in the error state for ofs. The members of the ios::open_mode enumeration are bits that can be ORed together. The value of mode is the result of such an OR operation. This result is an int value, and for this reason, mode has type int rather than open_mode. See open for a list of the possible values for mode. ═══ 4.2.9.3. rdbuf ═══ filebuf* rdbuf(); rdbuf() returns a pointer to the filebuf object that is attached to ofs. ═══ 4.3. ios Class ═══ Description Derivation Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.3.1. Class Description - ios ═══ The ios class maintains the error and format state information for the classes that are derived from it. The derived classes support the movement of formatted and unformatted data to and from the stream buffer. This chapter describes the members of the ios class, and thus describes the operations that are common to all the classes that are derived from ios. You can view the topics in this chapter either through the panel on the left, or by selecting from among the following:  Format State Variables  Format State Flags: - White Space and Padding - Base Conversion - Integral Formatting - Floating-Point Formatting - Uppercase and Lowercase - Buffer Flushing - Mutually Exclusive Format Flags  Format State Members  User-Defined Format Flags  ios Error State  Other ios Members  Built-In Manipulators ═══ Derivation ═══ ios ═══ Header File ═══ ios is declared in iostream.h. ═══ Members ═══ The following members are provided for ios. Italicized members are flags or variables used to maintain the format state information for streams.  ios constructor  bad  bitalloc  clear  dec  dec manipulator  endl manipulator  ends manipulator  eof  fail  fill  fixed  flags  flush manipulator  good  hex  hex manipulator  internal  iword  left  oct  oct manipulator  operator void*  operator=  precision  pword  rdbuf  rdstate  right  scientific  setf  showbase  showpoint  showpos  skip  skipws  stdio  sync_with_stdio  tie  unitbuf  unsetf  uppercase  width  ws manipulator  x_fill  x_precision  x_width  xalloc ═══ 4.3.2. Constructors and Assignment Operator for ios ═══ public: ios(streambuf* sb); protected: ios(); init(streambuf* isb); private: ios(ios& ioa); void operator=(ios& iob); There are three versions of the ios constructor. The version that is declared public takes a single argument that is a pointer to the streambuf object that becomes associated with the constructed ios object. If this pointer is equal to 0, the result is undefined. The version of the ios constructor that is declared protected takes no arguments. This version is needed because ios is used as a virtual base class for iostream, and therefore the ios class must have a constructor that takes no arguments. If you use this constructor in a derived class, you must use the init() function to associate the constructed ios object with the streambuf object pointed to by the argument isb. Copying of ios objects is not well defined, and for this reason, both the assignment operator and the copy constructor are declared private. Assignment between streams is supported by the istream_withassign, ostream_withassign, and iostream_withassign classes. See Assignment Operator for istream_withassign and Assignment Operator for ostream_withassign for more details. Except for the ..._withassign classes, none of the predefined classes derived from ios has a copy constructor or an assignment operator. Unless you define your own copy constructor or assignment operator for a class that you derive from ios, your class will have neither a copy constructor nor an assignment operator. ═══ 4.3.3. Format State Variables ═══ The format state is a collection of format flags and format variables that control the details of formatting for input and output operations. This section describes the format variables. ═══ 4.3.3.1. x_fill ═══ char x_fill; x_fill is the character that is used to pad values that do not require the width of an entire field for their representation. Its default value is a space character. ═══ 4.3.3.2. x_precision ═══ short x_precision; x_precision is the number of significant digits in the representation of floating-point values. Its default value is 6. ═══ 4.3.3.3. x_width ═══ short x_width; x_width is the minimum width of a field. Its default value is 0. ═══ 4.3.4. Format State Flags ═══ The following list shows the formatting features and the format flags that control them:  White space and padding: ios::skipws, ios::left, ios::right, ios::internal  Base conversion: ios::dec, ios::hex, ios::oct, ios::showbase  Integral formatting: ios::showpos  Floating-point formatting: ios::fixed, ios::scientific, ios::showpoint  Uppercase and lowercase: ios::uppercase  Buffer flushing: ios::stdio, ios::unitbuf Mutually Exclusive Format Flags describes the flags that produce unpredictable results if they are set at the same time. ═══ 4.3.4.1. White Space and Padding ═══ The following format state flags control white space and padding characters. skipws and right are set by default. ═══ 4.3.4.1.1. skipws ═══ If ios::skipws is set, white space will be skipped on input. If it is not set, white space is not skipped. If ios::skipws is not set, the arithmetic extractors will signal an error if you attempt to read an integer or floating-point value that is preceded by white space. ios::failbit is set, and extraction ceases until it is cleared. This is done to avoid looping problems. If the following program is run with an input file that contains integer values separated by spaces, ios::failbit is set after the first integer value is read, and the program halts. If the program did not call fail() at the beginning of the while loop to test if ios::failbit is set, it would loop indefinitely. #include void main() { fstream f("spadina.dat", ios::in); f.unsetf(ios::skipws); int i; while (!f.eof() && !f.fail()) { f >> i; cout << i; } } ═══ 4.3.4.1.2. left ═══ If ios::left is set, the value is left-justified. Fill characters are added after the value. ═══ 4.3.4.1.3. right ═══ If ios::right is set, the value is right-justified. Fill characters are added before the value. ═══ 4.3.4.1.4. internal ═══ If ios::internal is set, the fill characters are added after any leading sign or base notation, but before the value itself. ═══ 4.3.4.2. Base Conversion ═══ The manipulators ios::dec, ios::oct, and ios::hex (see Built-In Manipulators for ios for more details) have the same effect as the flags ios::dec, ios::oct, and ios::hex, respectively. dec is set by default. ═══ 4.3.4.2.1. dec ═══ If ios::dec is set, the conversion base is 10. ═══ 4.3.4.2.2. oct ═══ If ios::oct is set, the conversion base is 8. ═══ 4.3.4.2.3. hex ═══ If ios::hex is set, the conversion base is 16. ═══ 4.3.4.2.4. showbase ═══ If ios::showbase is set, the operation that inserts values converts them to an external form that can be read according to the C++ lexical conventions for integral constants. By default, ios::showbase is unset. ═══ 4.3.4.3. Integral Formatting ═══ :link auto dependent reftype=hd refid=iosshop. The following manipulator affects integral formatting: ═══ 4.3.4.3.1. showpos ═══ If ios::showpos is set, the operation that inserts values places a positive sign "+" into decimal conversions of positive integral values. By default, showpos is not set. ═══ 4.3.4.4. Floating-Point Formatting ═══ The following format flags control the formatting of floating-point values: :link auto dependent reftype=hd refid=iosshpt. ═══ 4.3.4.4.1. showpoint ═══ If ios::showpoint is set, trailing zeros and a decimal point appear in the result of a floating-point conversion. This flag has no effect if either ios::scientific or ios::fixed is set. showpoint is not set by default. ═══ 4.3.4.4.2. scientific ═══ If ios::scientific is set, the value is converted using scientific notation. In scientific notation, there is one digit before the decimal point and the number of digits following the decimal point depends on the value of ios::x_precision. The default value for ios::x_precision is 6. If ios::uppercase is set, an uppercase "E" precedes the exponent. Otherwise, a lowercase "e" precedes the exponent. By default, uppercase is not set. See uppercase for more information. ═══ 4.3.4.4.3. fixed ═══ If ios::fixed is set, floating-point values are converted to fixed notation with the number of digits after the decimal point equal to the value of ios::x_precision (or 6 by default). ios::fixed is not set by default. ═══ 4.3.4.4.4. Default Representation of Floating-Point Values ═══ If neither ios::fixed nor ios::scientific is set, the representation of floating-point values depends on their values and the number of significant digits in the representation equals ios::x_precision. Floating-point values are converted to scientific notation if the exponent resulting from a conversion to scientific notation is less than -4 or greater than or equal to the value of ios::x_precision. Otherwise, floating-point values are converted to fixed notation. If ios::showpoint is not set, trailing zeros are removed from the result and a decimal point appears only if it is followed by a digit. ios::scientific and ios::fixed are collectively identified by the static member ios::floatfield. ═══ 4.3.4.5. Uppercase and Lowercase ═══ :link auto dependent reftype=hd refid=iosuppr. The following enumeration member determines whether alphabetic characters used in floating-point numbers appear in upper- or lowercase: ═══ 4.3.4.5.1. uppercase ═══ If ios::uppercase is set, the operation that inserts values uses an uppercase "E" for floating-point values in scientific notation. In addition, the operation that inserts values stores hexadecimal digits "A" to "F" in uppercase and places an uppercase "X" before hexadecimal values when ios::showbase is set. If ios::uppercase is not set, a lowercase "e" introduces the exponent in floating-point values, hexadecimal digits "a" to "f" are stored in lowercase, and a lowercase "x" is inserted before hexadecimal values when ios::showbase is set. The setting of uppercase also determines whether special numbers such as inf or infinity are inserted in uppercase. ═══ 4.3.4.6. Buffer Flushing ═══ :link auto dependent reftype=hd refid=iosunbf . The following enumeration members affect buffer flushing behavior: ═══ 4.3.4.6.1. unitbuf ═══ If ios::unitbuf is set, ostream::osfx() performs a flush after each insertion. The attached stream buffer is unit buffered. ios::unitbuf is not set by default. ═══ 4.3.4.6.2. stdio ═══ This flag is used internally by sync_with_stdio(). Do not use ios::stdio directly. If you want to combine I/O Stream Library input and output with stdio.h input and output, use sync_with_stdio(). See sync_with_stdio for more details on sync_with_stdio(). ios::stdio is not set by default. ═══ 4.3.4.7. Mutually Exclusive Format Flags ═══ If you specify conflicting flags, the results are unpredictable. For example, the results will be unpredictable if you set both ios::left and ios::right in the format state of iosobj. Set only one flag in each set of the following three sets:  ios::left, ios::right, ios::internal  ios::dec, ios::oct, ios::hex  ios::scientific, ios::fixed ═══ 4.3.5. Public Members of ios for the Format State ═══ You can use the member functions listed below to control the format state of an ios object. Note: The following descriptions assume that the functions are called as part of an ios object called iosobj. The following functions are described:  fill - Set the fill character  flags - Set format flags  precision - Set the precision  setf - Set specific format flags  skip - Set ios::skipws format flag  unsetf - Turn off format flags  width - Set field width ═══ 4.3.5.1. fill ═══ char fill() const; char fill(char fillchar); fill() with no arguments returns the value of ios::x_fill in the format state of iosobj. fill() with an argument fillchar sets ios::x_fill to be equal to fillchar. It returns the value of ios::x_fill. ios::x_fill is the character used as padding if the field is wider than the representation of a value. The default value for ios::x_fill is a space. The ios::left, ios::right, and ios::internal flags determine the position of the fill character. You can also use the parameterized manipulator setfill to set the value of ios::x_fill. ═══ 4.3.5.2. flags ═══ long flags() const; long flags(long flagset); flags() with no arguments returns the value of the flags that make up the current format state. flags() with one argument sets the flags in the format state to the settings specified in flagset and returns the value of the previous settings of the format flags. ═══ 4.3.5.3. precision ═══ int precision() const; int precision(int prec); precision() with no arguments returns the value of ios::x_precision. precision() with one argument sets the value of ios::x_precision to prec and returns the previous value. The value of prec must be greater than 0. If the value is nonpositive, the value of ios::x_precision is set to the default value, 6. ios::x_precision controls the number of significant digits when floating-point values are inserted. The format state in effect when precision() is called affects the behavior of precision(). If neither ios::scientific nor ios::fixed is set, ios::x_precision specifies the number of significant digits in the floating-point value that is being inserted. If, in addition, ios::showpoint is not set, all trailing zeros are removed and a decimal point only appears if it is followed by digits. If either ios::scientific or ios::fixed is set, ios::x_precision specifies the number of digits following the decimal point. You can also use the parameterized manipulator setprecision to set ios::x_precision. ═══ 4.3.5.4. setf ═══ long setf(long newset); long setf(long newset, long field); setf() with one argument is accumulative. It sets the format flags that are marked in newset, without affecting flags that are not marked in newset, and returns the previous value of the format state. You can also use the parameterized manipulator setiosflags to set the format flags to a specific setting. setf() with two arguments clears the format flags specified in field, sets the format flags specified in newset, and returns the previous value of the format state. For example, to change the conversion base in the format state to ios::hex, you could use a statement like this: s.setf(ios::hex, ios::basefield); In this statement, ios::basefield specifies the conversion base as the format flag that is going to be changed, and ios::hex specifies the new value for the conversion base. If newset equals 0, all of the format flags specified in field are cleared. You can also use the parameterized manipulator resetiosflags to clear format flags. Note: If you set conflicting flags the results are unpredictable. ═══ 4.3.5.5. skip ═══ int skip(int i); skip() sets the format flag ios::skipws if the value of the argument i does not equal 0. If i does equal 0, ios::skipws is cleared. skip() returns a value of 1 if ios::skipws was set prior to the call to skip(), and returns 0 otherwise. ═══ 4.3.5.6. unsetf ═══ long unsetf(long oflags); unsetf() turns off the format flags specified in oflags and returns the previous format state. ═══ 4.3.5.7. width ═══ int width() const; int width(int fwidth); width() with no arguments returns the value of the current setting of the format state field width variable, ios::x_width. If the value of ios::x_width is smaller than the space needed for the representation of the value, the full value is still inserted. width() with one argument, fwidth, sets ios::x_width to the value of fwidth and returns the previous value. The default field width is 0. When the value of ios::x_width is 0, the operations that insert values only insert the characters needed to represent a value. If the value of ios::x_width is greater than 0, the characters needed to represent the value are inserted. Then fill characters are inserted, if necessary, so that the representation of the value takes up the entire field. ios::x_width only specifies a minimum width, not a maximum width. If the number of characters needed to represent a value is greater than the field width, none of the characters is truncated. After every insertion of a value of a numeric or string type (including char*, unsigned char*, signed char*, and wchar_t*, but excluding char, unsigned char, signed char, and wchar_t), the value of ios::x_width is reset to 0. After every extraction of a value of type char*, unsigned char*, signed char*, or wchar_t*, the value of ios::x_width is reset to 0. You can also use the parameterized manipulator setw to set the field width. ═══ 4.3.6. Public Members of ios for User-Defined Format Flags ═══ In addition to the flags described in Format State Flags, you can also use the ios member functions listed in this section to define additional format flags or variables in classes that you derive from ios. The following member functions are described:  bitalloc - Create bit set  iword - Return reference to user-defined flag  pword - Return reference to user-defined flag  xalloc - Return index to format state variables. ═══ 4.3.6.1. bitalloc ═══ static long bitalloc(); bitalloc() is a static function that returns a long value with a previously unallocated bit set. You can use this long value as an additional flag, and pass it as an argument to the format state member functions. When all the bits are exhausted, bitalloc() returns 0. ═══ 4.3.6.2. iword ═══ long& iword(int i); iword() returns a reference to the ith user-defined flag, where i is an index returned by xalloc(). iword() allocates space for the user-defined flag. If the allocation fails, iword() sets ios::failbit. ═══ 4.3.6.3. pword ═══ void* & pword(int i); pword() returns a reference to a pointer to the ith user-defined flag, where i is an index returned by xalloc(). pword() allocates space for the user-defined flag. If the allocation fails, pword() sets ios::failbit. pword() is the same as iword(), except that the two functions return different types. ═══ 4.3.6.4. xalloc ═══ static int xalloc(); xalloc() is a static function that returns an unused index into an array of words available for use as format state variables by classes derived from ios. xalloc() simply returns a new index; it does not do any allocation. iword() and pword() do the allocation, and if the allocation fails, they set ios::failbit. You should check ios::failbit after calling iword() or pword(). ═══ 4.3.7. Public Members of ios for the Error State ═══ The error state is an enumeration that records the errors that take place in the processing of ios objects. It has the following declaration: enum io_state { goodbit, eofbit, failbit, badbit, hardfail }; The error state is manipulated using the ios member functions described in this section. Note: 1. hardfail is a flag used internally by the I/O Stream Library. Do not use it. 2. The following descriptions assume that the functions are called as part of an ios object called iosobj. The following member functions are described:  bad - Check ios::badbit  clear - Clear or Set Error State  eof - Check ios::eofbit  fail - Check ios::failbit and ios::badbit  good - Are Any Bits Set  rdstate - Return Error State  Convert ios Object to Pointer Operator void*()  Check ios::failbit and ios::badbit Operator ! ═══ 4.3.7.1. bad ═══ int bad() const; bad() returns a nonzero value if ios::badbit is set in the error state of iosobj. Otherwise, it returns 0. ios::badbit is usually set when some operation on the streambuf object that is associated with the ios object has failed. It will probably not be possible to continue input and output operations on the ios object. ═══ 4.3.7.2. clear ═══ void clear(int state=0); clear() changes the error state of iosobj to state. If state equals 0 (its default), all of the bits in the error state are cleared. If you want to set one of the bits without clearing or setting the other bits in the error state, you can perform a bitwise OR between the bit you want to set and the current error state. For example, the following statement sets ios::badbit in iosobj and leaves all the other error state bits unchanged: iosobj.clear(ios::badbit|iosobj.rdstate()); ═══ 4.3.7.3. eof ═══ int eof() const; eof() returns a nonzero value if ios::eofbit is set in the error state of iosobj. Otherwise, it returns 0. ios::eofbit is usually set when an EOF has been encountered during an extraction operation. ═══ 4.3.7.4. fail ═══ int fail() const; fail() returns a nonzero value if either ios::badbit or ios::failbit is set in the error state. Otherwise, it returns 0. ═══ 4.3.7.5. good ═══ int good() const; good() returns a nonzero value if no bits are set in the error state of iosobj. Otherwise, it returns 0. ═══ 4.3.7.6. rdstate ═══ int rdstate() const; rdstate() returns the current value of the error state of iosobj. ═══ 4.3.7.7. operator void* ═══ operator void*(); operator const void*() const; The void* operator converts iosobj to a pointer so that it can be compared to 0. The conversion returns 0 if ios::failbit or ios::badbit is set in the error state of iosobj. Otherwise, a pointer value is returned. This value is not meant to be manipulated as a pointer; the purpose of the operator is to allow you to write statements such as the following: if (cin) cout << "ios::badbit and ios::failbit are not set" << endl; if (cin >> x) cout << "ios::badbit and ios::failbit are not set " << x << " was input" << endl; ═══ 4.3.7.8. operator! ═══ int operator!() const; The ! operator returns a nonzero value if ios::failbit or ios::badbit is set in the error state of iosobj. You can use this operator to write statements like the following: if (!cin) cout << "either ios::failbit or ios::badbit is set" << endl; else cout << "neither ios::failbit nor ios::badbit is set" << endl; ═══ 4.3.8. Other Members of ios ═══ This section describes the ios member functions that do not deal with the error state or the format state. These descriptions assume that the functions are called as part of an ios object called iosobj. The following functions are described:  rdbuf - Return pointer to associated streambuf object  sync_with_stdio - Attach stdiobuf object to predefined streams  tie - Set the tie variable ═══ 4.3.8.1. rdbuf ═══ streambuf* rdbuf(); rdbuf() returns a pointer to the streambuf object that is associated with iosobj. This is the streambuf object that was passed as an argument to the ios constructor. ═══ 4.3.8.2. sync_with_stdio ═══ static void sync_with_stdio(); sync_with_stdio() is a static function that solves the problems that occur when you call functions declared in stdio.h and I/O Stream Library functions in the same program. The first time that you call sync_with_stdio(), it attaches stdiobuf objects to the predefined streams cin, cout, and cerr. After that, input and output using these predefined streams can be mixed with input and output using the corresponding FILE objects (stdin, stdout, and stderr). This input and output are correctly synchronized. If you switch between the I/O Stream Library formatted extraction functions and stdio.h functions, you may find that a byte is "lost". The reason is that the formatted extraction functions for integers and floating-point values keep extracting characters until a nondigit character is encountered. This nondigit character acts as a delimiter for the value that preceded it. Because it is not part of the value, putback() is called to return it to the stream buffer. If a C stdio library function, such as getchar(), performs the next input operation, it will begin input at the character after this nondigit character. Thus, this nondigit character is not part of the value extracted by the formatted extraction function, and it is not the character extracted by the C stdio library function. It is "lost". Therefore, you should avoid switching between the I/O Stream Library formatted extraction functions and C stdio library functions whenever possible. sync_with_stdio() makes cout and clog unit buffered. After you call sync_with_stdio(), the performance of your program could diminish. The performance of your program depends on the length of strings, with performance diminishing most when the strings are shortest. Note: You should use I/O Stream Library functions exclusively for all new code. ═══ 4.3.8.3. tie ═══ ostream* tie(); ostream* tie(ostream* os); There are two versions of tie(). The version that takes no arguments returns the value of ios::x_tie, the tie variable. (The tie variable points to the ostream object that is tied to the ios object.) The version that takes one argument os makes the tie variable, ios::x_tie, equal to os and returns the previous value. You can use ios::x_tie to automatically flush the stream buffer attached to an ios object. If ios::x_tie for an ios object is not equal to 0 and the ios object needs more characters or has characters to be consumed, the ostream object pointed to by ios::x_tie is flushed. By default, the tie variables of the predefined streams cin, cerr, and clog all point to the predefined stream cout. The following example illustrates how these streams are tied: // Tying two streams together #include #include void main() { float f; cout << "Enter a number: "; // cin is tied to cout, so cin >> f; // cout is flushed before input cout << "The number was " << f << ".\n" << endl; ofstream myFile; myFile.open("testfile",ios::out); cin.tie(&myFile); // now tie cin to a different ostream cout << "Enter a number: "; // cout is not flushed by cin, cin >> f; // so prompt appears after input. cout << "The number was " << f << ".\n" << endl; } Initially, the program displays a prompt, requests input, and then displays output. After cin is tied to the ofstream myFile, however, the output is not flushed by the request for input, so no prompt is displayed until after the input is received. The output is flushed only by the endl manipulator at the end of the program. The following shows sample output for this program: Enter a number: 5 The number was 5. 6 Enter a number: The number was 6. ═══ 4.3.9. Built-In Manipulators for ios ═══ The I/O Stream Library provides you with a set of built-in manipulators for ios and the classes derived from it. These manipulators have a specific effect on a stream other than inserting or extracting a value. Manipulators implicitly invoke functions that modify the state of the stream, and they allow you to modify the state of a stream at the same time as you are doing input and output. The syntax for manipulators is consistent with the syntax for input and output. The following is a list of the manipulators and the classes that they apply to: dec istream and ostream hex istream and ostream oct istream and ostream ws istream endl ostream ends ostream flush ostream See Built-In Manipulators for istream for more details on the built-in manipulators for istream. See Built-In Manipulators for ostream for more details on the manipulators for ostream. ═══ 4.4. iostream and iostream_withassign Classes ═══ Description Derivation Header File To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.4.1. Class Description - iostream ═══ The iostream class combines the input capabilities of the istream class with the output capabilities of the ostream class. It is the base class for three other classes that also provide both input and output capabilities:  iostream_withassign, also described in this chapter, which you can use to assign another stream (such as an fstream for a file) to an iostream object.  strstream, which is a stream of characters stored in memory.  fstream, which is a stream that supports input and output. ═══ Derivation ═══ ios istream ostream iostream iostream_withassign ═══ Header File ═══ iostream and iostream_withassign are declared in iostream.h. ═══ 4.4.2. Public Members of iostream and iostream_withassign ═══ The following public member functions are described:  iostream constructor  iostream_withassign constructor  iostream_withassign assignment operator ═══ 4.4.2.1. Constructor for iostream ═══ iostream(streambuf* sb); The iostream constructor takes a single argument sb. The constructor creates an iostream object that is attached to the streambuf object that is pointed to by sb. The constructor also initializes the format variables to their defaults. ═══ 4.4.2.2. Constructor for iostream_withassign ═══ iostream_withassign(); The iostream_withassign constructor creates an iostream_withassign object. It does not do any initialization of this object. ═══ 4.4.2.3. Assignment Operator for iostream_withassign ═══ iostream_withassign& operator=(ios& is); iostream_withassign& operator=(streambuf* sb); There are two versions of the iostream_withassign assignment operator. The first version takes a reference to an ios object, is, as its argument. It associates the stream buffer attached to is with the iostream_withassign object that is on the left side of the assignment operator. The second version of the iostream_withassign assignment operator takes a pointer to a streambuf object, sb, as its argument. It associates this streambuf object with the iostream_withassign object that is on the left side of the assignment operator. ═══ 4.5. istream and istream_withassign Classes ═══ Description Derivation Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.5.1. Class Description - istream ═══ This chapter describes the istream class and its derived class istream_withassign. You can use the istream member functions to take characters out of the stream buffer that is associated with an istream object. istream_withassign is derived from istream and includes an assignment operator. You can view the topics in this chapter either through the panel on the left, or by selecting from among the following:  Input prefix function  istream members for formatted input  istream members for unformatted input  istream members for positioning  Other public members  Built-in manipulators  istream_withassign class ═══ Derivation ═══ ios istream istream_withassign ═══ Header File ═══ istream and istream_withassign are declared in iostream.h. ═══ Members ═══ The following members are provided for istream and istream_withassign:  Input Prefix Function  Constructors for istream  Public Members of istream for Formatted Input  get  getline  ignore  read  seekg  tellg  gcount  peek  putback  sync  Constructor for istream_withassign  Assignment Operator for istream_withassign ═══ 4.5.2. Constructors for istream ═══ istream(streambuf* sb); The istream constructor takes a single argument sb. The constructor creates an istream object that is attached to the streambuf object that is pointed to by sb. The constructor also initializes the format variables to their defaults. The other istream constructor declarations in iostream.h are obsolete; do not use them. ═══ 4.5.3. Input Prefix Function ═══ int ipfx(int need=0); ipfx() checks the stream buffer attached to an istream object to determine if it is capable of satisfying requests for characters. It returns a nonzero value if the stream buffer is ready, and 0 if it is not. The formatted input operator calls ipfx(0), while the unformatted input functions call ipfx(1). If the error state of the istream object is nonzero, ipfx() returns 0. Otherwise, the stream buffer attached to the istream object is flushed if either of the following conditions is true:  need has a value of 0.  The number of characters available in the stream buffer is fewer than the value of need. If ios::skipws is set in the format state of the istream object and need has a value of 0, leading white-space characters are extracted from the stream buffer and discarded. If ios::hardfail is set or EOF is encountered, ipfx() returns 0. Otherwise, it returns a nonzero value. ═══ 4.5.4. Public Members of istream for Formatted Input ═══ You can use the istream class to perform formatted input from a stream buffer using the input operator >>. Consider the following statement, where ins is a reference to an istream object and x is a variable of a built-in type: ins >> x; The input operator >> calls ipfx(0). If ipfx() returns a nonzero value, the input operator extracts characters from the streambuf object that is associated with ins. It converts these characters to the type of x and stores the result in x. The input operator sets ios::failbit if the characters extracted from the stream buffer cannot be converted to the type of x. If the attempt to extract characters fails because EOF is encountered, the input operator sets ios::eofbit and ios::failbit. If the attempt to extract characters fails for another reason, the input operator sets ios::badbit. Even if an error occurs, the input operator always returns ins. The details of conversion depend on the format state of the istream object and the type of the variable x. The input operator may set the width variable ios::x_width to 0, but it does not change anything else in the format state. The input operator is defined for the following types:  Arrays of character values (including signed char and unsigned char)  Other integral values: short, int, long  float, double, and long double values. In addition, the input operator is defined for streambuf objects. You can also define input operators for your own types. The following sections describe the input operator for these types. Note: The following descriptions assume that the input operator is called with the istream object ins on the left side of the operator. ═══ 4.5.4.1. Input Operator for Arrays of Characters ═══ istream& operator>>(char* pc); istream& operator>>(signed char* pc); istream& operator>>(unsigned char* pc); istream& operator>>(wchar_t* pwc); For pointers to char, signed char, and unsigned char, the input operator stores characters from the stream buffer attached to ins in the array pointed to by pc. The input operator stores characters until a white-space character is found. This white-space character is left in the stream buffer, and the extraction stops. If ios::x_width does not equal zero, a maximum of ios::x_width - 1 characters are extracted. The input operator calls ins.width(0) to reset ios::x_width to 0. For pointers to wchar_t, the input operator stores characters from the stream buffer attached to ins in the array pointed to by pwc. The input operator stores characters until a white-space character or a wchar_t blank is found. If the terminating character is a white-space character, it is left in the stream buffer. If it is a wchar_t blank, it is discarded to avoid returning two bytes to the input stream. For wchar_t* arrays, if ios::width does not equal zero, a maximum of ios::width-1 characters (at 2 bytes each) are extracted. A 2-character space is reserved for the wchar_t terminating null character. Note: The input operators for these types also reset ios::x_width to 0. None of the other input operators affects ios::x_width. All of the output operators except those for the char types and wchar_t, on the other hand, reset ios::x_width to 0. The input operator always stores a terminating null character in the array pointed to by pc or pwc, even if an error occurs. For arrays of wchar_t*, this terminating null character is a wchar_t terminating null character. ═══ 4.5.4.2. Input Operator for char ═══ istream& operator>>(char& rc); istream& operator>>(signed char& rc); istream& operator>>(unsigned char& rc); istream& operator>>(wchar_t& rc); For char, signed char, and unsigned char, the input operator extracts a character from the stream buffer attached to ins and stores it in rc. For references to wchar_t, the input operator extracts a wchar_t character from the stream buffer and stores it in wc. If ios::skipws is set, the input operator skips leading wchar_t spaces as well as leading char white spaces. ═══ 4.5.4.3. Input Operator for Other Integral Values ═══ istream& operator>>(short& ir); istream& operator>>(unsigned short& ir); istream& operator>>(int& ir); istream& operator>>(unsigned int& ir); istream& operator>>(long& ir); istream& operator>>(unsigned long& ir); This section describes how the input operator works for references to the integral types: short, unsigned short, int, unsigned int, long, and unsigned long. For these integral types, the input operator extracts characters from the stream buffer associated with ins and converts them according to the format state of ins. The converted characters are then stored in ir. There is no overflow detection on conversion of integral types. The first character extracted from the stream buffer may be a sign (+ or -). The subsequent characters are converted until a nondigit character is encountered. This nondigit character is left in the stream buffer. Which characters are treated as digits depends on the setting of the following format flags:  ios::oct: the characters are converted to an octal value. Characters are extracted from the stream buffer until a character that is not an octal digit (a digit from 0 to 7) is encountered. If ios::oct is set and a signed value is encountered, the value is converted into a decimal value. For example, if the characters "- 45" are encountered in the input stream and ios::oct is set, the decimal value - 37 is actually extracted.  ios::dec: the characters are converted to a decimal value. Characters are extracted from the stream buffer until a character that is not a decimal digit (a digit from 0 to 9) is encountered.  ios::hex: the characters are converted to a hexadecimal value. Characters are extracted from the stream buffer until a character that is not a hexadecimal digit (a digit from 0 to 9 or a letter from "A" to "F", upper or lower case) is encountered. If ios::hex is set and a signed value is encountered, the value is converted into a decimal value. For example, if the characters "-12" are encountered in the input stream and ios::hex is set, the decimal value -18 is actually extracted. If none of these format flags is set, the characters are converted according to the C++ lexical conventions. This conversion depends on the characters that follow the optional sign:  If these characters are "0x" or "0X", the subsequent characters are converted to a hexadecimal value.  If the first character is "0" and the second character is not "x" or "X", the subsequent characters are converted to an octal value.  If neither of these cases is true, the characters are converted to a decimal value. If no digits are available in the stream buffer (other than the "0" in "0X" or "0x" preceding a hexadecimal value), the input operator sets ios::failbit in the error state of ins. ═══ 4.5.4.4. Input Operator for float and double Values ═══ istream& operator>>(float& ref); istream& operator>>(double& ref); istream& operator>>(long double& ref); For float, double, and long double values, the input operator converts characters from the stream buffer attached to ins according to the C++ lexical conventions. The following conversions occur for certain string values:  If the value consists of the character strings "inf" or "infinity" in any combination of uppercase and lowercase letters, the string is converted to the appropriate type's representation of infinity.  If the value consists of the character string "nan" in any combination of uppercase and lowercase letters, the string is converted to the appropriate type's representation of a NaN. The resulting value is stored in ref. The input operator sets ios::failbit if no digits are available in the stream buffer or if the digits that are available do not begin a floating-point number. ═══ 4.5.4.5. Input Operator for streambuf Objects ═══ istream& operator>>(streambuf* sb); For pointers to streambuf objects, the input operator calls ipfx(0). If ipfx(0) returns a nonzero value, the input operator extracts characters from the stream buffer attached to ins and inserts them in sb. Extraction stops when an EOF character is encountered. The input operator always returns ins. ═══ 4.5.5. Public Members of istream for Unformatted Input ═══ You can use the functions listed in this section to extract characters from a stream buffer as a sequence of bytes. All of these functions call ipfx(1). They only proceed with their processing if ipfx(1) returns a nonzero value. Note: The following descriptions assume that the functions are called as part of an istream object called ins. The following functions are described:  get - Extract characters and store in array  get - Extract characters and store in stream buffer  get - Extract character and store in char  get - Extract character and return it  getline - Extract characters and store in array  ignore - Extract characters and discard them  read - Extract characters and store in array ═══ 4.5.5.1. get ═══ istream& get(char* ptr, int len, char delim='\n'); istream& get(signed char* ptr, int len, char delim='\n'); istream& get(unsigned char* ptr, int len, char delim='\n'); get() with three arguments extracts characters from the stream buffer attached to ins and stores them in the byte array beginning at the location pointed to by ptr and extending for len bytes. The default value of the delim argument is '\n'. Extraction stops when either of the following conditions is true:  delim or EOF is encountered before len-1 characters have been stored in the array. delim is left in the stream buffer and not stored in the array.  len-1 characters are extracted without delim or EOF being encountered. get() always stores a terminating null character in the array, even if it does not extract any characters from the stream buffer. get() sets the ios::failbit if it encounters an EOF character before it stores any characters. ═══ 4.5.5.2. get ═══ istream& get(streambuf& sb, char delim='\n'); get() with two arguments extracts characters from the stream buffer attached to ins and stores them in sb. The default value of the delim argument is "\n". Extraction stops when any of the following conditions is true:  An EOF character is encountered.  An attempt to store a character in sb fails. ios::failbit is set in the error state of ins.  delim is encountered. delim is left in the stream buffer attached to ins. ═══ 4.5.5.3. get ═══ istream& get(char& cref); istream& get(signed char& cref); istream& get(unsigned char& cref); istream& get(wchar_t& cref); get() with a single argument extracts a single character or wchar_t from the stream buffer attached to ins and stores this character in cref. ═══ 4.5.5.4. get ═══ int get(); get() with no arguments extracts a character from the stream buffer attached to ins and returns it. This version of get() returns EOF if EOF is extracted. ios::failbit is never set. ═══ 4.5.5.5. getline ═══ istream& getline(char* ptr, int len, char delim='\n'); istream& getline(signed char* ptr, int len, char delim='\n'); istream& getline(unsigned char* ptr, int len, char delim='\n'); getline() extracts characters from the stream buffer attached to ins and stores them in the byte array beginning at the location pointed to by ptr and extending for len bytes. The default value of the delim argument is "\n". Extraction stops when any one of the following conditions is true:  delim or EOF is encountered before len-1 characters have been stored in the array. getline() extracts delim from the stream buffer, but it does not store delim in the array.  len-1 characters are extracted before delim or EOF is encountered. getline() always stores a terminating null character in the array, even if it does not extract any characters from the stream buffer. getline() sets the ios::failbit for ins if it encounters an EOF character before it stores any characters. getline() is like get() with three arguments, except that get() does not extract the delim character from the stream buffer, while getline() does. See White Space in String Input in the Open Class Library User's Guide for an example of using the getline() function. ═══ 4.5.5.6. ignore ═══ istream& ignore(int num=1, int delim=EOF); ignore() extracts up to num character from the stream buffer attached to ins and discards them. ignore() will extract fewer than num characters if it encounters delim or EOF. ═══ 4.5.5.7. read ═══ istream& read(char* s, int n); istream& read(signed char* s, int n); istream& read(unsigned char* s, int n); read() extracts n characters from the stream buffer attached to ins and stores them in an array beginning at the position pointed to by s. If EOF is encountered before read() extracts n characters, read() sets the ios::failbit in the error state of ins. You can determine the number of characters that read() extracted by calling gcount() immediately after the call to read(). ═══ 4.5.6. Public Members of istream for Positioning ═══ The following functions are described:  seekg - reposition get pointer of ultimate producer  tellg - return position of get pointer of ultimate producer ═══ 4.5.6.1. seekg ═══ istream& seekg(streampos sp); istream& seekg(streamoff so, ios::seek_dir dir); seekg() repositions the get pointer of the ultimate producer. seekg() with one argument sets the get pointer to the position sp. seekg() with two arguments sets the get pointer to the position specified by dir with the offset so. dir can have the following values:  ios::beg: the beginning of the stream  ios::cur: the current position of the get pointer  ios::end: the end of the stream If you attempt to set the get pointer to a position that is not valid, seekg() sets ios::badbit. ═══ 4.5.6.2. tellg ═══ streampos tellg(); tellg() returns the current position of the get pointer of the ultimate producer. ═══ 4.5.7. Other Public Members of istream ═══ Note: The following descriptions assume that the functions are called as part of an istream object called ins. The following member functions are described:  gcount - Return number of characters extracted  peek - Return next character without extracting it  putback - Put extracted characters back into stream buffer  sync - Synchronize stream buffer and ultimate producer ═══ 4.5.7.1. gcount ═══ int gcount(); gcount() returns the number of characters extracted from the stream buffer attached to ins by the last call to an unformatted input function. The input operator >> may call unformatted input functions, and thus formatted input may affect the value returned by gcount(). ═══ 4.5.7.2. peek ═══ int peek(); peek() calls ipfx(1). If ipfx() returns zero, or if no more input is available from the ultimate producer, peek() returns EOF. Otherwise, it returns the next character in the stream buffer attached to ins without extracting the character. ═══ 4.5.7.3. putback ═══ istream& putback(char c); putback() attempts to put a character that was extracted from the stream buffer attached to ins back into the stream buffer. c must equal the character before the get pointer of the stream buffer. Unless some other activity is modifying the stream buffer, this is the last character extracted from the stream buffer. If c is not equal to the character before the get pointer, the result of putback() is undefined, and the error state of ins may be set. putback() does not call ipfx(), but if the error state of ins is nonzero, putback() returns without putting back the character or setting the error state. ═══ 4.5.7.4. sync ═══ int sync(); sync() establishes consistency between the ultimate producer and the stream buffer attached to ins. sync() calls ins.rdbuf()->sync(), which is a virtual function, so the details of its operation depend on the way the function is defined in a given derived class. If an error occurs, sync() returns EOF. ═══ 4.5.8. Built-In Manipulators for istream ═══ istream& ws(istream&); ios& dec(ios&); ios& hex(ios&); ios& oct(ios&); The I/O Stream Library provides you with a set of built-in manipulators that can be used with the istream class. These manipulators have a specific effect on an istream object beyond extracting their own values. The built-in manipulators are accepted by the following versions of the input operator: istream& operator>> (istream& (*f) (istream&)); istream& operator>> (ios& (*f) (ios&)); If ins is a reference to an istream object, this statement extracts white-space characters from the stream buffer attached to ins: ins >> ws; This statement sets ios::dec: ins >> dec; This statement sets ios::hex: ins >> hex; This statement sets ios::oct: ins >> oct; ═══ 4.5.9. Public Members of istream_withassign ═══ Description To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.5.10. Class Description - istream_withassign ═══ There are two public member functions of istream_withassign:  istream_withassign constructor  istream_withassign assignment operator ═══ 4.5.10.1. Constructor for istream_withassign ═══ istream_withassign(); The istream_withassign constructor creates an istream_withassign object. It does not do any initialization of this object. ═══ 4.5.10.2. Assignment Operator for istream_withassign ═══ istream_withassign& operator=(istream& is); istream_withassign& operator=(streambuf* sb); There are two versions of the istream_withassign assignment operator. The first version takes a reference to an istream object, is, as its argument. It associates the stream buffer attached to is with the istream_withassign object that is on the left side of the assignment operator. The second version of the assignment operator takes a pointer to a streambuf object, sb, as its argument. It associates this streambuf object with the istream_withassign object that is on the left side of the assignment operator. ═══ 4.6. Manipulators ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.6.1. Class Description - IOMANIP ═══ This chapter describes the parameterized manipulators provided by the I/O Stream Library and the facilities you can use to declare your own manipulators. ═══ Derivation ═══ The manipulator classes are defined by a set of macros, and take names as defined when you use the macros. See the section on manipulators in the Open Class Library User's Guide for further information. ═══ Header File ═══ The parameterized manipulator classes are declared in iomanip.h. ═══ 4.6.2. Parameterized Manipulators for the Format State ═══ The iomanip.h header file also contains calls to the IOMANIPdeclare() macro for types int and long. These calls create classes that are used to create the parameterized manipulators that control the format state of ios objects. The call to IOMANIPdeclare(int) creates classes with names that are expanded from the following macros:  SMANIP(int)  SAPP(int)  IMANIP(int)  IAPP(int)  OMANIP(int)  OAPP(int)  IOMANIP(int)  IOAPP(int) All of these macros expand to names that include the string "int". Similarly, IOMANIPdeclare(long) creates eight classes whose names include the string "long". The following manipulators are declared using the classes created by the calls to IOMANIPdeclare(int) and IOMANIPdeclare(long). Note: All of the parameterized manipulators described below are defined for both istream and ostream objects. In the following descriptions, is is a reference to an istream object and os is a reference to an ostream object. The following manipulators are described:  resetiosflags - clear format flags  setbase - set conversion base  setfill - set fill character  setiosflags - set format flags  setprecision - set precision  setw - set field width ═══ 4.6.2.1. resetiosflags ═══ SMANIP(long) resetiosflags(long flags); resetiosflags() clears the format flags specified in flags. It can appear in an input stream: is >> resetiosflags(flags); In this case, resetiosflags() calls is.setf(0,flags). resetiosflags() can also appear in an output stream: os << resetiosflags(flags); In this case, resetiosflags calls os.setf(0,flags). ═══ 4.6.2.2. setbase ═══ SMANIP(int) setbase(int base); setbase() sets the conversion base to be equal to the value of the argument base. If base equals 10, the conversion base is set to 10. If base equals 8, the conversion base is set to 8. If base equals 16, the conversion base is set to 16. Otherwise, the conversion base is set to 0. If the conversion base is 0, output is treated the same as if the base were 10, but input is interpreted according to the C++ lexical conventions. This means that input values that begin with "0" are interpreted as octal values, and values that begin with "0x" or "0X" are interpreted as hexadecimal values. ═══ 4.6.2.3. setfill ═══ SMANIP(int) setfill(int fill); setfill() sets the fill character, ios::x_fill, to fill. The fill character is the character that appears in values that need to be padded to fill the field width. setfill() can appear in either an input stream or an output stream: is >> setfill(fill); os << setfill(fill); setfill() performs the same task as the function fill(). ═══ 4.6.2.4. setiosflags ═══ SMANIP(long) setiosflags(long flags); setiosflags() sets the format flags specified in flags. setiosflags() can appear in an input stream: is >> setiosflags(flags); If it appears in an input stream, setiosflags() calls is.setf.(flags) If it appears in an output stream, setiosflags() calls os.setf(flags): os << setiosflags(flags); ═══ 4.6.2.5. setprecision ═══ SMANIP(int) setprecision(int prec); setprecision() sets the precision format state variable, ios::x_prec, to the value of prec. The value of prec must be greater than zero. If the value of prec is negative, the precision format state variable is set to 6. setprecision() can appear in either an input stream or an output stream: is >> setprecision(prec); os << setprecision(prec); ═══ 4.6.2.6. setw ═══ SMANIP(int) setw(int width); setw() sets the width format state variable, ios::x_width, to the value of width. setw() can appear in either an input stream or an output stream: is >> setw(width); os << setw(width); ═══ 4.7. ostream and ostream_withassign Classes ═══ Description Derivation Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.7.1. Class Description - ostream ═══ This chapter describes the ostream class and its derived class ostream_withassign. You can use the ostream member functions to put characters into the streambuf object that is associated with an ostream object. ostream_withassign is derived from ostream and includes an assignment operator. You can view the topics in this chapter either through the panel on the left, or by selecting from among the following:  Output prefix and suffix functions  Members for formatted output  Members for unformatted output  Members for positioning  Other public members  Built-in manipulators  ostream_withassign class ═══ Derivation ═══ ios ostream ostream_withassign ═══ Header File ═══ ostream and ostream_withassign are declared in iostream.h. ═══ Members ═══ The following members are provided for ostream and ostream_withassign:  Constructors for ostream  Output Operator for Arrays of Characters and char Values  Constructor for ostream_withassign  Assignment Operator for ostream_withassign  flush  opfx  osfx  put  seekp  tellp  write ═══ 4.7.2. Constructors for ostream ═══ Class: ostream ostream(streambuf* sb); The ostream constructor takes a single argument, sb, which is a pointer to a streambuf object. The constructor creates an ostream object that is attached to the streambuf object pointed to by sb. The constructor also initializes the format variables to their defaults. The other declarations for the ostream constructor in iostream.h are obsolete; do not use them. ═══ 4.7.3. Output Prefix and Suffix Functions ═══ The output operator calls the output prefix function opfx() before inserting characters into a stream buffer, and calls the output suffix function osfx() after inserting characters. The following descriptions assume the functions are called as part of an ostream object called os. ═══ 4.7.3.1. opfx ═══ int opfx(); opfx() is called by the output operator before inserting characters into a stream buffer. opfx() checks the error state of os. If the internal flag ios::hardfail is set, opfx() returns 0. Otherwise, opfx() flushes the stream buffer attached to the ios object pointed to by os.tie(), if one exists, and returns the value returned by ios::good(). ios::good() returns 0 if ios::failbit, ios::badbit, or ios::eofbit is set. Otherwise, ios::good() returns a nonzero value. ═══ 4.7.3.2. osfx ═══ void osfx(); osfx() is called before a formatted output function returns. osfx() flushes the streambuf object attached to os if ios::unitbuf is set. osfx() is called by the output operator. If you overload the output operator to handle your own classes, you should ensure that osfx() is called after any direct manipulation of a streambuf object. Binary output functions do not call osfx(). ═══ 4.7.4. Public Members of ostream for Formatted Output ═══ The ostream class lets you use the output operator << to perform formatted output (or insertion) to a stream buffer. Consider the following statement, where outs is a reference to an ostream object and x is a variable of a built-in type: outs << x; The output operator << calls opfx() before beginning insertion. If opfx() returns a nonzero value, the output operator converts x into a series of characters and inserts these characters into the stream buffer attached to outs. If an error occurs, the output operator sets ios::failbit. The details of the conversion of x depend on the format state of the ostream object and the type of x. For numeric and string values, including the char* types and wchar_t*, but excluding the char types and wchar_t, the output operator resets the width variable ios::x_width of the format state of an ostream object to 0, but it does not affect anything else in the format state. The output operator is defined for the following types:  Arrays of characters and char values, including arrays of wchar_t and wchar_t values.  Other integral values: short, int, long  float, double and long double values  Pointers to void The following sections describe the output operators for these types. The output operator is also defined for streambuf objects. You can also define output operators for your own types. Note: The following descriptions assume that the output operator is called with the ostream object outs on the left side of the operator. ═══ 4.7.4.1. Output Operator for Arrays of Characters and char Values ═══ ostream& operator<<(const char* cp); ostream& operator<<(const signed char* cp); ostream& operator<<(const unsigned char* cp); ostream& operator<<(wchar_t); ostream& operator<<(char ch); ostream& operator<<(signed char ch); ostream& operator<<(unsigned char ch); ostream& operator<<(const wchar_t *); For a pointer to a char, signed char, or unsigned char value, the output operator inserts all the characters in the string into the stream buffer with the exception of the null character that terminates the string. For a pointer to a wchar_t, the output operator converts the wchar_t string to its equivalent multibyte character string, and then inserts it into the stream buffer except for the null character that terminates the string. If ios::x_width is greater than zero and the representation of the value to be inserted is less than ios::x_width, the output operator inserts enough fill characters to ensure that the representation occupies an entire field in the stream buffer. The output operator does not perform any conversion on char, signed char, unsigned char, or wchar_t values. ═══ 4.7.4.2. Output Operator for Other Integral Values ═══ ostream& operator<<(short iv); ostream& operator<<(unsigned short iv); ostream& operator<<(int iv); ostream& operator<<(unsigned int iv); ostream& operator<<(long iv); ostream& operator<<(unsigned long iv); ostream& operator<<(long long iv); ostream& operator<<(unsigned long long iv); Note: The last two operators above are only available when the compiler is in a mode that supports the long long data type. For the integral types (short, unsigned short, int, unsigned int, long, and unsigned long), the output operator converts the integral value iv according to the format state of outs and inserts characters into the stream buffer associated with outs. There is no overflow detection on conversion of integral types. The conversion that takes place on iv depends, in part, on the settings of the following format flags:  If ios::oct is set, iv is converted to a series of octal digits. If ios::showbase is set, "0" is inserted into the stream buffer before the octal digits. If the value being inserted is equal to 0, a single "0" is inserted, not "00".  If ios::dec is set, iv is converted to a series of decimal digits.  If ios::hex is set, iv is converted to a series of hexadecimal digits. If ios::showbase is set, "0x" (or "0X" if ios::uppercase is set) is inserted into the stream buffer before the hexadecimal digits. If none of these format flags is set, iv is converted to a series of decimal digits. If iv is converted to a series of decimal digits, its sign also affects the conversion:  If iv is negative, a negative sign "-" is inserted before the decimal digits.  If iv is equal to 0, the single digit 0 is inserted.  If iv is positive and ios::showpos is set, a positive sign "+" is inserted before the decimal digits. ═══ 4.7.4.3. Output Operator for float and double Values ═══ ostream& operator<<(float val); ostream& operator<<(double val); ostream& operator<<(long double val); The output operator performs a conversion operation on the value val and inserts it into the stream buffer attached to outs. The conversion depends on the values returned by the following functions:  outs.precision(): returns the number of significant digits that appear after the decimal. The default value is 6.  outs.width(): if this returns 0, val is inserted without any fill characters. If the return value is greater than the number of characters needed to represent val, extra fill characters are inserted so that the total number of characters inserted is equal to the return value. The conversion also depends on the values of the following format flags:  If ios::scientific is set, val is converted to scientific notation, with one digit before the decimal, and the number of digits after the decimal equal to the value returned by outs.precision(). The exponent begins with a lowercase "e" unless ios::uppercase is set, in which case the exponent begins with an uppercase "E".  If ios::fixed is set, val is converted to fixed notation, with the number of digits after the decimal point equal to the value returned by outs.precision(). If neither ios::fixed nor ios::scientific is set, the conversion depends upon the value of val. See Floating-Point Formatting for more details.  If ios::uppercase is set, the exponents of values in scientific notation begin with an uppercase "E". See Format State Flags for more details on the format state. ═══ 4.7.4.4. Output Operator for Pointers to void ═══ ostream& operator<<(void* vp); The output operator converts pointers to void to integral values and then converts them to hexadecimal values as if ios::showbase were set. This version of the output operator is used to print out the values of pointers. ═══ 4.7.4.5. Output Operator for streambuf Objects ═══ ostream& operator<<(streambuf* sb); If opfx() returns a nonzero value, the output operator inserts all of the characters that can be taken from sb into the stream buffer attached to outs. Insertion stops when no more characters can be fetched from sb. No padding is performed. The return value is outs. ═══ 4.7.5. Public Members of ostream for Unformatted Output ═══ You can use the functions listed in this section to insert characters into a stream buffer without regard to the type of the values that the characters represent. Note: The following descriptions assume that the functions are called as part of an ostream object called outs. The following functions are described:  put - insert a single character  write - insert an array of characters ═══ 4.7.5.1. put ═══ ostream& put(char c); put() inserts c in the stream buffer attached to outs. put() sets the error state of outs if the insertion fails. ═══ 4.7.5.2. write ═══ ostream& write(const char* cp, int n); ostream& write(const signed char* cp, int n); ostream& write(const unsigned char* cp, int n); write() inserts the n characters that begin at the position pointed to by cp. This array of characters does not need to end with a null character. ═══ 4.7.6. Public Members of ostream for Positioning ═══ Note: The following descriptions assume that the functions are called as part of an ostream object called outs. The following functions are described:  seekp - reposition put pointer of ultimate consumer  tellp - return position of put pointer of associated stream buffer ═══ 4.7.6.1. seekp ═══ ostream& seekp(streampos sp); ostream& seekp(streamoff so, ios::seek_dir dir); seekp() repositions the put pointer of the ultimate consumer. seekp() with one argument sets the put pointer to the position sp. seekp() with two arguments sets the put pointer to the position specified by dir with the offset so. dir can have the following values:  ios::beg: the beginning of the stream  ios::cur: the current position of the put pointer  ios::end: the end of the stream The new position of the put pointer is equal to the position specified by dir offset by the value of so. If you attempt to move the put pointer to a position that is not valid, seekp() sets ios::badbit. ═══ 4.7.6.2. tellp ═══ streampos tellp(); tellp() returns the current position of the put pointer of the stream buffer that is attached to outs. ═══ 4.7.7. Other Public Members of ostream ═══ :link auto dependent refid=cscl066 reftype=hd . In this section, the following function is described: flush - clear associated stream buffer ═══ 4.7.7.1. flush ═══ ostream& flush(); The ultimate consumer of characters that are stored in a stream buffer may not necessarily consume them immediately. flush() causes any characters that are stored in the stream buffer attached to outs to be consumed. It calls outs.rdbuf()->sync() to accomplish this action. ═══ 4.7.8. Built-In Manipulators for ostream ═══ ostream& endl(ostream& i); ostream& ends(ostream& i); ostream& flush(ostream&); ios& dec(ios&); ios& hex(ios&); ios& oct(ios&); The I/O Stream Library provides you with a set of built-in manipulators that can be used with the ostream class. These manipulators have a specific effect on an ostream object beyond extracting their own values. The built-in manipulators are accepted by the following versions of the output operators: ostream& operator<<(ostream& (*f)(ostream&)); ostream& operator<<(ios& (*f)(ios&) ); If outs is a reference to an ostream object, then this statement inserts a newline character and calls flush(). outs << endl; This statement inserts a null character: outs << ends; This statement flushes the stream buffer attached to outs. It is equivalent to flush() outs << flush; This statement sets ios::dec: outs << dec; This statement sets ios::hex: outs << hex; This statement sets ios::oct: outs << oct; ═══ 4.7.9. Public Members of ostream_withassign ═══ Description To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.7.10. Class Description - ostream_withassign ═══ There are two public members of ostream_withassign:  ostream_withassign constructor  ostream_withassign assignment operator ═══ 4.7.10.1. Constructor for ostream_withassign ═══ ostream_withassign(); The ostream_withassign constructor creates an ostream_withassign object. It does not do any initialization on the object. ═══ 4.7.10.2. Assignment Operator for ostream_withassign ═══ ostream_withassign& operator=(ostream& os); ostream_withassign& operator=(streambuf* sb); There are two versions of the ostream_withassign assignment operator. The first version takes a reference to an ostream object, os, as its argument. It associates the streambuf attached to os with the ostream_withassign object that is on the left side of the assignment operator. The second version of the assignment operator takes a pointer to a streambuf object, sb, as its argument. It associates sb with the ostream_withassign object that is on the left side of the assignment operator. ═══ 4.8. stdiobuf and stdiostream Classes ═══ Description Derivation Header File Members Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.8.1. Class Description - stdiobuf ═══ This chapter describes the stdiobuf class and stdiostream, the class that uses stdiobuf objects as stream buffers. Operations on an stdiobuf are mirrored on the associated FILE structure (defined in the C header file stdio.h). Note: The classes described in this chapter are meant to be used when you have to mix C code with C++ code. If you are writing new C++ code, use filebuf, fstream, ifstream, and ofstream instead of stdiobuf and stdiostream. See sync_with_stdio for information on synchronizing stdio.h input and output with I/O Stream Library input and output. ═══ Derivation ═══ ios stdiostream streambuf stdiobuf ═══ Header File ═══ stdiobuf and stdiostream are declared in stdiostr.h. ═══ Members ═══ The following members are provided for stdiobuf and stdiostream:  Constructor for stdiobuf  Destructor for stdiobuf  stdiofile  Constructor for stdiostream  rdbuf ═══ 4.8.2. Public Members of stdiobuf ═══ The following members are described:  Constructor for stdiobuf  Destructor for stdiobuf  stdiofile ═══ 4.8.2.1. Constructor for stdiobuf ═══ stdiobuf(FILE* f); The stdiobuf constructor creates an stdiobuf object that is associated with the FILE pointed to by f. Changes that are made to the stream buffer in an stdiobuf object are also made to the associated FILE pointed to by f. Note: If ios::stdio is set in the format state of an ostream object, a call to osfx() flushes stdout and stderr. ═══ 4.8.2.2. Destructor for stdiobuf ═══ ~stdiobuf(); The stdiobuf destructor frees space allocated by the stdiobuf constructor and flushes the file that this stdiobuf object is associated with. ═══ 4.8.2.3. stdiofile ═══ FILE* stdiofile(); stdiofile() returns a pointer to the FILE object that the stdiobuf object is associated with. ═══ 4.8.3. Public Members of stdiostream ═══  Constructor for stdiostream  rdbuf ═══ 4.8.3.1. Constructor for stdiostream ═══ stdiostream(FILE* file); The stdiostream constructor creates a stdiostream object that is attached to the FILE pointed to by file. ═══ 4.8.3.2. rdbuf ═══ stdiobuf* rdbuf(); rdbuf() returns a pointer to the stdiobuf object that is attached to the stdiostream object. ═══ 4.8.3.3. Example of Using stdiostream ═══ The following example shows how you can use the stdiostream class. Two files are opened using fopen(). The pointers to the FILE structures are then used to create stdiostream objects. Finally, the contents of one of these stdiostream objects are copied into the other stdiostream object. #include #include #include void main() { FILE *in = fopen("in.dat", "r"); FILE *out = fopen("out.dat", "w"); int c; if (in == NULL) { cerr << "Cannot open file 'in.dat' for reading." << endl; exit(1); } if (out == NULL) { cerr << "Cannot open file 'out.dat' for writing." << endl; exit(1); } // // Create a stdiostream object attached to "f" // stdiostream sin(in); stdiostream sout(out); cout << "The data contained in the file is: " << endl; // // Now read data from "sin" and copy it to // "cout" and "sout" // while ((c = sin.rdbuf()->sbumpc()) != EOF) { cout << char(c); sout.rdbuf()->sputc(c); } cout << endl; } If you run this example with an input file containing the following: input input input input The following output is produced: The data contained in the file is: input input input input ═══ 4.9. streambuf Class ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.9.1. Class Description - streambuf ═══ You can use the streambuf class to manipulate objects of its derived classes filebuf, stdiobuf, and strstreambuf, or to derive other classes from it. You can view the topics in this chapter either through the panel on the left, or by selecting from among the following:  streambuf Public and protected interfaces  Public members  Functions that return pointers  Functions that set pointers  Other nonvirtual functions  Virtual functions ═══ Derivation ═══ streambuf is the base class for strstream, stdiobuf, and filebuf. It is not derived from any class. ═══ Header File ═══ streambuf is declared in iostream.h. ═══ Members ═══ The following members are provided for streambuf:  Constructors for streambuf  Destructor for streambuf  allocate  base  blen  dbp  doallocate  eback  ebuf  egptr  epptr  gbump  gptr  in_avail  out_waiting  overflow  pbackfail  pbase  pbump  pptr  sbumpc  seekoff  seekpos  setb  setbuf  setg  setp  sgetc  sgetn  snextc  sputbackc  sputc  sputn  stossc  sync  unbuffered  underflow ═══ 4.9.2. streambuf Public and Protected Interfaces ═══ streambuf has both a public interface and a protected interface. You should think of these two interfaces as being two separate classes, because the interfaces are used for different purposes. You should also treat streambuf as if it were defined as a virtual base class. Do not create objects of the streambuf class itself. This section describes the ways you can use the two interfaces of streambuf. Although most virtual functions are declared public, you should overload them in the classes that you derive from streambuf, and consider them part of the protected interface. What is the streambuf public interface? What is the streambuf protected interface? ═══ 4.9.2.1. What is the streambuf Public Interface? ═══ You should not create objects of the streambuf public interface directly. Instead, you should use streambuf through one of the predefined classes derived from streambuf. You can use objects of filebuf, strstreambuf and stdiobuf (the predefined classes derived from streambuf) directly as implementations of stream buffers. The public interface consists of the streambuf public member functions that can be called on objects of these predefined classes. streambuf itself does not have any facilities for taking characters from the ultimate producer or sending them to the ultimate consumer. The specialized member functions that handle the interface with the ultimate producer and the ultimate consumer are defined in filebuf, strstreambuf and stdiobuf. Except for the destructor of the streambuf class, the virtual functions are described as part of the protected interface. ═══ 4.9.2.2. What is the streambuf Protected Inteface? ═══ Use the streambuf protected interface in the following ways:  As a base class to implement your own specialized stream buffers. In this sense you can think of streambuf as a virtual base class. The streambuf class only provides the basic functions needed to manipulate characters in a stream buffer. The filebuf, strstreambuf and stdiobuf classes contain functions that handle the interface with the standard ultimate consumers and producers. If you want to perform more sophisticated operations, or if you want to use other ultimate consumers and ultimate producers, you will have to create your own class derived from streambuf. You need to know about the protected interface if you want to create a class derived from streambuf.  Through a predefined class derived from streambuf. There are two kinds of functions in the protected interface:  Nonvirtual member functions, which manipulate streambuf objects at a level of detail that would be inappropriate in the public interface.  Virtual member functions, which permit classes that you derive from streambuf to customize their operations depending on the ultimate producer or ultimate consumer. When you define the virtual functions in your derived classes, you must ensure that these definitions fulfill the conditions stated in the descriptions of the virtual functions. If your definitions of the virtual functions do not fulfill these conditions, objects of the derived class may have unspecified behavior. Although most virtual functions are declared as public members, they are described with the protected interface (with the exception of the destructor for the streambuf class) because they are meant to be overridden in the classes that you derive from streambuf. ═══ 4.9.3. Public Members of the streambuf Public Interface ═══ Note: The following descriptions assume that the functions are called as part of an object fb of a class derived from streambuf. fb could, for example, be an object of the class filebuf. It could also be an strstreambuf object or an stdiobuf object. The following member functions are described:  Constructors for streambuf  Destructor for streambuf  in_avail - Return Number of Characters in Get Area  out_waiting - Return Number of Characters in Put Area  sbumpc - Move Get Pointer One Character  sgetc - Return Character After Get Pointer  sgetn - Return Characters Following Get Pointer  snextc - Return Character Following Get Pointer  sputbackc - Move Get Pointer Back One Character  sputc - Store Character After Put Pointer  sputn - Store Characters After Put Pointer  stossc - Move Get Pointer Forward One Character ═══ 4.9.3.1. Constructors for streambuf ═══ streambuf(); streambuf(char* buffer, int len); streambuf(char* buffer, int len, int c); // obsolete There are three versions of the constructor for streambuf. The version with no arguments constructs an empty stream buffer corresponding to an empty sequence. The values returned by base(), eback(), ebuf(), egptr(), epptr(), pptr(), gptr(), and pbase() are initially all zero for this stream buffer. The version with two arguments constructs an empty stream buffer of length len starting at the position pointed to by buffer. The version of the constructor with three arguments is obsolete. It is included in the I/O Stream Library for compatibility with the AT&T C++ Language System Release 1.2. ═══ 4.9.3.2. Destructor for streambuf ═══ virtual ~streambuf(); The destructor for streambuf calls sync(). If a stream buffer has been set up and ios::alloc is set, sync() deletes the stream buffer. ═══ 4.9.3.3. in_avail ═══ int in_avail(); in_avail() returns the number of characters that are available to be extracted from the get area of fb. You can extract the number of characters equal to the value that in_avail() returns without causing an error. ═══ 4.9.3.4. out_waiting ═══ int out_waiting(); out_waiting() returns the number of characters that are in the put area waiting to be sent to the ultimate consumer. ═══ 4.9.3.5. sbumpc ═══ int sbumpc(); sbumpc() moves the get pointer past one character and returns the character that it moved past. sbumpc() returns EOF if the get pointer is already at the end of the get area. ═══ 4.9.3.6. sgetc ═══ int sgetc(); sgetc() returns the character after the get pointer without moving the get pointer itself. If no character is available, sgetc() returns EOF. Note: sgetc() does not change the position of the get pointer. ═══ 4.9.3.7. sgetn ═══ int sgetn(char* ptr, int n); sgetn() extracts the n characters following the get pointer, and copies them to the area starting at the position pointed to by ptr. If there are fewer than n characters following the get pointer, sgetn() takes the characters that are available and stores them in the position pointed to by ptr. sgetn() repositions the get pointer following the extracted characters and returns the number of extracted characters. ═══ 4.9.3.8. snextc ═══ int snextc(); snextc() moves the get pointer forward one character and returns the character following the new position of the get pointer. snextc() returns EOF if the get pointer is at the end of the get area either before or after it is moved forward. ═══ 4.9.3.9. sputbackc ═══ int sputbackc(char c); sputbackc() moves the get pointer back one character. The get pointer may simply move, or the ultimate producer may rearrange the internal data structures so that the character c is saved. The argument c must equal the character that precedes the get pointer in the stream buffer. The effect of sputbackc() is undefined if c is not equal to the character before the get pointer. sputbackc() returns EOF if an error occurs. The conditions that cause errors depend on the derived class. ═══ 4.9.3.10. sputc ═══ int sputc(int c); sputc() stores the argument c after the put pointer and moves the put pointer past the stored character. If there is enough space in the stream buffer, this will extend the size of the put area. sputc() returns EOF if an error occurs. The conditions that cause errors depend on the derived class. ═══ 4.9.3.11. sputn ═══ int sputn(const char* s, int n); sputn() stores the n characters starting at s after the put pointer and moves the put pointer to the end of the series. sputn() returns the number of characters successfully stored. If an error occurs, sputn() returns a value less than n. ═══ 4.9.3.12. stossc ═══ void stossc(); stossc() moves the get pointer forward one character. If the get pointer is already at the end of the get area, stossc() does not move it. ═══ 4.9.4. Protected Functions That Return Pointers ═══ This section describes the functions in the protected interface of streambuf that return pointers to boundaries of areas in a stream buffer. Note: The following descriptions assume that the functions are called as part of an object called dsb, which is an object of a class that is derived from streambuf. The following functions are described:  base - Return pointer to beginning of stream buffer  eback - Return pointer to beginning of putback area  ebuf - Return pointer to end of stream buffer  egptr - Return pointer to end of get area  epptr - Return pointer to end of put area  gptr - Return pointer to beginning of get area  pbase - Return pointer to beginning of space available for put area  pptr - Return pointer to beginning of put area ═══ 4.9.4.1. base ═══ char* base(); base() returns a pointer to the first byte of the stream buffer. The stream buffer consists of the space between the pointer returned by base() and the pointer returned by ebuf(). ═══ 4.9.4.2. eback ═══ char* eback(); eback() returns a pointer to the lower bound of the space available for the get area of dsb. The space between the pointer returned by eback() and the pointer returned by gptr() is available for putback. ═══ 4.9.4.3. ebuf ═══ char* ebuf(); ebuf() returns a pointer to the byte after the last byte of the stream buffer. ═══ 4.9.4.4. egptr ═══ char* egptr(); egptr() returns a pointer to the byte after the last byte of the get area of dsb. ═══ 4.9.4.5. epptr ═══ char* epptr(); epptr() returns a pointer to the byte after the last byte of the put area of dsb. ═══ 4.9.4.6. gptr ═══ char* gptr(); gptr() returns a pointer to the first byte of the get area of dsb. The get area consists of the space between the pointer returned by gptr() and the pointer returned by egptr(). Characters are extracted from the stream buffer beginning at the character pointed to by gptr(). ═══ 4.9.4.7. pbase ═══ char* pbase(); pbase() returns a pointer to the beginning of the space available for the put area of dsb. Characters between the pointer returned by pbase() and the pointer returned by pptr() have been stored in the stream buffer, but they have not been consumed by the ultimate consumer. ═══ 4.9.4.8. pptr ═══ char* pptr(); pptr() returns a pointer to the beginning of the put area of dsb. The put area consists of the space between the pointer returned by pptr() and the pointer returned by epptr(). ═══ 4.9.5. Protected Functions That Set Pointers ═══ This section describes the functions in the protected interface of streambuf that set the boundaries of areas in a stream buffer. The values of these boundaries are returned by the functions described in Protected Functions That Return Pointers. Note: The following descriptions assume that the functions are called as part of an object called dsb which is an object of a class that is derived from streambuf. The following functions are described:  setb - Set boundaries of stream buffer  setp - Set boundaries of put area  setg - Set boundaries of get area ═══ 4.9.5.1. setb ═══ void setb(char* startbuf, char* endbuf, int delbuf = 0); setb() sets the beginning of the existing stream buffer (the pointer returned by dsb.base()) to the position pointed to by startbuf, and sets the end of the stream buffer (the pointer returned by dsb.ebuf()) to the position pointed to by endbuf. If delbuf is a nonzero value, the stream buffer will be deleted when setb() is called again. If startbuf and endbuf are both equal to 0, no stream buffer is established. If startbuf is not equal to 0, a stream buffer is established, even if endbuf is less than startbuf. If this is the case, the stream buffer has length zero. ═══ 4.9.5.2. setg ═══ void setg(char* startpbk, char* startget, char* endget); setg() sets the beginning of the get area of dsb (the pointer returned by dsb.gptr()) to startget, and sets the end of the get area (the pointer returned by dsb.egptr()) to endget. setg() also sets the beginning of the area available for putback (the pointer returned by dsb.eback()) to startpbk. ═══ 4.9.5.3. setp ═══ void setp(char* startput, char* endput); setp()sets the spaces available for the put area. Both the start (pbase()) and the beginning (pptr()) of the put area are set to the value startput. See figure The Structure of Stream Buffers for details on where each of these functions points to within the stream buffer. setp() sets the beginning of the put area of dsb (the pointer returned by dsb.pptr()) to the position pointed to by startput, and sets the end of the put area (the pointer returned by dsb.epptr()) to the position pointed to by endput. ═══ 4.9.6. Other Nonvirtual Protected Member Functions ═══ This section describes the remaining nonvirtual member functions that make up the protected interface of streambuf. Note: The following descriptions assume that the functions are called as part of an object called dsb which is an object of a class that is derived from streambuf. The following functions are described:  allocate - Set up a stream buffer  blen - Return length of stream buffer  dbp - Record stream buffer status  gbump - Move beginning of get area  pbump - Move beginning of put area  unbuffered - Buffering state ═══ 4.9.6.1. allocate ═══ int allocate(); allocate() attempts to set up a stream buffer. allocate() returns the following values:  0, if dsb already has a stream buffer set up (that is, dsb->base() returns a nonzero value), or if unbuffered() returns a nonzero value. allocate() does not do any further processing if it returns 0.  1, if allocate() does set up a stream buffer.  EOF, if the attempt to allocate space for the stream buffer fails. allocate() is not called by any other nonvirtual member function of streambuf. ═══ 4.9.6.2. blen ═══ int blen() const; blen() returns the length (in bytes) of the stream buffer. ═══ 4.9.6.3. dbp ═══ void dbp(); dbp() writes to standard output the values returned by the following functions:  base()  eback()  ebuf()  egptr()  epptr()  gptr()  pptr() dbp() is intended for debugging. streambuf does not specify anything about the form of the output. dbp() is considered part of the protected interface because the information that it prints can only be understood in relation to that interface. It is declared as a public function so that it can be called anywhere during debugging. The following example shows the output produced by dbp() when it is called as part of a filebuf object: #include void main() { cout << "Here is some sample output." << endl; cout.rdbuf()->dbp(); } If you compile and run this example, your output will look like this: Here is some sample output. buf at 0x90210, base=0x91010, ebuf=0x91410, pptr=0x91010, epptr=0x91410, eback=0, gptr=0, egptr=0 ═══ 4.9.6.4. gbump ═══ void gbump(int offset); gbump() offsets the beginning of the get area by the value of offset. The value of offset can be positive or negative. gbump() does not check to see if the new value returned by gptr() is valid. The beginning of the get area is equal to the value returned by gptr(). ═══ 4.9.6.5. pbump ═══ void pbump(int offset); pbump() offsets the beginning of the put area by the value of offset. The value of offset can be positive or negative. pbump() does not check to see if the new value returned by pptr() is valid. The beginning of the put area is equal to the value returned by pptr(). ═══ 4.9.6.6. unbuffered ═══ int unbuffered() const; void unbuffered(int buffstate); unbuffered() manipulates the private streambuf variable called the buffering state. If the buffering state is nonzero, a call to allocate() does not set up a stream buffer. There are two versions of unbuffered(). The version that takes no arguments returns the current value of the buffering state. The version that takes an argument, buffstate, changes the value of the buffering state to buffstate. ═══ 4.9.7. Protected Virtual Member Functions ═══ This section describes the virtual functions in the protected interface of streambuf. Although these virtual functions have default definitions in streambuf, they can be overridden in classes that are derived from streambuf. The following descriptions state the default definition of each function and the expected behavior for these functions in classes where they are overridden. Note: The following descriptions assume that the functions are called as part of an object called dsb, which is an object of a class that is derived from streambuf. The following functions are described:  doallocate - Allocate space for a stream buffer  overflow - Clear put area  pbackfail - Deal with full putback area  seekoff - Reposition external get or put pointer  seekpos - Reposition external get or put pointer  setbuf - Set up stream buffer  sync - Synchronize stream buffer and ultimate producer or ultimate consumer  underflow - Fill get area. ═══ 4.9.7.1. doallocate ═══ virtual int doallocate(); doallocate() is called when allocate() determines that space is needed for a stream buffer. The default definition of doallocate() attempts to allocate space for a stream buffer using the operator new. If you define your own version of doallocate(), it must call setb() to provide space for a stream buffer or return EOF if it cannot allocate space. doallocate() should only be called if unbuffered() and base() return zero. In your own version of doallocate(), you provide the size of the buffer for your constructor. Assign the buffer size you want to to a variable using a #define statement. This variable can then be used in the constructor for your doallocate() function to define the size of the buffer. ═══ 4.9.7.2. overflow ═══ virtual int overflow(int c = EOF); overflow() is called when the put area is full, and an attempt is made to store another character in it. overflow() may be called at other times. The default definition of overflow() is compatible with the AT&T C++ Language System Release 1.2 version of the stream package, but it is not considered part of the current I/O Stream Library. Thus, the default definition of overflow() should not be used, and every class derived from streambuf should define overflow() itself. The definition of overflow() in your classes derived from streambuf should cause the ultimate consumer to consume the characters in the put area, call setp() to establish a new put area, and store the argument c in the put area if c does not equal EOF. overflow() should return EOF if an error occurs, and it should return a value not equal to EOF otherwise. ═══ 4.9.7.3. pbackfail ═══ virtual int pbackfail(int c); pbackfail() is called when both of the following conditions are true:  An attempt has been made to put back a character.  There is no room in the putback area. The pointer returned by eback() equals the pointer returned by gptr(). The default definition of pbackfail() returns EOF. If you define pbackfail() in your own classes, your definition of pbackfail() should attempt to deal with the full putback area by, for instance, repositioning the get pointer of the ultimate producer. If this is possible, pbackfail() should return the argument c. If not, pbackfail() should return EOF. ═══ 4.9.7.4. seekoff ═══ virtual streampos seekoff(streamoff so, seek_dir dir, int mode = ios::in|ios::out); seekoff() repositions the get or put pointer of the ultimate producer or ultimate consumer. seekoff() does not change the values returned by dsb.gptr() or dsb.pptr(). The default definition of seekoff() returns EOF. If you define your own seekoff() function, it should return EOF if the derived class does not support repositioning. If the class does support repositioning, seekoff() should return the new position of the affected pointer, or EOF if an error occurs. so is an offset from a position in the ultimate producer or ultimate consumer. dir is a position in the ultimate producer or ultimate consumer. dir can have the following values:  ios::beg: the beginning of the ultimate producer or ultimate consumer  ios::cur: the current position in the ultimate producer or ultimate consumer  ios::end: the end of the ultimate producer or ultimate consumer The new position of the affected pointer is the position specified by dir offset by the value of so. If you derive your own classes from streambuf, certain values of dir may not be valid depending on the nature of the ultimate consumer or producer. If ios::in is set in mode, the seekoff() should modify the get pointer. If ios::out is set in mode, the put pointer should be modified. If both ios::in and ios::out are set, both the get pointer and the put pointer should be modified. ═══ 4.9.7.5. seekpos ═══ virtual streampos seekpos(streampos pos, int mode = ios::in|ios::out); seekpos() repositions the get or put pointer of the ultimate producer or ultimate consumer to the position pos. If ios::in is set in mode, the get pointer is repositioned. If ios::out is set in mode, the put pointer is repositioned. If both ios::in and ios::out are set, both the get pointer and the put pointer are affected. seekpos() does not change the values returned by dsb.gptr() or dsb.pptr(). The default definition of seekpos() returns the return value of the function seekoff(streamoff(pos), ios::beg, mode). Thus, if you want to define seeking operations in a class derived from streambuf, you can define seekoff() and use the default definition of seekpos(). If you define seekpos() in a class derived from streambuf, seekpos() should return EOF if the class does not support repositioning or if pos points to a position equal to or greater than the end of the stream. If not, seekpos() should return pos. ═══ 4.9.7.6. setbuf ═══ virtual streambuf* setbuf(char* ptr, int len); streambuf* setbuf(unsigned char* ptr, int len); streambuf* setbuf(char* ptr, int len, int count); // obsolete There are three versions of setbuf(). The two versions that take two arguments set up a stream buffer consisting of the array of bytes starting at ptr with length len. This function is different from setb(). setb() sets pointers to an existing stream buffer. setbuf(), however, creates the stream buffer. The version of setbuf() that takes three arguments is obsolete. The I/O Stream Library includes it to be compatible with AT&T C++ Language System Release 1.2. The default definition of setbuf() sets up the stream buffer if the streambuf object does not already have a stream buffer. If you define setbuf() in a class derived from streambuf, setbuf() can either accept or ignore a request for an unbuffered streambuf object. The call to setbuf() is a request for an unbuffered streambuf object if ptr equals 0 or len equals 0. setbuf() should return a pointer to sb if it accepts the request, and 0 otherwise. ═══ 4.9.7.7. sync ═══ virtual int sync(); sync() synchronizes the stream buffer with the ultimate producer or the ultimate consumer. The default definition of sync() returns 0 if either of the following conditions is true:  The get area is empty and there are no characters waiting to go to the ultimate consumer  No stream buffer has been allocated for sb. Otherwise, sync() returns EOF. If you define sync() in a class derived from streambuf, it should send any characters that are stored in the put area to the ultimate consumer, and (if possible) send any characters that are waiting in the get area back to the ultimate producer. When sync() returns, both the put area and the get area should be empty. sync() should return EOF if an error occurs. ═══ 4.9.7.8. underflow ═══ virtual int underflow(); underflow() takes characters from the ultimate producer and puts them in the get area. The default definition of underflow() is compatible with the AT&T C++ Language System Release 1.2 version version of the stream package, but it is not considered part of the current I/O Stream Library. Thus, the default definition of underflow() should not be used, and every class derived from streambuf should define underflow() itself. If you define underflow() in a class derived from streambuf, it should return the first character in the get area if the get area is not empty. If the get area is empty, underflow() should create a get area that is not empty and return the next character. If no more characters are available in the ultimate producer, underflow() should return EOF and leave the get area empty. ═══ 4.10. strstream, istrstream, and ostrstream Classes ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.10.1. Class Description - strstream, istrstream, and ostrstream ═══ This chapter describes istrstream, ostrsteam, and strstream, the classes that specialize istream, ostream, and iostream (respectively) to use strstreambuf objects for stream buffers. These classes are called the array stream buffer classes because their stream buffers are arrays of bytes in memory. You can use these classes to perform input and output with strings in memory. This chapter also describes strstreambase, the class from which the array stream buffer classes are derived. You can view the topics in this chapter either through the panel on the left, or by selecting the information for a specific class from the list below:  strstreambase class  strstream class  istrstream class  ostrstream class ═══ Derivation ═══ ios istream ostream iostream strstream ios istream istrstream ios ostream ostrstream ═══ Header File ═══ strstream, istrstream, and ostrstream are declared in iostream.h. ═══ Members ═══ The following members are provided for strstream, istrstream, and ostrstream:  Constructors for istrstream  Destructor for istrstream  Constructors for ostrstream  Destructor for ostrstream  Constructor for strstream  Destructor for strstream  pcount  rdbuf  str  str ═══ 4.10.2. strstreambase ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.10.3. Class Description - strstreambase ═══ Note: The strstreambase class is an internal class that provides common functions for the classes that are derived from it. Do not use the strstreambase class directly. The following description is provided so that you can use the function as part of istrstream, ostrsteam, and strstream objects. ═══ 4.10.3.1. Public Members of strstreambase ═══ strstreambase implements the rdbuf function. ═══ 4.10.3.1.1. rdbuf ═══ strstreambuf* rdbuf(); rdbuf() returns a pointer to the stream buffer that the strstreambase object is attached to. ═══ 4.10.4. strstream ═══ Description Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.10.5. Class Description - strstream ═══ strstream is the class that specializes iostream for input and output with arrays of characters in memory. You can create an strstream object by associating the object with a previously allocated array of characters. You can then write output to it, read input from it, and apply other operations to it just as you would to another type of stream. ═══ 4.10.5.1. Public Members ═══  Constructor for strstream  Destructor for strstream  str - return pointer to stream buffer array You can view an example of using the strstream class in the Open Class Library User's Guide. ═══ 4.10.5.1.1. Constructor for strstream ═══ strstream(); strstream(char* cp, int len, int mode); strstream(signed char* cp, int len, int mode); strstream(unsigned char* cp, int len, int mode); There are two versions of the strstream constructor. The version that takes no arguments specifies that space is allocated dynamically for the stream buffer that is attached to the strstream object. The version of the strstream constructor that takes three arguments specifies that characters should be extracted and inserted into the array of bytes that starts at the position pointed to by cp with a length of len bytes. If ios::ate or ios::app is set in mode, cp points to a null-terminated string and insertions begin at the null character. Otherwise, insertions begin at the position pointed to by cp. You can use the istream::seekg() function to reposition the get pointer anywhere in this array. ═══ 4.10.5.1.2. Destructor for strstream ═══ ~strstream(); The strstream destructor frees the space allocated by the strstream constructor. ═══ 4.10.5.1.3. str ═══ char* str(); str() returns a pointer to the stream buffer attached to the strstream and calls freeze() with a nonzero value to prevent the stream buffer from being deleted. If the stream buffer was constructed with an explicit array, the value returned is a pointer to that array. If the stream buffer was constructed in dynamic mode, cp points to the dynamically allocated area. Until you call str(), deleting the dynamically allocated stream buffer is the responsibility of the strstream object. After str() has been called, the calling application has responsibility for the dynamically allocated stream buffer. Note: If your application calls str() without calling freeze() with a nonzero argument (to unfreeze the strstream), or without explicitly deleting the array of characters returned by the call to str(), the array of characters will not be deallocated by the strstream when it is destroyed. This situation is a potential source of a memory leak. ═══ 4.10.6. istrstream ═══ Description To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.10.7. Class Description - istrstream ═══ The following functions are described:  Constructors for istrstream  Destructor for istrstream ═══ 4.10.7.1. Constructors for istrstream ═══ istrstream(char* cp); istrstream(signed char* cp); istrstream(unsigned char* cp); istrstream(const char* cp); istrstream(const signed char* cp); istrstream(const unsigned char* cp); istrstream(char* cp, int len); istrstream(signed char* cp, int len); istrstream(unsigned char* cp, int len); istrstream(const char* cp, int len); istrstream(const signed char* cp, int len); istrstream(const unsigned char* cp, int len); The versions of the istrstream constructor that take one argument specify that characters should be extracted from the null-terminated string that is pointed to by cp. You can use the istream::seekg() function to reposition the get pointer in this string. The versions of the istrstream constructor that take two arguments specify that characters should be extracted from the array of bytes that starts at the position pointed to by cp and has a length of len bytes. You can use istream::seekg() to reposition the get pointer anywhere in this array. ═══ 4.10.7.2. Destructor for istrstream ═══ ~istrstream(); The istrstream destructor frees space that was allocated by the istrstream constructor. ═══ 4.10.8. ostrstream ═══ Description To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.10.9. Class Description - ostrstream ═══ The following functions are described:  Constructors for ostrstream  Destructor for ostrstream  str - return pointer to stream buffer array  pcount - return number of characters in stream buffer ═══ 4.10.9.1. Constructors for ostrstream ═══ ostrstream(); ostrstream(char* cp, int len, int mode = ios::out); ostrstream(signed char* cp, int len, int mode = ios::out); ostrstream(unsigned char* cp, int len, int mode = ios::out); The version of the ostrsteam constructor that takes no arguments specifies that space is allocated dynamically for the stream buffer that is attached to the ostrsteam object. The versions of the ostrsteam constructor that take three arguments specify that the stream buffer that is attached to the ostrsteam object consists of an array that starts at the position pointed to by cp with a length of len bytes. If ios::ate or ios::app is set in mode, cp points to a null-terminated string and insertions begin at the null character. Otherwise, insertions begin at the position pointed to by cp. You can use the ostream::seekp() function to reposition the put pointer. ═══ 4.10.9.2. Destructor for ostrstream ═══ ~ostrstream(); The ostrsteam destructor frees space allocated by the ostrsteam constructor. The destructor also writes a null byte to the stream buffer to terminate the stream. ═══ 4.10.9.3. str ═══ char* str(); str() returns a pointer to the stream buffer attached to the ostrsteam and calls freeze() with a nonzero value to prevent the stream buffer from being deleted. If the stream buffer was constructed with an explicit array, the value returned is a pointer to that array. If the stream buffer was constructed in dynamic mode, cp points to the dynamically allocated area. Until you call str(), deleting the dynamically allocated stream buffer is the responsibility of the ostrsteam object. After str() has been called, the calling application has responsibility for the dynamically allocated stream buffer. ═══ 4.10.9.4. pcount ═══ int pcount(); pcount() returns the number of bytes that have been stored in the stream buffer. pcount() is mainly useful when binary data has been stored and the stream buffer attached to the ostrsteam object is not a null-terminated string. pcount() returns the total number of bytes, not just the number of bytes up to the first null character. ═══ 4.11. strstreambuf Class ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 4.11.1. Class Description - strstreambuf ═══ This chapter describes the strstreambuf class, the class that specializes streambuf to use an array of bytes in memory as the ultimate producer or ultimate consumer. ═══ Derivation ═══ streambuf strstreambuf ═══ Header File ═══ strstreambuf is declared in strstrea.h. ═══ Members ═══ The following members are provided for strstreambuf:  Constructors for strstreambuf  Destructor for strstreambuf  doallocate  freeze  overflow  seekoff  setbuf  str  underflow ═══ 4.11.2. Constructors for strstreambuf ═══ strstreambuf(); strstreambuf(int bufsize); strstreambuf(void* (*alloc) (long), void(*free)(void*)); strstreambuf(char* sp, int len, char* tp); strstreambuf(signed char* sp, int len, signed char* tp); strstreambuf(unsigned char* sp, int len, unsigned char* tp); The first version of the strstreambuf constructor takes no arguments and constructs an empty strstreambuf object in dynamic mode. Space will be allocated automatically to accommodate the characters that are put into the strstreambuf object. This space will be allocated using the operator new and deallocated using the operator delete. The characters that are already stored by the strstreambuf object may have to be copied when new space is allocated. If you know you are going to insert many characters into an strstreambuf object, you can give the I/O Stream Library an estimate of the size of the object before you create it by calling strstreambuf::setbuf(). The second version of the strstreambuf constructor takes one argument and constructs an empty strstreambuf object in dynamic mode. The initial size of the stream buffer will be at least bufsize bytes. The third version of the strstreambuf constructor takes two arguments and creates an empty strstreambuf object in dynamic mode. alloc is a pointer to the function that is used to allocate space. alloc is passed a long value that equals the number of bytes that it is supposed to allocate. If the value of alloc is 0, the operator new is used to allocate space. free is a pointer to the function that is used to free space. free is passed an argument that is a pointer to the array of bytes that alloc allocated. If free has a value of 0, the operator delete is used to free space. The fourth, fifth, and sixth versions of the strstreambuf constructor take three arguments and construct a strstreambuf object with a stream buffer that begins at the position pointed to by sp. The nature of the stream buffer depends on the value of len:  If len is positive, the len bytes following the position pointed to by sp make up the stream buffer.  If len equals 0, sp points to the beginning of a null-terminated string, and the bytes of that string, excluding the terminating null character, will make up the stream buffer.  If len is negative, the stream buffer has an indefinite length. The get pointer of the stream buffer is initialized to sp, and the put pointer is initialized to tp. Regardless of the value of len, if the value of tp is 0, the get area will include the entire stream buffer, and insertions will cause errors. ═══ 4.11.3. Destructor for strstreambuf ═══ ~strstreambuf(); If freeze() has not been called for the strstreambuf object and a stream buffer is associated with the strstreambuf object, the strstreambuf destructor frees the space allocated by the strstreambuf constructor. The effect of the destructor depends on the constructor used to create the strstreambuf object:  If you created the strstreambuf object using the constructor that takes two pointers to functions as arguments (see Constructors for strstreambuf for more details), the destructor frees the space allocated by the destructor by calling the function pointed to by the second argument to the constructor.  If you created the strstreambuf object using any of the other constructors, the destructor calls the delete operator to free the space allocated by the constructor. ═══ 4.11.4. doallocate ═══ virtual int doallocate(); doallocate() attempts to allocate space for a stream buffer. If you created the strstreambuf object using the constructor that takes two pointers to functions as arguments (see Constructors for strstreambuf for more details), doallocate() allocates space for the stream buffer by calling the function pointed to by the first argument to the constructor. Otherwise, doallocate() calls the operator new to allocate space for the stream buffer. ═══ 4.11.5. freeze ═══ void freeze(int n=1); freeze() controls whether the array that makes up a stream buffer can be deleted automatically. If n has a nonzero value, the array is not deleted automatically. If n equals 0, the array is deleted automatically when more space is needed or when the strstreambuf object is deleted. If you call freeze() with a nonzero argument for a strstreambuf object that was allocated in dynamic mode, any attempts to put characters in the stream buffer may result in errors. Therefore, you should avoid insertions to such stream buffers because the results are unpredictable. However, if you have a "frozen" stream buffer and you call freeze() with an argument equal to 0, you can put characters in the stream buffer again. Only space that is acquired through dynamic allocation is ever freed. ═══ 4.11.6. overflow ═══ virtual int overflow(int c); overflow() causes the ultimate consumer to consume the characters in the put area and calls setp() to establish a new put area. The argument c is stored in the new put area if c is not equal to EOF. ═══ 4.11.7. str ═══ char* str(); str() returns a pointer to the first character in the stream buffer and calls freeze() with a nonzero argument. Any attempts to put characters in the stream buffer may result in errors. If the strstreambuf object was created with an explicit array (that is, the strstreambuf constructor with three arguments was used), str() returns a pointer to that array. If the strstreambuf object was created in dynamic mode and nothing is stored in the array, str() may return 0. ═══ 4.11.8. seekoff ═══ virtual streampos seekoff( streamoff so, ios::seek_dir dir, int mode); seekoff() repositions the get or put pointer in the array of bytes in memory that serves as the ultimate producer or the ultimate consumer. For a text mode file, seekoff() returns the actual physical file position, because carriage return characters and end-of-file characters are discarded on input. Thus, there may not be a one-to-one correspondence between the characters in a stream and those in its external representation. For further details, see "Low-Level I/O" in the IBM VisualAge C++ for OS/2 C Library Reference, S25H-6964. If you constructed the strstreambuf in dynamic mode (see Constructors for strstreambuf), the results of seekoff() are unpredictable. Therefore, do not use seekoff() with an strstreambuf object that you created in dynamic mode. If you did not construct the strstreambuf object in dynamic mode, seekoff() attempts to reposition the get pointer or the put pointer, depending on the value of mode. If ios::in is set in mode, seekoff() repositions the get pointer. If ios::out is set in mode, seekoff() repositions the put pointer. If both ios::in and ios::out are set, seekoff() repositions both pointers. seekoff() attempts to reposition the affected pointer to the value of dir + so. dir can have the following values:  ios::beg: the beginning of the array in memory  ios::cur: the current position in the array in memory  ios::end: the end of the array in memory If the value of dir + so is equal to or greater than the end of the array, the value is not valid and seekoff() returns EOF. Otherwise, seekoff() sets the affected pointer to this value and returns this value. ═══ 4.11.9. setbuf ═══ virtual streambuf* setbuf(0, int bufsize); setbuf() records bufsize. The next time that the strstreambuf object dynamically allocates a stream buffer, the stream buffer is at least bufsize bytes long. Note: If you call setbuf() for an strstreambuf object, you must call it with the first argument equal to 0. ═══ 4.11.10. underflow ═══ virtual int underflow(); If the get area is not empty, underflow() returns the first character in the get area. If the get area is empty, underflow() creates a new get area that is not empty and returns the first character. If no more characters are available in the ultimate producer, underflow() returns EOF and leaves the get area empty. ═══ 5. Collection Classes ═══ The Collection Class Library lets you develop programs that implement commonly used abstract data types, including sets, maps, sequences, trees, stacks, queues, and sorted or keyed collections. The following topics are discussed in this section: Flat Collection Classes Tree Collection Classes Auxiliary Collection Classes Abstract Collection Classes Header Files for Coding Examples ═══ 5.1. Flat Collection Classes ═══ This part contains detailed descriptions of the flat Collection Classes. Introduction to Flat Collections describes the common member functions for flat collections. Subsequent chapters describe individual collection classes. For information on the organization of chapters that describe individual abstract data types, see Format of Class Descriptions. The following flat collections are described in this part:  Bag  Deque  Equality sequence  Heap  Key bag  Key set  Key sorted bag  Key sorted set  Map  Priority queue  Queue  Relation  Sequence  Set  Sorted bag  Sorted map  Sorted relation  Sorted set  Stack ═══ 5.1.1. Introduction to Flat Collections ═══ This chapter defines some of the terms used in describing the Collection Class Library classes and functions, describes the format of chapters that describe individual collections, and describes some types defined by the Collection Class Library. ═══ 5.1.1.1. Terms Used ═══ CLASS_BASE_NAME For constructor and destructor declarations, this term is used in place of the default implementation variant of a class. For example, the constructor CLASS_BASE_NAME(...) for a Bag, is really IBag(...), because the default implementation variant of a bag is IBag. CLASS_NAME For member function declarations, this term is used in place of the class with template arguments. For example, if you want to use: IBoolean operator != ( CLASS_NAME const& collection ) const; for a Bag on BST Key Sorted Set, substitute IBagOnBSTKeySortedSet for CLASS_NAME. equal element Refers to equality of elements as defined by the equality operation or ordering relation provided for the element type (Element Functions and Key-Type Functions describes the purpose of the equality operation and ordering relation.) Where both equality operation and ordering relation are provided, the Collection Class Library may use either to determine element equality. given ... Refers to an argument of the described function, such as given element, given key, or given collection. iteration order The order in which elements are visited in allElementsDo() and setToNext() or setToPrevious(). In ordered collections, the element at position 1 will be visited first, then the element at position 2, and so on. Sorted collections, in particular, are visited following the ordering relation provided for the element type. In collections that are not ordered, the elements are visited in an arbitrary order. Each element is visited exactly once. positioning property The property of an element that is used to position the element in a collection. For key collections, the positioning property is key equality. For nonsequential collections with element equality, the positioning property is element equality. Other collections have no positioning property. same key Refers to equality of keys as defined by the equality operation or ordering relation provided for the key type. (See Element Functions and Key-Type Functions.) Where both equality operation and ordering relation are provided, the Collection Class Library may use either to determine key equality. this collection The collection to which a function is applied. Contrast with the given collection, which is an argument supplied to a function. The collection is synonymous with this collection. undefined cursor A cursor that may or may not be valid; there is no way to know whether the cursor is valid or not. An undefined cursor, even if it remains valid, may refer to a different element than before, or even to no element of the collection. Do not use cursors, once they become undefined, in functions that require the cursor to point to an element of the collection. ═══ 5.1.1.2. Format of Class Descriptions ═══ Each chapter describing one or more Collection Classes consists of the following components:  The chapter title, which usually refers to the kind of collection being discussed.  A description of the collection's characteristics, such as whether the collection is sorted or unsorted, or whether the type and value of the elements are relevant.  A textual example of using the collection in an application.  Information on the class's derivation.  A section on class implementation variants that provides some or all of the following information: - The default implementation, and the classes that you can use to alter the way the collection is implemented. These variant classes are based on other abstract data types within the Collection Class Library. For example, in the chapter on heap collections, the class IHeapOnTabularSequence is a heap collection based on ITabularSequence. - The names of the header files that correspond to particular implementation variants, so that you can include those files in your source code to make use of the implementation variants.  A section on template arguments and required parameters that provides the following information: - Template arguments, which identify what parameters you must supply when you instantiate a particular implementation variant. - Required functions, which are functions that must be provided by the element type or key type you use for any implementation variant.  A section on the reference class. The reference class allows you to make use of polymorphism. This section contains information on include files, template arguments and required functions similar to the information provided for the implementation variants described above. In general, reference classes do not put any additional requirements on the element type or key type. The requirements are those of the implementation variant used with the reference class.  Optionally, a coding example to show you how to use the collection. ═══ 5.1.1.2.1. Required Functions ═══ As described in Element Functions and Key-Type Functions, the Collection Classes require that you provide certain functions for the element type and key type. These functions are required by member functions of the Collection Class Library to manipulate elements and keys. The functions you must provide depend on the abstraction you use and on the implementation variant you choose. For example, you will usually need to provide a key access for all keyed abstractions, and for a hash table implementation you will need to provide a hash function. ═══ 5.1.1.3. Types Defined for the Collection Class Library ═══ The following types are defined in iglobals.h or in header files included by iglobals.h: typedef int IBoolean; enum { false = 0, False = 0, true = 1, True = 1 }; typedef unsigned long INumber; typedef unsigned long IPosition; enum ITreeIterationOrder {IPreorder, IPostorder}; // for n-ary tree only Note: If your environment defines another boolean type, use IBoolean wherever you want to refer to Boolean in the context of the Collection Class Library. ═══ 5.1.2. Flat Collection Member Functions ═══ Each flat collection implements some or all of the member functions described in this chapter. Chapters on individual classes identify which functions are implemented for those classes. The following member functions are described: ┌────────────────────────────────┬───────────────────────────────┐ │ Constructor │ locate │ │ Copy Constructor │ locateElementWithKey │ │ Destructor │ locateFirst │ │ operator!= │ locateLast │ │ operator= │ locateNext │ │ operator== │ locateNextElementWithKey │ │ add │ locateOrAdd │ │ addAllFrom │ locateOrAddElementWithKey │ │ addAsFirst │ locatePrevious │ │ addAsLast │ maxNumberOfElements │ │ addAsNext │ newCursor │ │ addAsPrevious │ numberOfDifferentElements │ │ addAtPosition │ numberOfDifferentKeys │ │ addDifference │ numberOfElements │ │ addIntersection │ numberOfElementsWithKey │ │ addOrReplaceElementWithKey │ numberOfOccurrences │ │ addUnion │ pop │ │ allElementsDo │ push │ │ allElementsDo │ remove │ │ anyElement │ removeAllElementsWithKey │ │ compare │ removeAllOccurrences │ │ contains │ removeAll │ │ containsAllFrom │ removeAll │ │ containsAllKeysFrom │ removeAt │ │ containsElementWithKey │ removeAtPosition │ │ copy │ removeElementWithKey │ │ dequeue │ removeFirst │ │ differenceWith │ removeLast │ │ elementAt │ replaceAt │ │ elementAtPosition │ replaceElementWithKey │ │ elementWithKey │ setToFirst │ │ enqueue │ setToLast │ │ firstElement │ setToNext │ │ intersectionWith │ setToNextDifferentElement │ │ isBounded │ setToNextWithDifferentKey │ │ isEmpty │ setToPosition │ │ isFirst │ setToPrevious │ │ isFull │ sort │ │ isLast │ top │ │ key │ unionWith │ │ lastElement │ │ └────────────────────────────────┴───────────────────────────────┘ ═══ 5.1.2.1. Constructor ═══ CLASS_BASE_NAME ( INumber numberOfElements = 100 ) ; Constructs a collection. numberOfElements is the estimated maximum number of elements contained in the collection. The collection is unbounded and is initially empty. If the estimated maximum is exceeded, the collection is automatically enlarged. Note: The collection constructor does not define whether any elements are constructed when the collection is constructed. For some classes, the element's default constructor may be invoked when the collection's constructor is invoked. This happens if a tabular or a diluted sequence implementation variant is used for a collection. The element's default constructor is used to allocate the required storage and initialize the elements. Therefore, a default constructor must be available for elements in such cases. Exception IOutOfMemory ═══ 5.1.2.2. Copy Constructor ═══ CLASS_BASE_NAME ( CLASS_NAME const& collection ) ; Constructs a collection and copies all elements from the given collection into the collection as described for addAllFrom. Exception IOutOfMemory ═══ 5.1.2.3. Destructor ═══ ~CLASS_BASE_NAME ( ) ; Removes all elements from the collection. Destructors are called for all elements contained in the collection and for elements that have been constructed in advance. Side Effects All cursors of the collection become undefined. ═══ 5.1.2.4. operator!= ═══ IBoolean operator!= ( CLASS_NAME const& collection ) const; Returns True if the given collection is not equal to the collection. For a definition of equality for collections, see operator==. ═══ 5.1.2.5. operator= ═══ CLASS_NAME& operator= ( CLASS_NAME const& collection ) ; Copies the given collection to the collection. Removes all elements from the collection and adds the elements from the given collection as described for addAllFrom. Preconditions  If the collection is bounded, numberOfElements() of the given collection must be less than maxNumberOfElements() of this collection. Side Effects  All cursors of this collection become undefined.  Collection classes supporting Visual Builder send a modifiedId notification. Return Value Returns a reference to the collection. Exceptions  IOutOfMemory  IFullException, if the collection is bounded ═══ 5.1.2.6. operator== ═══ IBoolean operator== ( CLASS_NAME const& collection ) const; Returns True if the given collection is equal to the collection. Two collections are equal if the number of elements in each collection is the same, and if the condition for the collection is described in the following list: Type of Collection Condition Unique Elements If the collections have unique elements, any element that occurs in one collection must occur in the other collection. Non-Unique Elements If an element has n occurrences in one collection, it must have exactly n occurrences in the other collection. Sequential The ordering of the elements is the same for both collections. ═══ 5.1.2.7. add ═══ IBoolean add ( Element const& element ) ; IBoolean add ( Element const& element, ICursor& cursor ) ; If the collection is unique (with respect to elements or keys) and the element or key is already contained in the collection, sets the cursor to the existing element in the collection without adding the element. Otherwise, it adds the element to the collection and sets the cursor to the added element. In sequential collections, the given element is added as the last element. In sorted collections, the element is added at a position determined by the element or key value. Adding an element will either use the element's copy constructor or the assignment operator provided for the element type, depending on the implementation variant you choose. See contains for the definition of element or key containment. Preconditions  The cursor must belong to the collection.  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If an element was added, all cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. Return Value Returns True if the element was added. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.8. addAllFrom ═══ void addAllFrom ( CLASS_NAME const& collection ) ; void addAllFrom ( IACollection const& collection ) ; Adds (copies) all elements of the given collection to the collection. The elements are added in the iteration order of the given collection. The contents of the elements, not the pointers to the elements, are copied. The elements are added according to the definition of add for this collection. The given collection is not changed. Preconditions Because the elements are added one by one, the following preconditions are tested for each individual add operation:  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If any elements were added, all cursors of this collection become undefined.  If any elements were added, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IIdenticalCollectionException  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.9. addAsFirst ═══ void addAsFirst ( Element const& element ) ; void addAsFirst ( Element const& element, ICursor& cursor ) ; Adds the element to the collection as the first element in sequential order. Sets the cursor to the added element. Preconditions  The cursor must belong to the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. Exceptions  ICursorInvalidException  IOutOfMemory  IFullException, if the collection is bounded ═══ 5.1.2.10. addAsLast ═══ void addAsLast ( Element const& element ) ; void addAsLast ( Element const& element, ICursor& cursor ) ; Adds the element to the collection as the last element in sequential order. Sets the cursor to the added element. Preconditions  The cursor must belong to the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. All cursors of this collection, except the given cursor, become undefined. Exceptions  ICursorInvalidException  IOutOfMemory  IFullException, if the collection is bounded ═══ 5.1.2.11. addAsNext ═══ void addAsNext ( Element const& element, ICursor& cursor ) ; Adds the element to the collection as the element following element pointed to by the cursor. Sets the cursor to the added element. Preconditions  The cursor must belong to the collection and must point to an element of the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.12. addAsPrevious ═══ void addAsPrevious ( Element const& element, ICursor& cursor ) ; Adds the element to the collection as the element preceding the element pointed to by the cursor. Sets the cursor to the added element. Preconditions  The cursor must belong to the collection and must point to an element of the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.13. addAtPosition ═══ void addAtPosition ( IPosition position, Element const& element ) ; void addAtPosition ( IPosition position, Element const& element, ICursor& cursor ) ; Adds the element at the given position to the collection, and sets the cursor to the added element. If an element exists at the given position, the new element is added as the element preceding the existing element. Preconditions  The cursor must belong to the collection.  (1 <= position <= numberOfElements + 1).  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was added, collection classes supporting Visual Builder send an addedId notification. Exceptions  IOutOfMemory  ICursorInvalidException  IPositionInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.14. addDifference ═══ void addDifference ( CLASS_NAME const& collection1, CLASS_NAME const& collection2 ) ; Creates the difference between the two given collections, and adds this difference to the collection. The contents of the added elements, not the pointers to those elements, are copied. For a definition of the difference between two collections, see differenceWith. Preconditions Because the elements are added one by one, the following preconditions are tested for each individual addition.  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If any elements were added, all cursors of this collection become undefined.  If any elements were added, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.15. addIntersection ═══ void addIntersection ( CLASS_NAME const& collection1, CLASS_NAME const& collection2 ) ; Creates the intersection of the two given collections, and adds this intersection to the collection. The contents of the added elements, not the pointers to those elements, are copied. For a definition of the intersection of two collections, see intersectionWith. Preconditions Because the elements are added one by one, the following preconditions are tested for each individual addition.  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If any elements were added, all cursors of this collection become undefined.  If any elements were added, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.16. addOrReplaceElementWithKey ═══ IBoolean addOrReplaceElementWithKey ( Element const& element ); IBoolean addOrReplaceElementWithKey ( Element const& element, ICursor& cursor ) ; If an element is contained in the collection where the key is equal to the key of the given element, sets the cursor to this element in the collection and replaces it with the given element. Otherwise, it adds the given element to the collection, and sets the cursor to the added element. If the given element is added, the contents of the element, not a pointer to it, is added. Preconditions  The cursor must belong to the collection.  If the collection is bounded, an element with the given key must be contained in the collection, or (numberOfElements() < maxNumberOfElements()). Side Effects  If the element was added, all cursors of this collection, except the given cursor, become undefined.  If the element was added, collection classes supporting Visual Builder send a replacedId notification. Return Value Returns True if the element was added. Returns False if the element was replaced. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.17. addUnion ═══ void addUnion ( CLASS_NAME const& collection1, CLASS_NAME const& collection2 ) ; Creates the union of the two given collections, and adds this union to the collection. The contents of the added elements, not the pointers to those elements, are copied. For a definition of the union of two collections, see unionWith. Preconditions Because the elements are added one by one, the following preconditions are tested for each individual addition.  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If any elements were added, all cursors of this collection become undefined.  If any elements were added, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.18. allElementsDo ═══ IBoolean allElementsDo ( IBoolean (*function) (Element&, void*), void* additionalArgument = 0 ) ; IBoolean allElementsDo ( IBoolean (*function) (Element const&, void*), void* additionalArgument = 0 ) const; Calls the given function for all elements in the collection until the given function returns False. The elements are visited in iteration order. Additional arguments can be passed to the given function using additionalArgument. The additional argument defaults to zero if no additional argument is given. Note: 1. The given function must not remove elements from or add them to the collection. If you want to remove elements, you can use the removeAll() function with a property argument. For further information see removeAll. 2. For the non-const version of allElementsDo(), the given function must not manipulate the element in the collection in a way that changes the positioning property of the element. Return Value Returns True if the given function returns True for every element it is applied to. ═══ 5.1.2.19. allElementsDo ═══ IBoolean allElementsDo ( IIterator & iterator ) ; IBoolean allElementsDo ( IConstantIterator & iterator ) const; Calls the applyTo() function of the given iterator for all elements of the collection until the applyTo() function returns False. The elements are visited in iteration order. Additional arguments may be passed as arguments to the constructor of the derived iterator class. Note: 1. The applyTo() function must not remove elements from or add elements to the collection. If you want to remove elements, you can use the removeAll() function with a property argument. For further information, see removeAll. 2. For the non-const version of allElementsDo(), the applyTo() function must not manipulate the element in the collection in a way that changes the positioning property of the element. Return Value Returns True if the applyTo() function returns True for every element it is applied to. ═══ 5.1.2.20. anyElement ═══ Element const& anyElement ( ) const; Returns a reference to an arbitrary element of the collection. Precondition The collection must not be empty. Exception IEmptyException ═══ 5.1.2.21. compare ═══ long compare ( CLASS_NAME const& collection, long (*comparisonFunction) (Element const& element1,Element const& element2) ) const; Compares the collection with the given collection. Comparison yields <0 if the collection is less than the given collection, 0 if the collection is equal to the given collection, and >0 if the collection is greater than the given collection. Comparison is defined by the first pair of corresponding elements, in both collections, that are not equal. If such a pair exists, the collection with the greater element is the greater one. Otherwise, the collection with more elements is the greater one. Note: 1. The given comparison function must return a result according to the following rules: >0 if (element1 > element2) 0 if (element1 == element2) <0 if (element1 < element2) 2. For elements of type char*, compare() is not locale-sensitive by default. Because it uses strcmp() and not strcoll(), it compares the binary values representing the characters, and is not based on the LC_COLLATE category of the current locale. Its results are reliable only for code pages and character sets in which the collating sequence matches the sequence of binary representations. Return Value Returns the result of the collection comparison. ═══ 5.1.2.22. contains ═══ IBoolean contains ( Element const& element ) const; Returns True if the collection contains an element equal to the given element. ═══ 5.1.2.23. containsAllFrom ═══ IBoolean containsAllFrom ( CLASS_NAME const& collection ) const; IBoolean containsAllFrom ( IACollection const& collection ) const; Returns True if all the elements of the given collection are contained in the collection. The definition of containment is described in contains. ═══ 5.1.2.24. containsAllKeysFrom ═══ IBoolean containsAllKeysFrom ( CLASS_NAME const& collection ) const; IBoolean containsAllKeysFrom ( IACollection const& collection ) const; Returns True if all of the keys of the given collection are contained in the collection. ═══ 5.1.2.25. containsElementWithKey ═══ IBoolean containsElementWithKey ( Key const& key ) const; Returns True if the collection contains an element with the same key as the given key. ═══ 5.1.2.26. copy ═══ void copy ( IACollection const& collection ) ; Copies the given collection to this collection. copy() removes all elements from this collection, and adds the elements from the given collection. For information on how adding is done, see addAllFrom. Note: The given collection may be of a concrete type other than the collection itself. In this case, copying implicitly performs a conversion. If, for example, the given collection is a bag and the collection itself is a set, elements with multiple occurrences in the copied bag will only occur once in the resulting set. Preconditions Because the elements are copied one by one, the following preconditions are tested for each individual copy operation:  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  All cursors of this collection become undefined.  If any elements were copied, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection has unique keys. This exception may be thrown, for example, when copying a bag into a map. ═══ 5.1.2.27. dequeue ═══ void dequeue ( ) ; void dequeue ( Element& element ) ; Copies the first element of the collection to the given element, and removes it from the collection. Precondition The collection must not be empty. Side Effects  All cursors of this collection become undefined.  If the element is removed, collection classes supporting Visual Builder send a modifiedId notification. Exception IEmptyException ═══ 5.1.2.28. differenceWith ═══ void differenceWith ( CLASS_NAME const& collection ) ; Makes the collection the difference between the collection and the given collection. The difference of A and B (A minus B) is the set of elements that are contained in A but not in B. The following rule applies for bags with duplicate elements: If bag P contains the element X m times and bag Q contains the element X n times, the difference of P and Q contains the element X m-n times if m > n, and zero times if m<=n. Side Effects  If any elements were removed, all cursors of this collection become undefined.  If the element is removed, collection classes supporting Visual Builder send a modifiedId notification. ═══ 5.1.2.29. elementAt ═══ Element& elementAt ( ICursor const& cursor ) ; Element const& elementAt ( ICursor const& cursor ) const; Returns a reference to the element pointed to by the given cursor. Note: For the version of elementAt() without the const suffix, do not manipulate the element or the key of the element in the collection in a way that changes the positioning property of the element. Precondition The cursor must belong to the collection and must point to an element of the collection. Exception ICursorInvalidException ═══ 5.1.2.30. elementAtPosition ═══ Element const& elementAtPosition ( IPosition position ) const; Returns a reference to the element at the given position in the collection. Position 1 specifies the first element. Position must be a valid position in the collection; that is, (1 <= position <= numberOfElements()). Precondition (1 <= position <= numberOfElements()). Exception IPositionInvalidException ═══ 5.1.2.31. elementWithKey ═══ Element& elementWithKey ( Key const& key ) ; Element const& elementWithKey ( Key const& key ) const; Returns a reference to an element specified by the key. Note: 1. For the version of elementWithKey() without a const suffix, do not manipulate the element in the collection in a way that changes the positioning property of the element. 2. If there are several elements with the given key, an arbitrary one is returned. Precondition The given key is contained in the collection. Exception INotContainsKeyException ═══ 5.1.2.32. enqueue ═══ void enqueue ( Element const& element ) ; void enqueue ( Element const& element, ICursor& cursor ) ; Adds the element to the collection, and sets the cursor to the added element. For ordinary queues, the given element is added as the last element. For priority queues, the element is added at a position determined by the ordering relation provided for the element or key type. Preconditions  The cursor must belong to the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection except the given cursor become undefined.  If the element is added, collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.33. firstElement ═══ Element const& firstElement ( ) const; Returns a reference to the first element of the collection. Precondition The collection must not be empty. Exception IEmptyException ═══ 5.1.2.34. intersectionWith ═══ void intersectionWith ( CLASS_NAME const& collection ) ; Makes the collection the intersection of the collection and the given collection. The intersection of A and B is the set of elements that is contained in both A and B. The following rule applies for bags with duplicate elements: If bag P contains the element X m times and bag Q contains the element X n times, the intersection of P and Q contains the element X MIN(m,n) times. Side Effects  If any elements were removed, all cursors of this collection become undefined.  If any elements were removed, collection classes supporting Visual Builder send a modifiedId notification. ═══ 5.1.2.35. isBounded ═══ IBoolean isBounded ( ) const; Returns True if the collection is bounded. ═══ 5.1.2.36. isEmpty ═══ IBoolean isEmpty ( ) const; Returns True if the collection is empty. ═══ 5.1.2.37. isFirst ═══ IBoolean isFirst ( ICursor const& cursor ) const; Returns True if the given cursor points to the first element of the collection. Preconditions The cursor must belong to the collection and must point to an element of the collection. Exception ICursorInvalidException ═══ 5.1.2.38. isFull ═══ IBoolean isFull ( ) const; Returns True if the collection is bounded and contains the maximum number of elements; that is, if (numberOfElements() == maxNumberOfElements()). ═══ 5.1.2.39. isLast ═══ IBoolean isLast ( ICursor const& cursor ) const; Returns True if the given cursor points to the last element of the collection. Preconditions The cursor must belong to the collection and must point to an element of the collection. Exception ICursorInvalidException ═══ 5.1.2.40. key ═══ Key const& key ( Element const& element ) const; Returns a reference to the key of the given element using the key() function provided for the element type. ═══ 5.1.2.41. lastElement ═══ Element const& lastElement ( ) const; Returns a reference to the last element of the collection. Precondition The collection must not be empty. Exception IEmptyException ═══ 5.1.2.42. locate ═══ IBoolean locate ( Element const& element, ICursor& cursor ) const; Locates an element in the collection that is equal to the given element. Sets the cursor to point to the element in the collection, or invalidates the cursor if no such element exists. If the collection contains several such elements, the first element in iteration order is located. Precondition The cursor must belong to the collection. Return Value Returns True if an element was found. Exceptions ICursorInvalidException ═══ 5.1.2.43. locateElementWithKey ═══ IBoolean locateElementWithKey ( Key const& key, ICursor& cursor ) const; Locates an element in the collection with the same key as the given key. Sets the cursor to point to the element in the collection, or invalidates the cursor if no such element exists. If the collection contains several such elements, the first element in iteration order is located. Precondition The cursor must belong to the collection. Return Value Returns True if an element was found. Exception ICursorInvalidException ═══ 5.1.2.44. locateFirst ═══ IBoolean locateFirst ( Element const& element, ICursor& cursor ) const; Locates the first element in iteration order in the collection that is equal to the given element. Sets the cursor to the located element, or invalidates the cursor if no such element exists. Precondition The cursor must belong to the collection. Return Value Returns True if an element was found. Exception ICursorInvalidException ═══ 5.1.2.45. locateLast ═══ IBoolean locateLast ( Element const& element, ICursor& cursor ) const; Locates the last element in iteration order in the collection that is equal to the given element. Sets the cursor to the located element, or invalidates the cursor if no such element exists. Precondition The cursor must belong to the collection. Return Value Returns True if an element was found. Exception ICursorInvalidException ═══ 5.1.2.46. locateNext ═══ IBoolean locateNext ( Element const& element, ICursor& cursor ) const; Locates the next element in iteration order in the collection that is equal to the given element, starting at the element next to the one pointed to by the given cursor. Sets the cursor to point to the element in the collection. The cursor is invalidated if the end of the collection is reached and no more occurrences of the given element are left to be visited. Note: If you code a call to locateFirst() and a set of calls to locateNext(), each occurrence of an element will be visited exactly once in iteration order. Precondition The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if an element was found. Exception ICursorInvalidException ═══ 5.1.2.47. locateNextElementWithKey ═══ IBoolean locateNextElementWithKey ( Key const& key, ICursor& cursor ) const; Locates the next element in iteration order in the collection with the given key, starting at the element next to the one pointed to by the given cursor. Sets the cursor to point to the element in the collection. The cursor is invalidated if the end of the collection is reached and no more occurrences of such an element are left to be visited. Note: If you code a call to locateFirst() and a set of calls to locateNextElementWithKey(), each occurrence of an element will be visited exactly once in iteration order. Preconditions The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if an element was found. Exception ICursorInvalidException ═══ 5.1.2.48. locateOrAdd ═══ IBoolean locateOrAdd ( Element const& element ) ; IBoolean locateOrAdd ( Element const& element, ICursor& cursor ) ; Locates an element in the collection that is equal to the given element. (See locate for details on locate().) If no such element is found, locateOrAdd() adds the element as described in add. The cursor is set to the located or added element. Note: This method may be more efficient than using locate() followed by a conditionally called add(). Preconditions  The cursor must belong to the collection.  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element.  The element or key must exist, or (numberOfElements() < maxNumberOfElements()). Side Effects  If the element was added, all cursors of this collection, except the given cursor, become undefined.  If the element was added, collection classes supporting Visual Builder send an addedId notification. Return Value Returns True if the element was located. Returns False if the element could not be located but had to be added. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.2.49. locateOrAddElementWithKey ═══ IBoolean locateOrAddElementWithKey ( Element const& element ) ; IBoolean locateOrAddElementWithKey ( Element const& element; ICursor& cursor ) ; Locates an element in the collection with the given key as described for the locateElementWithKey() function. If no such element exists, locateOrAddElementWithKey() adds the element as described in add. The cursor is set to the located or added element. Preconditions  If the collection is bounded and an element with the given key is not already contained, (numberOfElements() < maxNumberOfElements()).  The cursor must belong to the collection. Side Effects  If the element was added, all cursors of this collection, except the given cursor, become undefined.  If the element was added, collection classes supporting Visual Builder send an addedId notification. Return Value Returns True if the element was located. Returns False if the element could not be located but had to be added. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.50. locatePrevious ═══ IBoolean locatePrevious ( Element const& element, ICursor& cursor ) const; Locates the previous element in iteration order that is equal to the given element, beginning at the element previous to the one specified by the given cursor and moving in reverse iteration order through the elements. Sets the cursor to the located element, or invalidates the cursor if no such element exists. Preconditions The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if an element was found. Exceptions ICursorInvalidException ═══ 5.1.2.51. maxNumberOfElements ═══ INumber maxNumberOfElements ( ) const; Returns the maximum number of elements the collection can contain. Precondition The collection is bounded. Exceptions INotBoundedException ═══ 5.1.2.52. newCursor ═══ Cursor* newCursor ( ) const; Creates a cursor for the collection and returns a pointer to the cursor. The cursor is initially not valid. Exception IOutOfMemory ═══ 5.1.2.53. numberOfDifferentElements ═══ INumber numberOfDifferentElements ( ) const; Returns the number of different elements in the collection. ═══ 5.1.2.54. numberOfDifferentKeys ═══ INumber numberOfDifferentKeys ( ) const; Returns the number of different keys in the collection. ═══ 5.1.2.55. numberOfElements ═══ INumber numberOfElements ( ) const; Returns the number of elements the collection contains. ═══ 5.1.2.56. numberOfElementsWithKey ═══ INumber numberOfElementsWithKey ( Key const& key ) const; Returns the number of elements in the collection with the given key. ═══ 5.1.2.57. numberOfOccurrences ═══ INumber numberOfOccurrences ( Element const& element ) const; Returns the number of occurrences of the given element in the collection. ═══ 5.1.2.58. pop ═══ void pop ( ) ; void pop ( Element& element ) ; Copies the last element of the collection to the given element, and removes it from the collection. Precondition The collection must not be empty. Side Effects  All cursors of this collection become undefined.  If the element was removed from the collection, collection classes supporting Visual Builder send a removedId notification. Exception IEmptyException ═══ 5.1.2.59. position ═══ IPosition position ( ICursor const& cursor) const; Determines the position of the current element. Position 1 specifies the first element. Precondition The cursor must belong to the collection, and the cursor must point to an element of the collection. Exception ICursorInvalidException ═══ 5.1.2.60. push ═══ void push ( Element const& element ) ; void push ( Element const& element, ICursor& cursor ) ; Adds the element to the collection as the last element (as defined for add), and sets the cursor to the added element. Preconditions  The cursor must belong to the collection.  If the collection is bounded, (numberOfElements() < maxNumberOfElements()). Side Effects  All cursors of this collection, except the given cursor, become undefined.  If the element was added to the collection, collection classes supporting Visual Builder send an addedId notification. Exceptions  IOutOfMemory  ICursorInvalidException  IFullException, if the collection is bounded ═══ 5.1.2.61. remove ═══ IBoolean remove ( Element const& element ) ; Removes an element in the collection that is equal to the given element. If no such element exists, the collection remains unchanged. In collections with nonunique elements, an arbitrary occurrence of the given element will be removed. Element destructors are called as described in removeAt. Side Effects  If an element was removed, all cursors of this collection become undefined.  If an element was removed, collection classes supporting Visual Builder send a removedId notification. Return Value Returns True if an element was removed. ═══ 5.1.2.62. removeAll ═══ void removeAll ( ) ; Removes all elements from the collection. Element destructors are called as described in removeAt. Side Effects  All cursors of this collection become undefined.  Collection classes supporting Visual Builder send a modifiedId notification. ═══ 5.1.2.63. removeAll ═══ INumber removeAll ( IBoolean (*property) (Element const&, void*), void* additionalArgument = 0 ) ; Removes all elements from this collection for which the given property function returns True. Additional arguments can be passed to the given property function using additionalArgument. The additional argument defaults to zero if no additional argument is given. Element destructors are called as described in removeAt. Side Effects  If any elements were removed, all cursors of this collection become undefined.  If any elements were removed, collection classes supporting Visual Builder send a modifiedId notification. Return Value The number of elements removed. ═══ 5.1.2.64. removeAllElementsWithKey ═══ INumber removeAllElementsWithKey ( Key const& key ) ; Removes all elements from the collection with the same key as the given key. Element destructors are called as described in removeAt. Side Effects  If any elements were removed, all cursors of this collection become undefined.  If any elements were removed, collection classes supporting Visual Builder send a removedId notification. Return Value The number of elements removed. ═══ 5.1.2.65. removeAllOccurrences ═══ INumber removeAllOccurrences ( Element const& element ) ; Removes all elements from the collection that are equal to the given element, and returns the number of elements removed. Element destructors are called as described in removeAt. Side Effects  If any elements were removed, all cursors of this collection become undefined.  If any elements were removed, collection classes supporting Visual Builder send a modifiedId notification. ═══ 5.1.2.66. removeAt ═══ void removeAt ( ICursor& cursor ) ; Removes the element pointed to by the given cursor. The given cursor is invalidated. Note: It is undefined whether the destructor for the removed element is called or whether the element will only be destructed with the collection destructor. For example, in a tabular implementation, a destructor will only be called when the whole collection is destructed, not when a single element is removed. Preconditions The cursor must belong to the collection and must point to an element of the collection. Side Effects  All cursors of this collection, except the given cursor, become undefined.  If an element was removed, collection classes supporting Visual Builder send a removedId notification. Exception ICursorInvalidException ═══ 5.1.2.67. removeAtPosition ═══ void removeAtPosition ( IPosition position ) ; Removes the element from the collection that is at the given position. Element destructors are called as described in removeAt. The first element of the collection has position 1. Precondition Position must be a valid position in the collection; that is, (1 <= position <= numberOfElements()). Side Effects  All cursors of this collection become undefined.  Collection classes supporting Visual Builder send a removedId notification. Exception IPositionInvalidException ═══ 5.1.2.68. removeElementWithKey ═══ IBoolean removeElementWithKey ( Key const& key ) ; Removes an element from the collection with the same key as the given key. If no such element exists, the collection remains unchanged. In collections with nonunique elements, an arbitrary occurrence of such an element will be removed. Element destructors are called as described in removeAt. Side Effects  If an element was removed, all cursors of this collection become undefined.  If an element was removed, collection classes supporting Visual Builder send a removedId notification. Return Value Returns True if an element was removed. ═══ 5.1.2.69. removeFirst ═══ void removeFirst ( ) ; Removes the first element from the collection. Element destructors are called as described in removeAt. Precondition The collection must not be empty. Side Effects  All cursors of this collection become undefined.  If an element was removed, collection classes supporting Visual Builder send a removedId notification. Exception IEmptyException ═══ 5.1.2.70. removeLast ═══ void removeLast ( ) ; Removes the last element from the collection. Element destructors are called as described in removeAt. Precondition The collection must not be empty. Side Effects  All cursors of this collection become undefined.  If an element was removed, collection classes supporting Visual Builder send a removedId notification. Exception IEmptyException ═══ 5.1.2.71. replaceAt ═══ void replaceAt ( ICursor const& cursor, Element const& element ) ; Replaces the element pointed to by the cursor with the given element. Preconditions  The cursor must belong to the collection and must point to an element of the collection.  The given element must have the same positioning property as the replaced element. Side Effect Collection classes supporting Visual Builder send a replacedId notification. Exceptions  ICursorInvalidException  IInvalidReplacementException ═══ 5.1.2.72. replaceElementWithKey ═══ IBoolean replaceElementWithKey ( Element const& element ) ; IBoolean replaceElementWithKey ( Element const& element, ICursor& cursor ) ; Replaces an element with the same key as the given element by the given element, and sets the cursor to this element. If no such element exists, it invalidates the cursor. In collections with nonunique elements, an arbitrary occurrence of such an element will be replaced. Precondition The cursor must belong to the collection. Side Effect Collection classes supporting Visual Builder send a replacedId notification. Return Value Returns True if an element was replaced. Exceptions ICursorInvalidException ═══ 5.1.2.73. setToFirst ═══ IBoolean setToFirst ( ICursor& cursor ) const; Sets the cursor to the first element of the collection in iteration order. If the collection is empty (if no first element exists), it invalidates the given cursor. Precondition The cursor must belong to the collection. Return Value Returns True if the collection is not empty. Exception ICursorInvalidException ═══ 5.1.2.74. setToLast ═══ IBoolean setToLast ( ICursor& cursor ) const; Sets the cursor to the last element of the collection in iteration order. If the collection is empty (if no last element exists), the given cursor is no longer valid. Precondition The cursor must belong to the collection. Return Value Returns True if the collection is not empty. Exceptions ICursorInvalidException ═══ 5.1.2.75. setToNext ═══ IBoolean setToNext ( ICursor& cursor ) const; Sets the cursor to the next element in the collection in iteration order. If no more elements are left to be visited, the given cursor will no longer be valid. Precondition The cursor must belong to the collection and must point to an element. Return Value Returns True if there is a next element. Exceptions ICursorInvalidException ═══ 5.1.2.76. setToNextDifferentElement ═══ IBoolean setToNextDifferentElement ( ICursor& cursor ) const; Sets the cursor to the next element in iteration order in the collection that is different from the element pointed to by the given cursor. If no more elements are left to be visited, the given cursor will no longer be valid. Precondition The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if a subsequent element was found that is different. Exception ICursorInvalidException ═══ 5.1.2.77. setToNextWithDifferentKey ═══ IBoolean setToNextWithDifferentKey ( ICursor& cursor ) const; Sets the cursor to the next element in the collection in iteration order with a key different from the key of the element pointed to by the given cursor. If no such element exists, the given cursor is no longer valid. Preconditions The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if a subsequent element was found whose key is different from the current key. Exception ICursorInvalidException ═══ 5.1.2.78. setToPosition ═══ void setToPosition ( IPosition position, ICursor& cursor ) const; Sets the cursor to the element at the given position. Position 1 specifies the first element. Precondition  The cursor must belong to the collection.  Position must be a valid position in the collection; that is, (1 <= position <= numberOfElements()). Exceptions  ICursorInvalidException  IPositionInvalidException ═══ 5.1.2.79. setToPrevious ═══ IBoolean setToPrevious ( ICursor& cursor ) const; Sets the cursor to the previous element in iteration order, or invalidates the cursor if no such element exists. Preconditions The cursor must belong to the collection and must point to an element of the collection. Return Value Returns True if a previous element exists. Exception ICursorInvalidException ═══ 5.1.2.80. sort ═══ void sort ( long (*comparisonFunction) (Element const& element1, Element const& element2) ); Sorts the collection so that the elements occur in ascending order. The relation of two elements is defined by the comparisonFunction, which you provide. Note: The comparisonFunction must deliver a result according to the following rules: >0 if (element1 > element2) 0 if (element1 == element2) <0 if (element1 < element2) Side Effects  All cursors of this collection become undefined.  Collection classes supporting Visual Builder send a modifiedId notification. ═══ 5.1.2.81. top ═══ Element const& top ( ) const; Returns a reference to the last element of the collection. Precondition The collection must not be empty. Exception IEmptyException ═══ 5.1.2.82. unionWith ═══ void unionWith ( CLASS_NAME const& collection ) ; Makes the collection the union of the collection and the given collection. The union of A and B is the set of elements that are members of A or B or both. The following rule applies for bags with duplicate elements: If bag P contains the element X m times and bag Q contains the element X n times, the union of P and Q contains the element X m+n times. Preconditions Because the elements from the given collection are added to the collection one by one, the following preconditions are tested for each individual add operation :  If the collection is bounded and unique, the element or key must exist or (numberOfElements() < maxNumberOfElements()).  If the collection is bounded and nonunique, (numberOfElements() < maxNumberOfElements()).  If the collection is a map or a sorted map and contains an element with the same key as the given element, this element must be equal to the given element. Side Effects  If any elements were added to the collection, all cursors of this collection become undefined.  Collection classes supporting Visual Builder send a modifiedId notification. Exceptions  IOutOfMemory  IFullException, if the collection is bounded  IKeyAlreadyExistsException, if the collection is a map or a sorted map ═══ 5.1.3. Bag ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.3.1. Class Description - Bag ═══ A bag is an unordered collection of zero or more elements with no key. Multiple elements are supported. A request to add an element that already exists is not ignored. Figure Combination of Flat Collection Properties gives an overview of the properties of a bag and its relationship to other flat collections. An example of using a bag is a program for entering observations on species of plants and animals found in a river. Each time you spot a plant or animal in the river, you enter the name of the species into the collection. If you spot a species twice during an observation period, the species is added twice, because a bag supports multiple elements. You can locate the name of a species that you have observed, and you can determine the number of observations of that species, but you cannot sort the collection by species, because a bag is an unordered collection. If you want to sort the elements of a bag, use a sorted bag instead. The following rule applies for duplicates: If bag P contains the element X m times and bag Q contains the element X n times, then the union of P and Q contains the element X m+n times, the intersection of P and Q contains the element X MIN(m,n) times, and the difference of P and Q contains the element X m-n times if m is > n, and zero times if m is <= n. ═══ Derivation ═══ Collection Equality Collection Bag ═══ Variants and Header Files ═══ IBag, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivbag.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IBag ibag.h AVL tree IGBag ibag.h AVL tree IBagOnBSTKeySortedSet ibagbst.h B* tree IGBagOnBSTKeySortedSet ibagbst.h B* tree IBagOnSortedLinkedSequence ibagsls.h Linked sequence IGBagOnSortedLinkedSequence ibagsls.h Linked sequence IBagOnSortedTabularSequence ibagsts.h Tabular sequence IGBagOnSortedTabularSequence ibagsts.h Tabular sequence IBagOnSortedDilutedSequence ibagsds.h Diluted sequence IGBagOnSortedDilutedSequence ibagsds.h Diluted sequence IBagOnHashKeySet ibaghks.h Hash table IGBagOnHashKeySet ibaghks.h Hash table ═══ Members ═══ All member functions of flat collections are described in Introduction to Flat Collections. The following members are provided for bag:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addUnion  allElementsDo  anyElement  contains  containsAllFrom  differenceWith  elementAt  intersectionWith  isBounded  isEmpty  isFull  locate  locateNext  locateOrAdd  maxNumberOfElements  newCursor  numberOfDifferentElements  numberOfElements  numberOfOccurrences  remove  removeAllOccurrences  removeAll  removeAt  replaceAt  setToFirst  setToNext  setToNextDifferentElement  unionWith Bag also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.3.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for bags:  Bag  Bag on b* key sorted set  Bag on sorted linked sequence  Bag on sorted tabular sequence  Bag on sorted diluted sequence  Bag on hash key set ═══ 5.1.3.2.1. Bag ═══ IBag IGBag The default implementation of the class IBag requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.3.2.2. Bag on B* Key Sorted Set ═══ IBagOnBSTKeySortedSet IGBagOnBSTKeySortedSet The default implementation of the class IBagOnBSTKeySortedSet requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.3.2.3. Bag on Sorted Linked Sequence ═══ IBagOnSortedLinkedSequence IGBagOnSortedLinkedSequence The implementation of the class IBagOnSortedLinkedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.3.2.4. Bag on Sorted Tabular Sequence ═══ IBagOnSortedTabularSequence IGBagOnSortedTabularSequence The implementation of the class IBagOnSortedTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.3.2.5. Bag on Sorted Diluted Sequence ═══ IBagOnSortedDilutedSequence IGBagOnSortedDilutedSequence The implementation of the class IBagOnSortedDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.3.2.6. Bag on Hash Key Set ═══ IBagOnHashKeySet IGBagOnHashKeySet The implementation of the class IBagOnHashKeySet requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Hash function ═══ 5.1.3.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IABag, which is found in the iabag.h header file, or the corresponding reference class, IRBag, which is found in the irbag.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.3.3.1. Template Arguments and Required Functions ═══ IABag IRBag The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.4. Deque ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.4.1. Class Description - Deque ═══ A deque or double-ended queue is a sequence with restricted access. It is an ordered collection of elements with no key and no element equality. The elements are arranged so that each collection has a first and a last element, each element except the last has a next element, and each element but the first has a previous element. You can only add or remove the first or last element. The type and value of the elements are irrelevant, and have no effect on the behavior of the collection. An example of using a deque is a program for managing a lettuce warehouse. Cases of lettuce arriving into the warehouse are registered at one end of the queue (the "fresh" end) by the receiving department. The shipping department reads the other end of the queue (the "old" end) to determine which case of lettuce to ship next. However, if an order comes in for very fresh lettuce, which is sold at a premium, the shipping department reads the "fresh" end of the queue to select the freshest case of lettuce available. ═══ Derivation ═══ Collection Ordered Collection Sequential Collection Sequence Deque Note that deque is based on sequence but is not actually derived from it or from the other classes shown above. See Restricted Access for further details. ═══ Variants and Header Files ═══ IDeque, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivdeque.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IDeque ideque.h Linked sequence IGDeque ideque.h Linked sequence IDequeOnTabularSequence idquts.h Tabular sequence IGDequeOnTabularSequence idquts.h Tabular sequence IDequeOnDilutedSequence idquds.h Diluted sequence IGDequeOnDilutedSequence idquds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for deque:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addAsFirst  addAsLast  allElementsDo  anyElement  compare  elementAt  elementAtPosition  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  maxNumberOfElements  newCursor  numberOfElements  position  removeAll  removeFirst  removeLast  setToFirst  setToLast  setToNext  setToPosition  setToPrevious Deque also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.4.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for deques:  Deque  Deque on tabular sequence  Deque on diluted sequence ═══ 5.1.4.2.1. Deque ═══ IDeque IGDeque The default implementation of the class IDeque requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.4.2.2. Deque on Tabular Sequence ═══ IDequeOnTabularSequence IGDequeOnTabularSequence The implementation of the class IDequeOnTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment ═══ 5.1.4.2.3. Deque on Diluted Sequence ═══ IDequeOnDilutedSequence IGDequeOnDilutedSequence The implementation of the class IDequeOnDilutedSequence requires the following element functions: Element Type  Default constructor  copy constructor  Assignment ═══ 5.1.4.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IADeque, which is found in the iadeque.h header file, or the corresponding reference class, IRDeque, which is found in the irdeque.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.4.3.1. Template Arguments and Required Functions ═══ IADeque IRDeque The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.4.4. Coding Example for Deque ═══ The following program uses the default deque class, IDeque, to create a deque. It fills the deque with characters by adding them to the back end. The program then removes the characters from alternating ends of the deque (beginning with the front end) until the deque is empty. The program uses the constant iterator class, IConstantIterator, when printing the collection. It uses the addAsLast() function to fill the deque and the numberOfElements() function to determine the deque's size. It uses the functions firstElement(), removeFirst(), lastElement(), and removeLast() to empty the deque. // letterdq.C - An example of using a Deque. #include #include // Let's use the default deque typedef IDeque Deque; // The deque requires iteration to be const typedef IConstantIterator CharIterator; class Print : public CharIterator { public: IBoolean applyTo(char const-,-) { cout << c; return True; } }; /*-------------------------------------------------------------*\ | Test variables | \*-------------------------------------------------------------*/ char *String = "Teqikbonfxjmsoe aydg.o zlarv pu o wr cu h"; /*-------------------------------------------------------------*\ | Main program | \*-------------------------------------------------------------*/ int main() { Deque D; char C; IBoolean ReadFront = True; int i; // Put all characters in the deque. // Then read it, changing the end to read from // with every character read. cout << endl << "Adding characters to the back end of the deque:" << endl; for (i = 0; String[i] != 0; i ++) { D.addAsLast(String[i]); cout << String[i]; } cout << endl << endl << "Current number of elements in the deque: " << D.numberOfElements() << endl; cout << endl << "Contents of the deque:" << endl; Print Aprinter; D.allElementsDo(Aprinter); cout << endl << endl << "Reading from the deque one element from front, one " << "from back, and so on:" << endl; while (!D.isEmpty()) { if (ReadFront) // Read from front of Deque { C = D.firstElement(); // Get the character D.removeFirst(); // Delete it from the Deque } else { C = D.lastElement(); D.removeLast(); } cout << C; ReadFront = !ReadFront; // Switch to other end of Deque } cout << endl; return(0); } The program produces the following output: Adding characters to the back end of the deque: Teqikbonfxjme vralz o.gdya eospu o wr cu h Current number of elements in the deque: 43 Contents of the deque: Teqikbonfxjme vralz o.gdya eospu o wr cu h Reading from the deque one element from front, one from back, and so on: The quick brown fox jumpes over a lazy dog. ═══ 5.1.5. Equality Sequence ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.5.1. Class Description - Equality Sequence ═══ An equality sequence is an ordered collection of elements. The elements are arranged so that each collection has a first and a last element, each element except the last has a next element, and each element but the first has a previous element. An equality sequence supports element equality, which gives you the ability, for example, to search for particular elements. An example of using an equality sequence is a program that calculates members of the Fibonacci sequence and places them in a collection. Multiple elements of the same value are allowed. For example, the sequence begins with two instances of the value 1. You can search for a given element, for example 8, and find out what element follows it in the sequence. Element equality allows you to do this, using the locate() and setToNext() functions. ═══ Derivation ═══ Collection Equality Collection Sequential Collection Equality Sequence Figure Combination of Flat Collection Properties illustrates the properties of an equality sequence and its relationship to other flat collections. ═══ Variants and Header Files ═══ IEqualitySequence, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the iveqseq.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IEqualitySequence ieqseq.h Linked sequence IGEqualitySequence ieqseq.h Linked sequence IEqualitySequence- ieqts.h Tabular sequence OnTabularSequence IGEqualitySequence ieqts.h Tabular sequence IEqualitySequence- ieqds.h Diluted sequence OnDilutedSequence IGEqualitySequence ieqds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for equality sequence:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addAsFirst  addAsLast  addAsNext  addAsPrevious  addAtPosition  allElementsDo  anyElement  compare  contains  containsAllFrom  elementAt  elementAtPosition  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  locate  locateFirst  locateLast  locateNext  locateOrAdd  locatePrevious  maxNumberOfElements  newCursor  numberOfElements  numberOfOccurrences  position  remove  removeAll  removeAllOccurrences  removeAt  removeAtPosition  removeFirst  removeLast  replaceAt  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  sort Equality sequence also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.5.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for equality sequences:  Equality sequence  Equality sequence on tabular sequence  Equality sequence on diluted sequence ═══ 5.1.5.2.1. Equality Sequence ═══ IEqualitySequence IGEqualitySequence The default implementation of IEqualitySequence requires the following element functions: Element Type  Assignment  Equality test ═══ 5.1.5.2.2. Equality Sequence on Tabular Sequence ═══ IEqualitySequenceOnTabularSequence IGEqualitySequenceOnTabularSequence The implementation of the class IEqualitySequenceOnTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test ═══ 5.1.5.2.3. Equality Sequence on Diluted Sequence ═══ IEqualitySequenceOnDilutedSequence IGEqualitySequenceOnDilutedSequence The implementation of the class IEqualitySequenceOnDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test ═══ 5.1.5.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAEqSeq, which is found in the iaeqseq.h header file, or the corresponding reference class, IREqSeq, which is found in the ireqseq.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.5.3.1. Template Arguments and Required Functions ═══ IAEqSequ IREqSequ The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.6. Heap ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.6.1. Class Description - Heap ═══ A heap is an unordered collection of zero or more elements with no key. Element equality is not supported. Multiple elements are supported. The type and value of the elements are irrelevant, and have no effect on the behavior of the heap. You can compare using a heap collection to managing the scrap metal entering a scrapyard. Pieces of scrap are placed in the heap in an arbitrary location, and an element can be added multiple times (for example, the rear left fender from a particular kind of car). When a customer requests a certain amount of scrap, elements are removed from the heap in an arbitrary order until the required amount is reached. You cannot search for a specific piece of scrap except by examining each piece of scrap in the heap and manually comparing it to the piece you are looking for. Figure Combination of Flat Collection Properties illustrates the properties of a heap and its relationship to other flat collections. ═══ Derivation ═══ Collection Heap ═══ Variants and Header Files ═══ IHeap, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivheap.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IHeap iheap.h Linked sequence IGHeap iheap.h Linked sequence IHeapOnTabularSequence iheapts.h Tabular sequence IGHeapOnTabularSequence iheapts.h Tabular sequence IHeapOnDilutedSequence iheapds.h Diluted sequence IGHeapOnDilutedSequence iheapds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for heap:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  allElementsDo  anyElement  elementAt  isBounded  isEmpty  isFull  maxNumberOfElements  newCursor  numberOfElements  removeAll  removeAt  replaceAt  setToFirst  setToNext Heap also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.6.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for heaps:  Heap  Heap on Tabular Sequence  Heap on Diluted Sequence ═══ 5.1.6.2.1. Heap ═══ IHeap IGHeap The default implementation of IHeap requires the following element functions: Element Type  Copy constructor  Assignment ═══ 5.1.6.2.2. Heap on Tabular Sequence ═══ IHeapOnTabularSequence IGHeapOnTabularSequence The implementation of the class IHeapOnTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Assignment ═══ 5.1.6.2.3. Heap on Diluted Sequence ═══ IHeapOnDilutedSequence IGHeapOnDilutedSequence The implementation of the class IHeapOnDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor ═══ 5.1.6.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAHeap, which is found in the iaheap.h header file, or the corresponding reference class, IRHeap, which is found in the irheap.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.6.3.1. Template Arguments and Required Functions ═══ IAHeap IRHeap The concrete base class is one of the heap classes. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.6.4. Coding Example for Heap ═══ See Coding Example for Key Sorted Set for an example of using a heap. ═══ 5.1.7. Key Bag ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.7.1. Class Description - Key Bag ═══ A key bag is an unordered collection of zero or more elements that have a key. Multiple elements are supported. An example of using a key bag is a program that manages the distribution of combination locks to members of a fitness club. The element key is the number that is printed on the back of each combination lock. Each element also has data members for the club member's name, member number, and so on. When you join the club, you are given one of the available combination locks, and your name, member number, and the number on the combination lock are entered into the collection. Because a given number on a combination lock may appear on several locks, the program allows the same lock number to be added to the collection multiple times. When you return a lock because you are leaving the club, the program finds each element whose key matches your lock's serial number, and deletes one such element that has your name associated with it. Figure Behavior of add for Unique and Miltiple Collections illustrates the differences in behavior between map, relation, key set, and key bag when identical elements and elements with the same key are added. ═══ Derivation ═══ Collection Key Collection Key Bag Figure Combination of Flat Collection Properties gives an overview of the properties of a key bag and its relationship to other flat collections. ═══ Variants and Header Files ═══ IKeyBag, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivkeybag.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IKeyBag ikeybag.h Hash table IGKeyBag ikeybag.h Hash table IHashKeyBag ihshkb.h Hash table IGHashKeyBag ihshkb.h Hash table ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for key bag:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addOrReplaceElementWithKey  allElementsDo  anyElement  containsAllKeysFrom  containsElementWithKey  elementAt  elementWithKey  isBounded  isEmpty  isFull  key  locateElementWithKey  locateNextElementWithKey  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfDifferentKeys  numberOfElements  numberOfElementsWithKey  removeAll  removeAllElementsWithKey  removeAt  removeElementWithKey  replaceAt  replaceElementWithKey  setToFirst  setToNext  setToNextWithDifferentKey Key Bag also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.7.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for key bags:  Key bag  Hash key bag ═══ 5.1.7.2.1. Key Bag ═══ IKeyBag IGKeyBag The default implementation of the class IKeyBag requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type  Equality test  Hash function ═══ 5.1.7.2.2. Hash Key Bag ═══ IHashKeyBag IGHashKeyBag The implementation of the class IHashKeyBag requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type  Equality test  Hash function ═══ 5.1.7.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAKeyBag, which is found in the iakeybag.h header file, or the corresponding reference class, IRKeyBag, which is found in the irkeybag.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.7.3.1. Template Arguments and Required Functions ═══ IAKeyBag IRKeyBag The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.7.4. Coding Example for Key Bag ═══ The following program uses the default key bag class, IKeyBag, to create a key bag for storing observations made on animals. The key of the class is the name of the animal. The program produces various reports regarding the observations. Then it removes all the extinct animals, which are stored in a sequence, from the key bag. The program uses the add() function to fill the key bag and the forCursor macro to display the observations. It uses the following functions to produce the reports:  numberOfElements()  numberOfDifferentKeys()  numberOfElementsWithKey()  locateElementWithKey()  setToNextElementWithKey()  removeAllElementsWithKey() // animals.C - An example of using a Key Bag #include // Class Animal: #include "animal.h" // Let's use the default Key Bag: #include typedef IKeyBag Animals; // For keys let's use the default Sequence: #include typedef ISequence Names; main() { Animals animals; Animals::Cursor animalsCur1(animals), animalsCur2(animals); animals.add(Animal("bear", "heavy")); animals.add(Animal("bear", "strong")); animals.add(Animal("dinosaur", "heavy")); animals.add(Animal("dinosaur", "huge")); animals.add(Animal("dinosaur", "extinct")); animals.add(Animal("eagle", "black")); animals.add(Animal("eagle", "strong")); animals.add(Animal("lion", "dangerous")); animals.add(Animal("lion", "strong")); animals.add(Animal("mammoth", "long haired")); animals.add(Animal("mammoth", "extinct")); animals.add(Animal("sabre tooth tiger", "extinct")); animals.add(Animal("zebra", "striped")); // Display all elements in animals: cout << endl << "All our observations on animals:" << endl; forCursor(animalsCur1) cout << " " << animalsCur1.element(); cout << endl << endl << "Number of observations on animals: " << animals.numberOfElements() << endl; cout << endl << "Number of different animals: " << animals.numberOfDifferentKeys() << endl; Names namesOfExtinct(animals.numberOfDifferentKeys()); Names::Cursor extinctCur1(namesOfExtinct); animalsCur1.setToFirst(); do { IString name = animalsCur1.element().name(); cout << endl << "We have " << animals.numberOfElementsWithKey(name) << " observations on " << name << ":" << endl; // We need to use a separate cursor here // because otherwise animalsCur1 would become // invalid after last locateNextElement...() animals.locateElementWithKey(name, animalsCur2); do { IString attribute = animalsCur2.element().attribute(); cout << " " << attribute << endl; if (attribute == "extinct") namesOfExtinct.add(name); } while (animals.locateNextElementWithKey(name, animalsCur2)); } while (animals.setToNextWithDifferentKey(animalsCur1)); // Remove all observations on extinct animals: forCursor(extinctCur1) animals.removeAllElementsWithKey(extinctCur1.element()); // Display all elements in animals: cout << endl << endl << "After removing all observations on extinct animals:" << endl; forCursor(animalsCur1) cout << " " << animalsCur1.element(); cout << endl << "Number of observations on animals: " << animals.numberOfElements() << endl; cout << endl << "Number of different animals: " << animals.numberOfDifferentKeys() << endl; return 0; } The program produces the following output: All our observations on animals: The eagle is strong. The eagle is black. The bear is strong. The bear is heavy. The zebra is striped. The mammoth is extinct. The mammoth is long haired. The lion is strong. The lion is dangerous. The dinosaur is extinct. The dinosaur is huge. The dinosaur is heavy. The sabre tooth tiger is extinct. Number of observations on animals: 13 Number of different animals: 7 We have 2 observations on eagle: strong black We have 2 observations on bear: strong heavy We have 1 observations on zebra: striped We have 2 observations on mammoth: extinct long haired We have 2 observations on lion: strong dangerous We have 3 observations on dinosaur: extinct huge heavy We have 1 observations on sabre tooth tiger: extinct After removing all observations on extinct animals: The eagle is strong. The eagle is black. The bear is strong. The bear is heavy. The zebra is striped. The lion is strong. The lion is dangerous. Number of observations on animals: 7 Number of different animals: 4 ═══ 5.1.8. Key Set ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.8.1. Class Description - Key Set ═══ A key set is an unordered collection of zero or more elements that have a key. Element equality is not supported. Only unique elements are supported, in terms of their key. An example of using a key set is a program that allocates rooms to patrons checking into a hotel. The room number serves as the element's key, and the patron's name is a data member of the element. When you check in at the front desk, the clerk pulls a room key from the board, and enters that key's number and your name into the collection. When you return the key at check-out time, the record for that key is removed from the collection. You cannot add an element to the collection that is already present, because there is only one key for each room. If you attempt to add an element that is already present, the add() function returns False to indicate that the element was not added. Figure Behavior of add for Unique and Miltiple Collections illustrates the differences in behavior between map, relation, key set, and key bag when identical elements and elements with the same key are added. Figure Combination of Flat Collection Properties gives an overview of the properties of a key set and its relationship to other flat collections. ═══ Derivation ═══ Collection Key Collection Key Set ═══ Variants and Header Files ═══ IKeySet, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivkeyset.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IKeySet ikeyset.h AVL tree IGKeySet ikeyset.h AVL tree IKeySetOnBSTKeySortedSet iksbst.h B* tree IGKeySetOnBSTKeySortedSet iksbst.h B* tree IHashKeySet ihshks.h Hash table IGHashKeySet ihshks.h Hash table IKeySetOnSortedLinkedSequence ikssls.h Linked sequence IGKeySetOnSortedLinkedSequence ikssls.h Linked sequence IKeySetOnSortedTabularSequence ikssts.h Tabular sequence IGKeySetOnSortedTabularSequence ikssts.h Tabular sequence IKeySetOnSortedDilutedSequence ikssds.h Diluted sequence IGKeySetOnSortedDilutedSequence ikssds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for key set:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addOrReplaceElementWithKey  allElementsDo  anyElement  containsAllKeysFrom  containsElementWithKey  elementAt  elementWithKey  isBounded  isEmpty  isFull  key  locateElementWithKey  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfElements  removeAll  removeAt  removeElementWithKey  replaceAt  replaceElementWithKey  setToFirst  setToNext Key set also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.8.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for key sets:  Key set  Key set on B* key sorted set  Hash key set  Key set on sorted linked sequence  Key set on sorted tabular sequence  Key set on sorted diluted sequence ═══ 5.1.8.2.1. Key Set ═══ IKeySet IGKeySet The default implementation of the class IKeySet requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.8.2.2. Key Set on B* Key Sorted Set ═══ IKeySetOnBSTKeySortedSet IGKeySetOnBSTKeySortedSet The implementation of the class IKeySetOnBSTKeySortedSet requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.8.2.3. Hash Key Set ═══ IHashKeySet IGHashKeySet The implementation class IHashKeySet requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type  Equality test  Hash function ═══ 5.1.8.2.4. Key Set on Sorted Linked Sequence ═══ IKeySetOnSortedLinkedSequence IGKeySetOnSortedLinkedSequence The implementation of the class IKeySetOnSortedLinkedSequence requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.8.2.5. Key Set on Sorted Tabular Sequence ═══ IKeySetOnSortedTabularSequence IGKeySetOnSortedTabularSequence The implementation of the class IKeySetOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.8.2.6. Key Set on Sorted Diluted Sequence ═══ IKeySetOnSortedDilutedSequence IGKeySetOnSortedDilutedSequence The implementation of the class IKeySetOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.8.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAKeySet, which is found in the iakeyset.h header file, or the corresponding reference class, IRKeySet, which is found in the irkeyset.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.8.3.1. Template Arguments and Required Functions ═══ IAKeySet IRKeySet The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.8.4. Coding Example for Key Set ═══ The following program implements a key set using the default class, IKeySet. The program adds four elements to the key set and then removes one element by looking for a key. If an exception occurs, it displays the exception name and description. The program uses cursor iteration (the forCursor macro) to display the contents of the collection. To add and remove elements, it uses the add() function and the removeElementWithKey() function. // intkyset.C - An example of using a Key Set #include #include #include #include // Class DemoElement: #include "demoelem.h" typedef IKeySet < DemoElement,int > TestKeySet; ostream & operator<< ( ostream & sout, TestKeySet const & t){ sout << t.numberOfElements() << " elements are in the set:\n"; TestKeySet::Cursor cursor (t); // forCursor(c) // expands to // for ((c).setToFirst (); (c).isValid (); (c).setToNext ()) forCursor (cursor) sout << " " << cursor.element() << "\n"; return sout << "\n"; } main(){ TestKeySet t; try { t.add(DemoElement(1,1)); t.add(DemoElement(2,4711)); t.add(DemoElement(3,1)); t.add(DemoElement(4,443)); cout << t; t.removeElementWithKey (3); cout << t; } catch (IException & exception) { cout << exception.name() << " : " << exception.text(); } return 0; } The program produces the following output: 4 elements are in the set: 1,1 2,4711 3,1 4,443 3 elements are in the set: 1,1 2,4711 4,443 ═══ 5.1.9. Key Sorted Bag ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.9.1. Class Description - Key Sorted Bag ═══ A key sorted bag is an ordered collection of zero or more elements that have a key. Elements are sorted according to the value of their key field. Element equality is not supported. Multiple elements are supported. An example of using a key sorted bag is a program that maintains a list of families, sorted by the number of family members in each family. The key is the number of family members. You can add an element whose key is already in the collection (because two families can have the same number of members), and you can generate a list of families sorted by size. You cannot locate a family except by its key, because a key sorted bag does not support element equality. Figure Combination of Flat Collection Properties gives an overview of the properties of a key sorted bag and its relationship to other flat collections. ═══ Derivation ═══ Collection Ordered Collection Key Collection Sorted Collection Key Sorted Collection Key Sorted Bag ═══ Variants and Header Files ═══ IKeySortedBag, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivksbag.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IKeySortedBag iksbag.h Linked sequence IGKeySortedBag iksbag.h Linked sequence IKeySortedBagOnSortedTabularSequence iksbsts.h Tabular sequence IGKeySortedBagOnSortedTabularSequence iksbsts.h Tabular sequence IKeySortedBagOnSortedDilutedSequence iksbsds.h Diluted sequence IGKeySortedBagOnSortedDilutedSequence iksbsds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for key sorted bag:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addOrReplaceElementWithKey  allElementsDo  anyElement  compare  containsAllKeysFrom  containsElementWithKey  elementAt  elementAtPosition  elementWithKey  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  key  lastElement  locateElementWithKey  locateNextElementWithKey  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfDifferentKeys  numberOfElements  numberOfElementsWithKey  position  removeAll  removeAllElementsWithKey  removeAt  removeAtPosition  removeElementWithKey  removeFirst  removeLast  replaceAt  replaceElementWithKey  setToFirst  setToLast  setToNext  setToNextWithDifferentKey  setToPosition  setToPrevious Key sorted bag also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.9.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for key sorted bags:  Key Sorted Bag  Key Sorted Bag on Tabular Sequence  Key Sorted Bag on Diluted Sequence ═══ 5.1.9.2.1. Key Sorted Bag ═══ IKeySortedBag IGKeySortedBag The implementation of the class IKeySortedBag requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.9.2.2. Key Sorted Bag on Tabular Sequence ═══ IKeySortedBagOnTabularSequence IGKeySortedBagOnTabularSequence The implementation of the class IKeySortedBagOnTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.9.2.3. Key Sorted Bag on Diluted Sequence ═══ IKeySortedBagOnDilutedSequence IGKeySortedBagOnDilutedSequence The implementation of the class IKeySortedBagOnDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.9.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAKeySortedBag, which is found in the iaksbag.h header file, or the corresponding reference class, IRKeySortedBag, which is found in the irksbag.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.9.3.1. Template Arguments and Required Functions ═══ IAKSBag IRKSBag The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.9.4. Coding Example for Key Sorted Bag ═══ The following program illustrates the use of a key sorted bag. The program determines the number of words that have the same length in a phrase. It stores the words of the phrase in a key sorted bag that it implements using the default class, IKeySortedBag. The program makes the key the length of the word. Because of the properties of a key sorted bag, it sorts the words by their length (the key), and it stores all duplicate words. The program determines the number of different word lengths using the numberOfDifferentKeys() function. It uses the numberOfElementsWithKey() function and the setToNextWithDifferentKey() function to iterate through the collection and count the number of words with the same length. // wordbag.C - An example of using a Key Sorted Bag #include // Class Word #include "toyword.h" // Let's use the defaults: #include typedef IKeySortedBag WordBag; int main() { IString phrase[] = {"people", "who", "live", "in", "glass", "houses", "should", "not", "throw", "stones"}; const size_t phraseWords = sizeof(phrase) / sizeof(IString); WordBag wordbag(phraseWords); for (int cnt=0; cnt < phraseWords; cnt++) { unsigned keyValue = phrase[cnt].length(); Word theWord(phrase[cnt],keyValue); wordbag.add (theWord); } cout << "Contents of our WordBag sorted by number of letters:" << endl; WordBag::Cursor wordBagCursor(wordbag); forCursor(wordBagCursor) cout << "WB: " << wordBagCursor.element().getWord() << endl; cout << endl << "Our phrase has " << phraseWords << " words." << endl ; cout << "In our WordBag are " << wordbag.numberOfElements() << " words." << endl << endl; cout << "There are " << wordbag.numberOfDifferentKeys() << " different word lengths." << endl << endl; wordBagCursor.setToFirst(); do { unsigned letters = wordbag.key(wordBagCursor.element()); cout << "There are " << wordbag.numberOfElementsWithKey(letters) << " words with " << letters << " letters." << endl; } while (wordbag.setToNextWithDifferentKey(wordBagCursor)); return 0; } This program produces the following output: Contents of our WordBag sorted by number of letters: WB: in WB: who WB: not WB: live WB: glass WB: throw WB: people WB: houses WB: should WB: stones Our phrase has 10 words. In our WordBag are 10 words. There are 5 different word lengths. There are 1 words with 2 letters. There are 2 words with 3 letters. There are 1 words with 4 letters. There are 2 words with 5 letters. There are 4 words with 6 letters. ═══ 5.1.10. Key Sorted Set ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.10.1. Class Description - Key Sorted Set ═══ A key sorted set is an ordered collection of zero or more elements that have a key. Elements are sorted according to the value of their key field. Element equality is not supported. Only elements with unique keys are supported. A request to add an element whose key already exists is ignored. An example of using a key sorted set is a program that keeps track of canceled credit card numbers and the individuals to whom they are issued. Each card number occurs only once, and the collection is sorted by card number. When a merchant enters a customer's card number into a point-of-sale terminal, the collection is checked to see if that card number is listed in the collection of canceled cards. If it is found, the name of the individual is shown, and the merchant is given directions for contacting the card company. If the card number is not found, the transaction can proceed because the card is valid. A list of canceled cards is printed out each month, sorted by card number, and distributed to all merchants who do not have an automatic point-of-sale terminal installed. Figure Combination of Flat Collection Properties gives an overview of the properties of a key sorted set and its relationship to other flat collections. ═══ Derivation ═══ Collection Ordered Collection Key Collection Sorted Collection Key Sorted Collection Key Sorted Set ═══ Variants and Header Files ═══ IKeySortedSet, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivksset.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IKeySortedSet iksset.h AVL tree IGKeySortedSet iksset.h AVL tree IAVLKeySortedSet iavlkss.h AVL tree IGAVLKeySortedSet iavlkss.h AVL tree IBSTKeySortedSet ibstkss.h B* tree IGBSTKeySortedSet ibstkss.h B* tree IKeySortedSetOn- iksssls.h Linked sequence SortedLinkedSequence IGKeySortedSetOn- iksssls.h Linked sequence SortedLinkedSequence IKeySortedSetOn- iksssts.h Tabular sequence SortedTabularSequence IGKeySortedSetOn- iksssts.h Tabular sequence SortedTabularSequence IKeySortedSetOn- iksssds.h Diluted sequence SortedDilutedSequence IGKeySortedSetOn- iksssds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for key sorted set:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addOrReplaceElementWithKey  allElementsDo  anyElement  compare  containsAllKeysFrom  containsElementWithKey  elementAt  elementAtPosition  elementWithKey  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  key  lastElement  locateElementWithKey  locateNextElementWithKey  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfElements  position  removeAll  removeAt  removeAtPosition  removeElementWithKey  removeFirst  removeLast  replaceAt  replaceElementWithKey  setToFirst  setToLast  setToNext  setToPosition  setToPrevious Key Sorted Set also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.10.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for key sorted sets:  Key sorted set  AVL key sorted set  B* key sorted set  Key sorted set on sorted linked sequence  Key sorted set on sorted tabular sequence  Key sorted set on Sorted diluted sequence ═══ 5.1.10.2.1. Key Sorted Set ═══ IKeySortedSet IGKeySortedSet The implementation of the class IKeySortedSet requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.10.2.2. AVL Key Sorted Set. ═══ IAVLKeySortedSet IGAVLKeySortedSet The implementation of the class IAVLKeySortedSet requires the following element and key-type functions: Element Type  Copy constructor  Assignment  Destructor  Key access Key Type Ordering relation ═══ 5.1.10.2.3. B* Key Sorted Set ═══ IBSTKeySortedSet IBSTKeySortedSet The implementation of the class IBSTKeySortedSet requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.10.2.4. Key Sorted Set on Sorted Linked Sequence ═══ IKeySortedSetOnSortedLinkedSequence IGKeySortedSetOnSortedLinkedSequence The implementation of the class IKeySortedSetOnSortedLinkedSequence requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.10.2.5. Key Sorted Set on Sorted Tabular Sequence ═══ IKeySortedSetOnSortedTabularSequence IGKeySortedSetOnSortedTabularSequence The implementation of the class IKeySortedSetOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.10.2.6. Key Sorted Set on Sorted Diluted Sequence ═══ IKeySortedSetOnSortedDilutedSequence IGKeySortedSetOnSortedDilutedSequence The implementation of the class IKeySortedSetOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.10.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAKeySortedSet, which is found in the iaksset.h header file, or the corresponding reference class, IRKeySortedSet, which is found in the irksset.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.10.3.1. Template Arguments and Required Functions ═══ IAKeySortedSet IRKeySortedSet The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.10.4. Coding Example for Key Sorted Set ═══ The following program uses the default classes for a key sorted set and a heap, IKeySortedSet and IHeap, to track parcels for a delivery service. It uses a key sorted set to record the parcels that are currently in circulation. The fast access of a sorted collection is not necessary to keep track of the delivered parcels, so the program uses a heap to keep track of them. The parcel element contains three data members: one of type PlaceTime that stores the origin time and place of the parcel, another of type PlaceTime that stores the current time and place of the parcel, and one of type ToyString that stores the destination. The function update() adds parcels that have arrived at their destinations to the heap of delivered parcels, and removes them from the key sorted set for circulating parcels. The program uses the add() function to update and the removeAll() function to remove elements from the key sorted set. // parcel.C - An example of using a Key Sorted Set and a Heap #include #include "parcel.h" // Let's use the default KeySorted Set: #include // Let's use the default Heap: #include typedef IKeySortedSet ParcelSet; typedef IHeap ParcelHeap; ostream& operator<<(ostream&, ParcelSet const&); ostream& operator<<(ostream&, ParcelHeap const&); void update(ParcelSet&, ParcelHeap&); main() { ParcelSet circulating; ParcelHeap delivered; int today = 8; circulating.add(Parcel("London", "Athens", today, "26LoAt")); circulating.add(Parcel("Amsterdam", "Toronto", today += 2, "27AmTo")); circulating.add(Parcel("Washington", "Stockholm", today += 5, "25WaSt")); circulating.add(Parcel("Dublin", "Kairo", today += 1, "25DuKa")); update(circulating, delivered); cout << "\nThe situation at start:\n"; cout << "Parcels in circulation:\n" << circulating; today ++; circulating.elementWithKey("27AmTo").arrivedAt( "Atlanta", today); circulating.elementWithKey("25WaSt").arrivedAt( "Amsterdam", today); circulating.elementWithKey("25DuKa").arrivedAt( "Paris", today); update(circulating, delivered); cout << "\n\nThe situation at day " << today << ":\n"; cout << "Parcels in circulation:\n" << circulating; today ++; // One day later ... circulating.elementWithKey("27AmTo").arrivedAt("Chicago", today); // As in real life, one parcel gets lost: circulating.removeElementWithKey("26LoAt"); update(circulating, delivered); cout << "\n\nThe situation at day " << today << ":\n"; cout << "Parcels in circulation:\n" << circulating; today ++; circulating.elementWithKey("25WaSt").arrivedAt("Oslo", today); circulating.elementWithKey("25DuKa").arrivedAt("Kairo", today); // New parcels are shipped. circulating.add(Parcel("Dublin", "Rome", today, "27DuRo")); // Let's try to add one with a key already there. // The KeySsorted Set should ignore it: circulating.add(Parcel("Nowhere", "Nirvana", today, "25WaSt")); update(circulating, delivered); cout << "\n\nThe situation at day " << today << ":\n"; cout << "Parcels in circulation:\n" << circulating; cout << "Parcels delivered:\n" << delivered; // Now we make all parcels arrive today: today ++; ParcelSet::Cursor circulatingcursor(circulating); forCursor(circulatingcursor) { circulating.elementAt(circulatingcursor).wasDelivered(today); } update(circulating, delivered); cout << "\n\nThe situation at day " << today << ":\n"; cout << "Parcels in circulation:\n" << circulating; cout << "Parcels delivered:\n" << delivered; if (circulating.isEmpty()) cout << "\nAll parcels were delivered.\n"; else cout << "\nSomething very strange happened here.\n"; return 0; } ostream& operator<<(ostream& os, ParcelSet const& parcels) { ParcelSet::Cursor pcursor(parcels); forCursor(pcursor) { os << pcursor.element() << "\n"; } return os; } ostream& operator<<(ostream& os, ParcelHeap const& parcels) { ParcelHeap::Cursor pcursor(parcels); forCursor(pcursor) { os << pcursor.element() << "\n"; } return os; } Boolean wasDelivered(Parcel const& p, void* dp) { if ( p.lastArrival().city() == p.destination() ) { ((ParcelHeap*)dp)->add(p); return True; } else return False; } void update(ParcelSet& p, ParcelHeap& d) { p.removeAll(wasDelivered, &d); } The program produces the following output: The situation at start: Parcels in circulation: 25DuKa: From Dublin(day 16) to Kairo is at Dublin since day 16. 25WaSt: From Washington(day 15) to Stockholm is at Washington since day 15. 26LoAt: From London(day 8) to Athens is at London since day 8. 27AmTo: From Amsterdam(day 10) to Toronto is at Amsterdam since day 10. The situation at day 17: Parcels in circulation: 25DuKa: From Dublin(day 16) to Kairo is at Paris since day 17. 25WaSt: From Washington(day 15) to Stockholm is at Amsterdam since day 17. 26LoAt: From London(day 8) to Athens is at London since day 8. 27AmTo: From Amsterdam(day 10) to Toronto is at Atlanta since day 17. The situation at day 18: Parcels in circulation: 25DuKa: From Dublin(day 16) to Kairo is at Paris since day 17. 25WaSt: From Washington(day 15) to Stockholm is at Amsterdam since day 17. 27AmTo: From Amsterdam(day 10) to Toronto is at Chicago since day 18. The situation at day 19: Parcels in circulation: 25WaSt: From Washington(day 15) to Stockholm is at Oslo since day 19. 27AmTo: From Amsterdam(day 10) to Toronto is at Chicago since day 18. 27DuRo: From Dublin(day 19) to Rome is at Dublin since day 19. Parcels delivered: 25DuKa: From Dublin(day 16) to Kairo was delivered on day 19. The situation at day 20: Parcels in circulation: Parcels delivered: 25DuKa: From Dublin(day 16) to Kairo was delivered on day 19. 25WaSt: From Washington(day 15) to Stockholm was delivered on day 20. 27AmTo: From Amsterdam(day 10) to Toronto was delivered on day 20. 27DuRo: From Dublin(day 19) to Rome was delivered on day 20. All parcels were delivered. ═══ 5.1.11. Map ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.11.1. Class Description - Map ═══ A map is an unordered collection of zero or more elements that have a key. Element equality is supported and the values of the elements are relevant. Only elements with unique keys are supported. A request to add an element whose key already exists in another element of the collection causes an exception to be thrown. A request to add a duplicate element is ignored. An example of using a map is a program that translates integer values between the ranges of 0 and 20 to their written equivalents, or between written numbers and their numeric values. Two maps are created, one with the integer values as keys, one with the written equivalents as keys. You can enter a number, and that number is used as a key to locate the written equivalent. You can enter a written equivalent of a number, and that text is used as a key to locate the value. A given key always matches only one element. You cannot add an element with a key of 1 or "one" if that element is already present in the collection. Figure Behavior of add for Unique and Miltiple Collections illustrates the differences in behavior between map, relation, key set, and key bag when identical elements and elements with the same key are added. Figure Combination of Flat Collection Properties gives an overview of the properties of a map and its relationship to other flat collections. ═══ Derivation ═══ Collection Key Collection Equality Collection Equality Key Collection Map ═══ Variants and Header Files ═══ IMap, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivmap.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IMap imap.h AVL tree IGMap imap.h AVL tree IMapOnBSTKeySortedSet imapbst.h B* tree IGMapOnBSTKeySortedSet imapbst.h B* tree IMapOnSortedLinkedSequence imapsls.h Linked sequence IGMapOnSortedLinkedSequence imapsls.h Linked sequence IMapOnSortedTabularSequence imapsts.h Tabular sequence IGMapOnSortedTabularSequence imapsts.h Tabular sequence IMapOnSortedDilutedSequence imapsds.h Diluted sequence IGMapOnSortedDilutedSequence imapsds.h Diluted sequence IMapOnHashKeySet imaphks.h Hash table IGMapOnHashKeySet imaphks.h Hash table ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for map:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addOrReplaceElementWithKey  addUnion  allElementsDo  anyElement  contains  containsAllFrom  containsAllKeysFrom  containsElementWithKey  differenceWith  elementAt  elementWithKey  intersectionWith  isBounded  isEmpty  isFull  key  locate  locateElementWithKey  locateOrAdd  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfElements  remove  removeAll  removeAt  removeElementWithKey  replaceAt  replaceElementWithKey  setToFirst  setToNext  unionWith Map also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.11.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for maps:  Map  Map on B* key sorted set  Map on sorted linked sequence  Map on sorted tabular sequence  Map on sorted diluted sequence  Map on hash key set ═══ 5.1.11.2.1. Map ═══ IMap IGMap The default implementation of the class IMap requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type Ordering relation ═══ 5.1.11.2.2. Map on B* Key Sorted Set ═══ IMapOnBSTKeySortedSet IGMapOnBSTKeySortedSet The implementation of the class IMapOnBSTKeySortedSet requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type Ordering relation ═══ 5.1.11.2.3. Map on Sorted Linked Sequence ═══ IMapOnSortedLinkedSequence IGMapOnSortedLinkedSequence The implementation of the class IMapOnSortedLinkedSequence requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type Ordering relation ═══ 5.1.11.2.4. Map on Sorted Tabular Sequence ═══ IMapOnSortedTabularSequence IGMapOnSortedTabularSequence The implementation of the class IMapOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type Ordering relation ═══ 5.1.11.2.5. Map on Sorted Diluted Sequence ═══ IMapOnSortedDilutedSequence IGMapOnSortedDilutedSequence The implementation of the class IMapOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type Ordering relation ═══ 5.1.11.2.6. Map on Hash Key Set ═══ IMapOnHashKeySet IGMapOnHashKeySet The implementation of the class IMapOnHashKeySet requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Key access Key Type  Equality test  Hash function ═══ 5.1.11.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAMap, which is found in the iamap.h header file, or the corresponding reference class, IRMap, which is found in the irmap.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.11.3.1. Template Arguments and Required Functions ═══ IAMap IRMap The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.11.4. Coding Example for Map ═══ The following program translates a string from EBCDIC to ASCII and from ASCII to EBCDIC. It uses two maps, one with the EBCDIC code as key (E2AMap) and one with the ASCII code as key (A2EMap). It converts from EBCDIC to ASCII by finding the element whose key matches the EBCDIC code in E2AMap (which has the EBCDIC code as key) and taking the ASCII code information from that element. It converts from ASCII to EBCDIC by finding the key that matches the ASCII code in A2EMap (which has the ASCII code as key) and taking the EBCDIC code information for that element. The program uses the add() function to build the maps and the elementWithKey() function to convert the characters. // transtab.C - An example of using a Map #include "transelm.h" // Get the standard operation classes: #include #include "trmapops.h" // char const translationTable[256] = .... #include "xebc2asc.h" /*-------------------------------------------------------------*\ | Now we define the two Map templates and two maps. | | We want both of them to be based on the Hashtable KeySet. | \*-------------------------------------------------------------*/ #include typedef IGMapOnHashKeySet < TranslationElement, char, TranslationOpsE2A > TransE2AMap; typedef IGMapOnHashKeySet < TranslationElement, char, TranslationOpsA2E > TransA2EMap; void display(char*, char*); int main(int argc, char* argv[]) { TransA2EMap A2EMap; TransE2AMap E2AMap; /*-----------------------------------------------------*\ | Load the translation table into both maps. | | The maps organize themselves according to the key | | specification already given. | \*-----------------------------------------------------*/ for (int i=0; i < 256; i++) { /* ascCode ebcCode */ TranslationElement te(translationTable[i], i ); E2AMap.add(te); A2EMap.add(te); } // What do we want to convert now? char* toConvert; if (argc > 1) toConvert = argv[1]; else toConvert = "$7 (=Dollar seven)"; size_t textLength = strlen(toConvert) +1; char* convertedToAsc = new char[textLength]; char* convertedToEbc = new char[textLength]; // Convert the strings in place, character by character for (i=0; toConvert[i] != 0x00; i++) { convertedToAsc[i] = E2AMap.elementWithKey(toConvert[i]).ascCode (); convertedToEbc[i] = A2EMap.elementWithKey(toConvert[i]).ebcCode (); } display("To convert", toConvert); display("After EBCDIC-ASCII conversion", convertedToAsc); display("After ASCII-EBCDIC conversion", convertedToEbc); delete[] convertedToAsc; delete[] convertedToEbc; return 0; } #include #include void display (char* title, char* text) { cout << endl << title << ':' << endl; cout << " Text: '" << text << "'" << endl; cout << " Hex: " << hex; for (int i=0; text[i] != 0x00; i++) { cout << (int)(unsigned) text[i] << " "; } cout << dec << endl; } The program produces the following output: To convert: Hex: 24 37 20 20 28 3d 44 6f 6c 6c 61 72 20 73 65 76 65 6e 29 After EBCDIC-ASCII conversion: Hex: 86 4 81 81 89 15 eb 3f 25 25 2f 94 81 b0 dd fc dd 3e 91 After ASCII-EBCDIC conversion: Hex: 5b f7 40 40 4d 7e c4 96 93 93 81 99 40 a2 85 a5 85 95 5d ═══ 5.1.12. Priority Queue ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.12.1. Class Description - Priority Queue ═══ A priority queue is a key sorted bag with restricted access. It is an ordered collection of zero or more elements. Keys and multiple elements are supported. Element equality is not supported. When an element is added, it is placed in the queue according to its key value or priority. The highest priority is indicated by the lowest key value. You can only remove the element with the highest priority. Within the priority queue, elements are sorted according to ascending key values, as in other key collections. You can only remove the element with the lowest key value. For elements with equal priority, the priority queue has a first-in, first-out behavior. An example of a priority queue is a program used to assign priorities to service calls in a heating repair firm. When a customer calls with a problem, a record with the customer's name and the seriousness of the situation is placed in a priority queue. When a service person becomes available, customers are chosen by the program beginning with those whose situation is most severe. In this example, a serious problem such as a nonfunctioning furnace would be indicated by a low value for the priority, and a minor problem such as a noisy radiator would be indicated by a high value for the priority. ═══ Derivation ═══ Key Sorted Collection Key Sorted Bag Priority Queue Note that priority queue is based on key sorted bag but is not actually derived from it or from the other classes shown above. The diagram does not show all bases of priority queue. See the figure "Abstract Class Hierarchy" in section Abstract Classes for an illustration. See Restricted Access for further details. ═══ Variants and Header Files ═══ IPriorityQueue, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivprioqu.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IPriorityQueue iprioqu.h Linked sequence IGPriorityQueue iprioqu.h Linked sequence IPriorityQueueOn- ipqusts.h Tabular sequence SortedTabularSequence IGPriorityQueueOn- ipqusts.h Tabular sequence SortedTabularSequence IPriorityQueueOn- ipqusds.h Diluted sequence SortedDilutedSequence IGPriorityQueueOn- ipqusds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for priority queue:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  allElementsDo  anyElement  compare  containsAllKeysFrom  containsElementWithKey  dequeue  elementAt  elementAtPosition  elementWithKey  enqueue  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  key  lastElement  locateElementWithKey  locateNextElementWithKey  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfDifferentKeys  numberOfElements  numberOfElementsWithKey  position  removeAll  removeFirst  setToFirst  setToLast  setToNext  setToNextWithDifferentKey  setToPosition  setToPrevious Priority queue also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.12.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for priority queues:  Priority queue  Priority queue on sorted tabular sequence  Priority queue on sorted diluted sequence ═══ 5.1.12.2.1. Priority Queue ═══ IPriorityQueue IGPriorityQueue The implementation of the class IPriorityQueue requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.12.2.2. Priority Queue on Sorted Tabular Sequence ═══ IPriorityQueueOnSortedTabularSequence IGPriorityQueueOnSortedTabularSequence The implementation of the class IPriorityQueueOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.12.2.3. Priority Queue on Sorted Diluted Sequence ═══ IPriorityQueueOnSortedDilutedSequence IGPriorityQueueOnSortedDilutedSequence The implementation of the class IPriorityQueueOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access Key Type Ordering relation ═══ 5.1.12.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAPriorityQueue, which is found in the iaprioqu.h header file, or the corresponding reference class, IRPriorityQueue, which is found in the irprioqu.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.12.3.1. Template Arguments and Required Functions ═══ IAPriorityQueue IRPriorityQueue The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.13. Queue ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.13.1. Class Description - Queue ═══ A queue is a sequence with restricted access. It is an ordered collection of elements with no key and no element equality. The elements are arranged so that each collection has a first and a last element, each element except the last has a next element, and each element but the first has a previous element. The type and value of the elements are irrelevant, and have no effect on the behavior of the collection. You can only add an element as the last element, and you can only remove the first element. Consequently, the elements of a queue are in chronological order. A queue is characterized by a first-in, first-out (FIFO) behavior. An example of using a queue is a program that processes requests for parts at the cash sales desk of a warehouse. A request for a part is added to the queue when the customer's order is taken, and is removed from the queue when an order picker receives the order form for the part. Using a queue collection in such an application ensures that all orders for parts are processed on a first-come, first-served basis. ═══ Derivation ═══ Collection Ordered Collection Sequential Collection Sequence Queue Note that queue is based on sequence but is not actually derived from it or from the other classes shown above. See Restricted Access for further details. ═══ Variants and Header Files ═══ IQueue, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivqueue.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IQueue iqueue.h Linked sequence IGQueue iqueue.h Linked sequence IQueueOnTabularSequence iquets.h Tabular sequence IGQueueOnTabularSequence iquets.h Tabular sequence IQueueOnDilutedSequence iqueds.h Diluted sequence IGQueueOnDilutedSequence iqueds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for queue:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addAsLast  allElementsDo  anyElement  compare  dequeue  elementAt  elementAtPosition  enqueue  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  maxNumberOfElements  newCursor  numberOfElements  position  removeAll  removeFirst  setToFirst  setToLast  setToNext  setToPosition Queue also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.13.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for queues:  Queue  Queue on tabular sequence  Queue on diluted sequence ═══ 5.1.13.2.1. Queue ═══ IQueue IGQueue The default implementation of the class IQueue requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.13.2.2. Queue on Tabular Sequence ═══ IQueueOnTabularSequence IGQueueOnTabularSequence The implementation of the class IDequeOnTabularSequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.13.2.3. Queue on Diluted Sequence ═══ IQueueOnDilutedSequence IGQueueOnDilutedSequence The implementation of the class IQueueOnDilutedSequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.13.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAQueue, which is found in the iaqueue.h header file, or the corresponding reference class, IRQueue, which is found in the irqueue.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.13.3.1. Template Arguments and Required Functions ═══ IAQueue IRQueue The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.14. Relation ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.14.1. Class Description - Relation ═══ A relation is an unordered collection of zero or more elements that have a key. Element equality is supported, and the values of the elements are relevant. The keys of the elements are not unique. You can add an element whether or not there is already an element in the collection with the same key. Figure Behavior of add for Unique and Miltiple Collections illustrates the differences in behavior between map, relation, key set, and key bag when identical elements and elements with the same key are added. An example of using a relation is a program that maintains a list of all your relatives, with an individual's relationship to you as the key. You can add an aunt, uncle, grandmother, daughter, father-in-law, and so on. You can add an aunt even if an aunt is already in the collection, because you can have several relatives who have the same relationship to you. (For unique relationships such as mother or father, your program would have to check the collection to make sure it did not already contain a family member with that key, before adding the family member.) You can locate a member of the family, but the family members are not in any particular order. Figure Combination of Flat Collection Properties gives an overview of the properties of a relation and its relationship to other flat collections. ═══ Derivation ═══ Collection Key Collection Equality Collection Equality Key Collection Relation ═══ Variants and Header Files ═══ IRelation is the default implementation variant. IGRelation is the default implementation with generic operations class. Both variants are declared in the header file irel.h. To use Visual Builder features with your collections, use IVRelation instead of IRelation, and IVGRelation instead of IGRelation. Both variants are declared in the header file ivrel.h. ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for relation:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addOrReplaceElementWithKey  addUnion  allElementsDo  anyElement  contains  containsAllFrom  containsAllKeysFrom  containsElementWithKey  differenceWith  elementAt  elementWithKey  intersectionWith  isBounded  isEmpty  isFull  key  locate  locateElementWithKey  locateNextElementWithKey  locateOrAdd  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfDifferentKeys  numberOfElements  numberOfElementsWithKey  remove  removeAll  removeAllElementsWithKey  removeAt  removeElementWithKey  replaceAt  replaceElementWithKey  setToFirst  setToNext  setToNextWithDifferentKey  unionWith Relation also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.14.2. Template Arguments and Required Functions ═══ IRelation IGRelation The default implementation of the class IRelation requires the following element functions: Element Type  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type  Equality test  Hash function ═══ 5.1.14.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IARelation, which is found in the iarel.h header file, or the corresponding reference class, IRRelation, which is found in the irrel.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.14.3.1. Template Arguments and Required Functions ═══ IARelation IRRelation The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.15. Sequence ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.15.1. Class Description - Sequence ═══ A sequence is an ordered collection of elements. The elements are arranged so that each collection has a first and a last element, each element except the last has a next element, and each element but the first has a previous element. The type and value of the elements are irrelevant, and have no effect on the behavior of the collection. Elements can be added and deleted from any position in the collection. Elements can be retrieved or replaced. A sequence does not support element equality or a key. If you require element equality for a sequence, you can use an equality sequence. An example of a sequence is a program that maintains a list of the words in a paragraph. The order of the words is obviously important, and you can add or remove words at a given position, but you cannot search for individual words except by iterating through the collection and comparing each word to the word you are searching for. You can add a word that is already present in the sequence, because a given word may be used more than once in a paragraph. Figure Combination of Flat Collection Properties illustrates the properties of a sequence and its relationship to other flat collections. ═══ Derivation ═══ Collection Ordered Collection Sequential Collection Sequence ═══ Variants and Header Files ═══ ISequence, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivseq.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISequence iseq.h Linked sequence IGSequence iseq.h Linked sequence ILinkedSequence ilnseq.h Linked sequence IGLinkedSequence ilnseq.h Linked sequence ITabularSequence itbseq.h Tabular sequence IGTabularSequence itbseq.h Tabular sequence IDilutedSequence itdseq.h Diluted sequence IGDilutedSequence itdseq.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for sequence:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addAsFirst  addAsLast  addAsNext  addAsPrevious  addAtPosition  allElementsDo  anyElement  compare  elementAt  elementAtPosition  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  maxNumberOfElements  newCursor  numberOfElements  position  removeAll  removeAt  removeAtPosition  removeFirst  removeLast  replaceAt  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  sort Sequence also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.15.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sequences:  Sequence  linked sequence  tabular sequence  diluted sequence ═══ 5.1.15.2.1. Sequence ═══ ISequence IGSequence The default implementation of ISequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.15.2.2. Linked Sequence ═══ ILinkedSequence IGLinkedSequence The implementation of the class ILinkedSequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.15.2.3. Tabular Sequence ═══ ITabularSequence IGTabularSequence The implementation of the class ITabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment ═══ 5.1.15.2.4. Diluted Sequence ═══ IDilutedSequence IGDilutedSequence The implementation of the class IDilutedSequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.15.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASequence, which is found in the iaseq.h header file, or the corresponding reference class, IRSequence, which is found in the irseq.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.15.3.1. Template Arguments and Required Functions ═══ IASequence IRSequence The concrete base class is one of the sequence classes. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.15.4. Coding Example for Sequence ═══ The following program creates a sequence using the default sequence class, ISequence, and adds a number of words to it. The program sorts the words in ascending order and searches the sequence for the word "fox". Finally, it prints the word that is in position 9. The program uses two types of iteration. It uses the iterator class, IIterator, when printing the sequence, and it uses cursor iteration when searching for a word. With the iterator object, the program uses the allElementsDo() function. With cursor iteration, it uses the setToFirst(), isValid(), and setToNext() functions. It uses the elementAt() and elementAtPosition() functions to find words in the sequence. // wordseq.C - An example of using a Sequence #include // Get definition and declaration of class Word: #include "toyword.h" // Define a compare function to be used for sort: inline long wordCompare ( Word const& w1, Word const& w2) { return (w1.getWord() > w2.getWord()); } // We want to use the default Sequence called ISequence. #include typedef ISequence WordSeq; typedef IIterator WordIter; // Test variables to put into the Sequence. IString wordArray[9] = { "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog" }; // Our Iterator class for use with allElementsDo(). // The alternative method of iteration, using a cursor, does // not need such an iterator class. class PrintClass : public WordIter { public: IBoolean applyTo(Word &w) { cout << endl << w.getWord(); // Print the string return(True); } }; // Main program int main() { WordSeq WL; WordSeq::Cursor cursor(WL); PrintClass Print; int i; for (i = 0; i < 9; i ++) { // Put all strings into Sequence Word aWord(wordArray[i]); // Fill object with right value WL.addAsLast(aWord); // Add it to the Sequence at end } cout << endl << "Sequence in initial order:" << endl; WL.allElementsDo(Print); WL.sort(wordCompare); // Sort the Sequence ascending cout << endl << endl << "Sequence in sorted order:" << endl; WL.allElementsDo(Print); // Use iteration via cursor now: cout << endl << endl << "Look for \"fox\" in the Sequence:" << endl; for (cursor.setToFirst(); cursor.isValid() && (WL.elementAt(cursor).getWord() != "fox"); cursor.setToNext()); if (WL.elementAt(cursor).getWord() != "fox") { cout << endl << "The element was not found." << endl; } else { cout << endl << " The element was found." << endl; } cout << endl << "The element at position 9: " << WL.elementAtPosition(9).getWord() << endl; return(0); } The program produces the following output: Sequence in initial order: the quick brown fox jumps over a lazy dog Sequence in sorted order: a brown dog fox jumps lazy over quick the Look for "fox" in the Sequence: The element was found. The element at position 9: the ═══ 5.1.16. Set ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.16.1. Class Description - Set ═══ A set is an unordered collection of zero or more elements with no key. Element equality is supported, and the values of the elements are relevant. Only unique elements are supported. A request to add an element that already exists is ignored. An example of a set is a program that creates a packing list for a box of free samples to be sent to a warehouse customer. The program searches a database of in-stock merchandise, and selects ten items at random whose price is below a threshold level. Each item is then added to the set. The set does not allow an item to be added if it is already present in the collection, ensuring that a customer does not get two samples of a single product. The set is not sorted, and elements of the set cannot be located by key. Figure Combination of Flat Collection Properties gives an overview of the properties of a set and its relationship to other flat collections. The set also offers typical set functions such as union, intersection, and difference. ═══ Derivation ═══ Collection Equality Collection Set ═══ Variants and Header Files ═══ ISet, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivset.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISet iset.h AVL tree IGSet iset.h AVL tree ISetOnBSTKeySortedSet isetbst.h B* tree IGSetOnBSTKeySortedSet isetbst.h B* tree ISetOnSortedLinkedSequence isetsls.h Linked sequence IGSetOnSortedLinkedSequence isetsls.h Linked sequence ISetOnSortedTabularSequence isetsts.h Tabular sequence IGSetOnSortedTabularSequence isetsts.h Tabular sequence ISetOnSortedDilutedSequence isetsds.h Diluted sequence IGSetOnSortedDilutedSequence isetsds.h Diluted sequence ISetOnHashKeySet isethks.h Hash table IGSetOnHashKeySet isethks.h Hash table ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for set:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addUnion  allElementsDo  anyElement  contains  containsAllFrom  differenceWith  elementAt  intersectionWith  isBounded  isEmpty  isFull  locate  locateOrAdd  maxNumberOfElements  newCursor  numberOfElements  remove  removeAll  removeAt  replaceAt  setToFirst  setToNext  unionWith Set also defines a cursor that inherits from IElementCursor. The members for IElementCursor are described in Cursor. ═══ 5.1.16.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sets:  Set  Set on B* key sorted set  Set on sorted linked sequence  Set on sorted tabular sequence  Set on sorted diluted sequence  Set on hash key set ═══ 5.1.16.2.1. Set ═══ ISet IGSet The default implementation of the class ISet requires the following element functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.16.2.2. Set on B* Key Sorted Set ═══ ISetOnBSTKeySortedSet IGSetOnBSTKeySortedSet The implementation of the class ISetOnBSTKeySortedSet requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.16.2.3. Set on Sorted Linked Sequence ═══ ISetOnSortedLinkedSequence IGSetOnSortedLinkedSequence The implementation of the class ISetOnSortedLinkedSequence requires the following element functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.16.2.4. Set on Sorted Tabular Sequence ═══ ISetOnSortedTabularSequence IGSetOnSortedTabularSequence The implementation of the class ISetOnSortedTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.16.2.5. Set on Sorted Diluted Sequence ═══ ISetOnSortedDilutedSequence IGSetOnSortedDilutedSequence The implementation of the class ISetOnSortedDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.16.2.6. Set on Hash Key Set ═══ ISetOnHashKeySet IGSetOnHashKeySet The implementation of the class ISetOnHashKeySet requires the following element functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Hash function ═══ 5.1.16.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASet, which is found in the iaset.h header file, or the corresponding reference class, IRSet, which is found in the irset.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.16.3.1. Template Arguments and Required Functions ═══ IASet IRSet The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.16.4. Coding Example for Set ═══ The follow program creates sets using the default class, ISet. The odd set contains all odd numbers less than ten. The prime set contains all prime numbers less than ten. The program creates a set, oddPrime, that contains all the prime numbers less than ten that are odd, by using the intersection of odd and prime. It creates another set, evenPrime, that contains all the prime numbers less than ten that are even, by using the difference of prime and oddPrime. When printing the sets, the program uses the iterator class, IIterator. It uses the add() function to build the odd and prime sets. It uses the addIntersection() and addDifference() functions to create the oddPrime and evenPrime sets, respectively. // evenodd.C - An example of using a Set #include #include // Take the defaults for the Set and for // the required functions for integer typedef ISet IntSet; // For iteration we want to use an object of an iterator class class PrintClass : public IIterator { public: virtual IBoolean applyTo(int& i) { cout << " " << i << " "; return True;} }; // Local prototype for the function to display an IntSet. void List(char *, IntSet &); // Main program int main () { IntSet odd, prime; IntSet oddPrime, evenPrime; int One = 1, Two = 2, Three = 3, Five = 5, Seven = 7, Nine = 9; // Fill odd set with odd integers < 10 odd.add( One ); odd.add( Three ); odd.add( Five ); odd.add( Seven ); odd.add( Nine ); List("Odds less than 10: ", odd); // Fill prime set with primes < 10 prime.add( Two ); prime.add( Three ); prime.add( Five ); prime.add( Seven ); List("Primes less than 10: ", prime); // Intersect 'Odd' and 'Prime' to give 'OddPrime' oddPrime.addIntersection( odd, prime); List("Odd primes less than 10: ", oddPrime); // Subtract all 'Odd' from 'Prime' to give 'EvenPrime' evenPrime.addDifference( prime, oddPrime); List("Even primes less than 10: ", evenPrime); return(0); } // Local function to display an IntSet. void List(char *Message, IntSet &anIntSet) { PrintClass Print; cout << Message; anIntSet.allElementsDo(Print); cout << endl; } The program produces the following output: Odds less than 10: 1 3 5 7 9 Primes less than 10: 2 3 5 7 Odd primes less than 10: 3 5 7 Even primes less than 10: 2 ═══ 5.1.17. Sorted Bag ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.17.1. Class Description - Sorted Bag ═══ A sorted bag is an ordered collection of zero or more elements with no key. Both element equality and multiple elements are supported. An example of using a sorted bag is a program for entering observations on the types of stones found in a riverbed. Each time you find a stone on the riverbed, you enter the stone's mineral type into the collection. You can enter the same mineral type for several stones, because a sorted bag supports multiple elements. You can search for stones of a particular mineral type, and you can determine the number of observations of stones of that type. You can also display the contents of the collection, sorted by mineral type, if you want a complete list of observations made to date. Figure Combination of Flat Collection Properties gives an overview of the properties of a sorted bag and its relationship to other flat collections. ═══ Derivation ═══ Collection Ordered Collection Equality Collection Sorted Collection Equality Sorted Collection Sorted Bag ═══ Variants and Header Files ═══ ISortedBag, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivsrtbag.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISortedBag isrtbag.h AVL tree IGSortedBag isrtbag.h AVL tree ISortedBagOnBSTKeySortedSet isbbst.h B* tree IGSortedBagOnBSTKeySortedSet isbbst.h B* tree ISortedBagOn- isbsls.h Linked sequence SortedLinkedSequence IGSortedBagOn isbsls.h Linked sequence SortedLinkedSequence ISortedBagOn- isbsts.h Tabular sequence SortedTabularSequence IGSortedBagOn- isbsts.h Tabular sequence SortedTabularSequence ISortedBagOn- isbsds.h Diluted sequence SortedDilutedSequence IGSortedBagOn- isbsds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for sorted bag:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addUnion  allElementsDo  anyElement  compare  contains  containsAllFrom  differenceWith  elementAt  elementAtPosition  firstElement  intersectionWith  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  locate  locateNext  locateOrAdd  maxNumberOfElements  newCursor  numberOfDifferentElements  numberOfElements  numberOfOccurrences  position  remove  removeAll  removeAllOccurrences  removeAt  removeAtPosition  removeFirst  removeLast  replaceAt  setToFirst  setToLast  setToNext  setToNextDifferentElement  setToPosition  setToPrevious  unionWith Sorted Bag also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.17.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sorted bags:  Sorted bag  Sorted bag on B* key sorted set  Sorted bag on sorted linked sequence  Sorted bag on sorted tabular sequence  Sorted bag on sorted diluted sequence ═══ 5.1.17.2.1. Sorted Bag ═══ ISortedBag IGSortedBag The default implementation of the class ISortedBag requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.17.2.2. Sorted Bag on B* Key Sorted Set ═══ ISortedBagOnBSTKeySortedSet IGSortedBagOnBSTKeySortedSet The implementation of the class ISortedBagOnBSTKeySortedSet requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.17.2.3. Sorted Bag on Sorted Linked Sequence ═══ ISortedBagOnSortedLinkedSequence IGSortedBagOnSortedLinkedSequence The implementation of the class ISortedBagOnSortedLinkedSequence requires the following element functions: Element Type  Default constructor  Constructor  Assignment  Equality test  Ordering relation ═══ 5.1.17.2.4. Sorted Bag on Sorted Tabular Sequence ═══ ISortedBagOnSortedTabularSequence IGSortedBagOnSortedTabularSequence The implementation of the class ISortedBagOnSortedTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.17.2.5. Sorted Bag on Sorted Diluted Sequence ═══ ISortedBagOnSortedDilutedSequence IGSortedBagOnSortedDilutedSequence The implementation of the class ISortedBagOnSortedDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.17.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASortedBag, which is found in the iasrtbag.h header file, or the corresponding reference class, IRSortedBag, which is found in the irsrtbag.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.17.3.1. Template Arguments and Required Functions ═══ IASortedBag IRSortedBag The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.18. Sorted Map ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.18.1. Class Description - Sorted Map ═══ A sorted map is an ordered collection of zero or more elements that have a key. Element equality is supported and the values of the elements are relevant. Elements are sorted by the value of their keys. Only elements with unique keys are supported. A request to add an element whose key already exists in another element of the collection causes an exception to be thrown. A request to add a duplicate element is ignored. An example of using a sorted map is a program that matches the names of rivers and lakes to their coordinates on a topographical map. The river or lake name is the key. You cannot add a lake or river to the collection if it is already present in the collection. You can display a list of all lakes and rivers, sorted by their names, and you can locate a given lake or river by its key, to determine its coordinates. Figure Combination of Flat Collection Properties gives an overview of the properties of a sorted map and its relationship to other flat collections. ═══ Derivation ═══ Equality Key Collection Equality Sorted Collection Equality Key Sorted Collection Sorted Map The diagram does not show all bases of sorted map. See the figure "Abstract Class Hierarchy" in section Abstract Classes for an illustration. ═══ Variants and Header Files ═══ ISortedMap, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivsrtmap.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISortedMap isrtmap.h AVL tree IGSortedMap isrtmap.h AVL tree ISortedMapOnBSTKeySortedSet ismbst.h B* tree IGSortedMapOnBSTKeySortedSet ismbst.h B* tree ISortedMapOn- ismsls.h Linked sequence SortedLinkedSequence IGSortedMapOn- ismsls.h Linked sequence SortedLinkedSequence ISortedMapOn- ismsts.h Tabular sequence SortedTabularSequence IGSortedMapOn- ismsts.h Tabular sequence SortedTabularSequence ISortedMapOn- ismsds.h Diluted sequence SortedDilutedSequence IGSortedMapOn- ismsds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for sorted maps:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addOrReplaceElementWithKey  addUnion  allElementsDo  anyElement  compare  contains  containsAllFrom  containsAllKeysFrom  containsElementWithKey  differenceWith  elementAt  elementAtPosition  elementWithKey  firstElement  intersectionWith  isBounded  isEmpty  isFirst  isFull  isLast  key  lastElement  locate  locateElementWithKey  locateNext  locateNextElementWithKey  locateOrAdd  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfElements  position  remove  removeAll  removeAt  removeAtPosition  removeElementWithKey  removeFirst  removeLast  replaceAt  replaceElementWithKey  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  unionWith Sorted map also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.18.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sorted maps:  Sorted map  Sorted map on B* key sorted set  Sorted map on sorted linked sequence  Sorted map on sorted tabular sequence  Sorted map on sorted diluted sequence ═══ 5.1.18.2.1. Sorted Map ═══ ISortedMap IGSortedMap The implementation of the class ISortedMap requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.18.2.2. Sorted Map on B* Key Sorted Set ═══ ISortedMapOnBSTKeySortedSet IGSortedMapOnBSTKeySortedSet The implementation of the class ISortedMapOnBSTKeySortedSet requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.18.2.3. Sorted Map on Sorted Linked Sequence ═══ ISortedMapOnSortedLinkedSequence IGSortedMapOnSortedLinkedSequence The implementation of the class ISortedMapOnSortedLinkedSequence requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.18.2.4. Sorted Map on Sorted Tabular Sequence ═══ ISortedMapOnSortedTabularSequence IGSortedMapOnSortedTabularSequence The implementation of the class ISortedMapOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.18.2.5. Sorted Map on Sorted Diluted Sequence ═══ ISortedMapOnSortedDilutedSequence IGSortedMapOnSortedDilutedSequence The implementation of the class ISortedMapOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.18.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASortedMap, which is found in the iasrtmap.h header file, or the corresponding reference class, IRSortedMap, which is found in the irsrtmap.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.18.3.1. Template Arguments and Required Functions ═══ IASortedMap IRSortedMap The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.18.4. Coding Example for Sorted Map ═══ The following program uses a sorted map and a sorted relation to display sorted lists of the name and size of files contained on a disk. It uses the default classes, ISortedMap and ISortedRelation, to implement the collections. The program uses the sorted map to store the name of the file, because all elements in a sorted map are unique and all names on a disk are unique. It uses a sorted relation for the file size, because there may be identical file sizes, and identical values are permissible in sorted relations. The program uses the add() function to fill both collections. To print the collections, it uses the forCursor macro and the allElementsDo() function. The program produces a list of files sorted by name (in ascending order) and a list of the same files sorted by file size (in descending order). Because the output varies depending on the file system in use when it is run, no output is shown here. // dskusage.C - An example of using a Sorted Map and a Sorted Relation #include "dsur.h" // Our own common exit for all errors: void errorExit(int, char*, char* = ""); // Use the default Sorted Map as is: #include // Use the default Sorted Relation as is: #include int main (int argc, char* argv[]) { char* fspec = "dsu.dat"; // Default for input file if (argc > 1) fspec = argv[1]; ifstream inputfile(fspec); if (!inputfile) errorExit(20, "Unable to open input file", fspec); ISortedMap dsurByName; ISortedMap ::Cursor curByName(dsurByName); IGSortedRelation dsurBySpace; IGSortedRelation ::Cursor curBySpace(dsurBySpace); // Read all records into dsurByName while (inputfile.good()) { DiskSpaceUR dsur(inputfile); if (dsur.isValid()) { dsurByName.add(dsur); dsurBySpace.add(dsur); } } if (! inputfile.eof()) errorExit(39, "Error during read of", fspec); cout << "\n\nAll Disk Space Usage records " << "sorted (ascending) by name:\n" << endl; forCursor(curByName) cout << " " << dsurByName.elementAt(curByName) << endl; cout << "\n\nAll Disk Space Usage records " << "sorted (descending) by space:\n" << endl; forCursor(curBySpace) cout << " " << dsurBySpace.elementAt(curBySpace) << endl; return 0; } #include // for exit() definition void errorExit (int rc, char* s1, char* s2) { cerr << s1 << " " << s2 << endl; exit(rc); } ═══ 5.1.19. Sorted Relation ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.19.1. Class Description - Sorted Relation ═══ A sorted relation is an ordered collection of zero or more elements that have a key. The elements are sorted by the value of their key. Element equality is supported, and the values of the elements are relevant. The keys of the elements are not unique. You can add an element whether or not there is already an element in the collection with the same key. An example of using a sorted relation is a program used by telephone operators to provide directory assistance. The computerized directory is a sorted relation whose key is the name of the individual or business associated with a telephone number. When a caller requests the number of a given person or company, the operator enters the name of that person or company to access the phone number. The collection can have multiple identical keys, because two individuals or companies might have the same name. The collection is sorted alphabetically, because once a year it is used as the source material for a printed telephone directory. Figure Combination of Flat Collection Properties gives an overview of the properties of a sorted relation and its relationship to other flat collections. ═══ Derivation ═══ Equality Key Collection Equality Collection Equality Key Sorted Collection Sorted Relation The diagram does not show all bases of sorted relation. See the figure "Abstract Class Hierarchy" in section Abstract Classes for an illustration. ═══ Variants and Header Files ═══ ISortedRelation, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. Note: In the table, some class names have been hyphenated to fit in their column. In your code you should not include these hyphens in the class names. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivsrtrel.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISortedRelation isrtrel.h Linked sequence IGSortedRelation isrtrel.h Linked sequence ISortedRelationOn- isrsts.h Tabular sequence SortedTabularSequence IGSortedRelationOn- isrsts.h Tabular sequence SortedTabularSequence ISortedRelationOn- isrsds.h Diluted sequence SortedDilutedSequence IGSortedRelationOn- isrsds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for sorted relation:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addOrReplaceElementWithKey  addUnion  allElementsDo  anyElement  compare  contains  containsAllFrom  containsAllKeysFrom  containsElementWithKey  differenceWith  elementAt  elementAtPosition  elementWithKey  firstElement  intersectionWith  isBounded  isEmpty  isFirst  isFull  isLast  key  lastElement  locate  locateElementWithKey  locateNext  locateNextElementWithKey  locateOrAdd  locateOrAddElementWithKey  maxNumberOfElements  newCursor  numberOfDifferentKeys  numberOfElements  numberOfElementsWithKey  position  remove  removeAll  removeAllElementsWithKey  removeAt  removeAtPosition  removeElementWithKey  removeFirst  removeLast  replaceAt  replaceElementWithKey  setToFirst  setToLast  setToNext  setToNextWithDifferentKey  setToPosition  setToPrevious  unionWith Sorted relation also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.19.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sorted relations:  Sorted relation  Sorted relation on sorted tabular sequence  Sorted relation on sorted diluted sequence ═══ 5.1.19.2.1. Sorted Relation ═══ ISortedRelation IGSortedRelation The default implementation of the class ISortedRelation requires the following element and key-type functions: Element Type  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.19.2.2. Sorted Relation on Sorted Tabular Sequence ═══ ISortedRelationOnSortedTabularSequence IGSortedRelationOnSortedTabularSequence The implementation of the class ISortedRelationOnSortedTabularSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.19.2.3. Sorted Relation on Sorted Diluted Sequence ═══ ISortedRelationOnSortedDilutedSequence IGSortedRelationOnSortedDilutedSequence The implementation of the class ISortedRelationOnSortedDilutedSequence requires the following element and key-type functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Key access  Equality test Key Type Ordering relation ═══ 5.1.19.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASortedRelation, which is found in the iasrtrel.h header file, or the corresponding reference class, IRSortedRelation, which is found in the irsrtrel.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.19.3.1. Template Arguments and Required Functions ═══ IASortedRelation IRSortedRelation The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.19.4. Coding Example for Sorted Relation ═══ See Coding Example for Sorted Map for an example of a sorted relation. ═══ 5.1.20. Sorted Set ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.20.1. Class Description - Sorted Set ═══ A sorted set is an ordered collection of zero or more elements with element equality but no key. Only unique elements are supported. A request to add an element that already exists is ignored. The value of the elements is relevant. The elements of a sorted set are ordered such that the value of each element is less than or equal to the value of its successor. The element with the smallest value currently in a sorted set is called the first element. The element with the largest value is called the last element. When an element is added, it is placed in the sorted set according to the defined ordering relation. An example of using a sorted set is a program that tests numbers to see if they are prime. Two complementary sorted sets are used, one for prime numbers, and one for nonprime numbers. When you enter a number, the program first looks in the set of nonprime numbers. If the value is found there, the number is nonprime. If the value is not found there, the program looks in the set of prime numbers. If the value is found there, the number is prime. Otherwise the program determines whether the number is prime or nonprime, and places it in the appropriate sorted set. The program can also display a list of prime or nonprime numbers, beginning at the first prime or nonprime following a given value, because the numbers in a sorted set are sorted from smallest to largest. Figure Combination of Flat Collection Properties gives an overview of the properties of a sorted set and its relationship to other flat collections. ═══ Derivation ═══ Collection Ordered Collection Sorted Collection Equality Collection Equality Sorted Collection Sorted Set ═══ Variants and Header Files ═══ ISortedSet, the first class in the table below, is the default implementation variant. If you want to use polymorphism, you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivsrtset.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant ISortedSet isrtset.h AVL tree IGSortedSet isrtset.h AVL tree ISortedSetOn- issbst.h B* tree BSTKeySortedSet IGSortedSetOn- issbst.h B* tree BSTKeySortedSet ISortedSetOn- isssls.h Linked sequence SortedLinkedSequence IGSortedSetOn- isssls.h Linked sequence SortedLinkedSequence ISortedSetOn- isssts.h Tabular sequence SortedTabularSequence IGSortedSetOn- isssts.h Tabular sequence SortedTabularSequence ISortedSetOn- isssds.h Diluted sequence SortedDilutedSequence IGSortedSetOn- isssds.h Diluted sequence SortedDilutedSequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for sorted sets:  Constructor  Copy Constructor  Destructor  operator!=  operator=  operator==  add  addAllFrom  addDifference  addIntersection  addUnion  allElementsDo  anyElement  compare  contains  containsAllFrom  differenceWith  elementAt  elementAtPosition  firstElement  intersectionWith  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  locate  locateNext  locateOrAdd  maxNumberOfElements  newCursor  position  remove  removeAll  removeAt  removeAtPosition  removeFirst  removeLast  replaceAt  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  unionWith Sorted Set also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.20.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for sorted sets:  Sorted set  Sorted set on B* key sorted set  Sorted set on sorted linked sequence  Sorted set on sorted tabular sequence  Sorted set on sorted diluted sequence ═══ 5.1.20.2.1. Sorted Set ═══ ISortedSet IGSortedSet The default implementation of the class ISortedSet requires the following element functions: Element Type  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.20.2.2. Sorted Set on B* Key Sorted Set ═══ ISortedSetOnBSTKeySortedSet IGSortedSetOnBSTKeySortedSet The default implementation of the class ISortedSetOnBSTKeySortedSet requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.20.2.3. Sorted Set on Sorted Linked Sequence ═══ ISortedSetOnSortedLinkedSequence IGSortedSetOnSortedLinkedSequence The implementation of the class ISortedSetOnSortedLinkedSequence requires the following element functions: Element Type  Copy constructor  Assignment  Destructor  Equality test  Ordering relation ═══ 5.1.20.2.4. Sorted Set on Sorted Tabular Sequence ═══ ISortedSetOnSortedTabularSequence IGSortedSetOnSortedTabularSequence The implementation of the class ISortedSetOnSortedTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.20.2.5. Sorted Set on Sorted Diluted Sequence ═══ ISortedSetOnSortedDilutedSequence IGSortedSetOnSortedDilutedSequence The implementation of the class ISortedSetOnSortedDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment  Equality test  Ordering relation ═══ 5.1.20.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IASortedSet, which is found in the iasrtset.h header file, or the corresponding reference class, IRSortedSet, which is found in the irsrtset.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.20.3.1. Template Arguments and Required Functions ═══ IASortedSet IRSortedSet The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.20.4. Coding Example for Sorted Set ═══ The following program uses the default class, ISortedSet, to create sorted lists of planets with different properties. The program stores all planets in our solar system, all heavy planets in our solar system, all bright planets in our solar system, and all heavy or bright planets in our solar system in a number of sorted sets. Each set sorts the planets by its distance from the sun. The program uses the forCursor macro to create the heavyPlanets and the brightPlanets collections. It uses the allElementsDo() function to display the planets in each collection and the unionWith() function when creating the bright-or-heavy planets category. // planets.C - An example of using a Sorted Set #include // Let's use the Sorted Set Default Variant: #include // Get Class Planet: #include "planet.h" int main() { ISortedSet allPlanets, heavyPlanets, brightPlanets; // A cursor to cursor through allPlanets: ISortedSet::Cursor aPCursor(allPlanets); SayPlanetName showPlanet; allPlanets.add( Planet("Earth", 149.60f, 1.0000f, 99.9f)); allPlanets.add( Planet("Jupiter", 778.3f, 317.818f, -2.4f)); allPlanets.add( Planet("Mars", 227.9f, 0.1078f, -1.9f)); allPlanets.add( Planet("Mercury", 57.91f, 0.0558f, -0.2f)); allPlanets.add( Planet("Neptun", 4498.f, 17.216f, +7.6f)); allPlanets.add( Planet("Pluto", 5910.f, 0.18f, +14.7f)); allPlanets.add( Planet("Saturn", 1428.f, 95.112f, +0.8f)); allPlanets.add( Planet("Uranus", 2872.f, 14.517f, +5.8f)); allPlanets.add( Planet("Venus", 108.21f, 0.8148f, -4.1f)); forCursor(aPCursor) { if (allPlanets.elementAt(aPCursor).isHeavy()) heavyPlanets.add(allPlanets.elementAt(aPCursor)); if (allPlanets.elementAt(aPCursor).isBright()) brightPlanets.add(allPlanets.elementAt(aPCursor)); } cout << endl << endl << "All Planets: " << endl; allPlanets.allElementsDo(showPlanet); cout << endl << endl << "Heavy Planets: " << endl; heavyPlanets.allElementsDo(showPlanet); cout << endl << endl << "Bright Planets: " << endl; brightPlanets.allElementsDo(showPlanet); cout << endl << endl << "Bright-or-Heavy Planets: " << endl; brightPlanets.unionWith(heavyPlanets); brightPlanets.allElementsDo(showPlanet); cout << endl << endl << "Did you notice that all these Sets are sorted" << " in the same order" << endl << " (distance of planet from sun) ? " << endl; return 0; } The program produces the following output: All Planets: Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto Heavy Planets: Jupiter Saturn Uranus Neptune Bright Planets: Mercury Venus Mars Jupiter Bright-or-Heavy Planets: Mercury Venus Mars Jupiter Saturn Uranus Neptune Did you notice that all these Sets are sorted in the same order (distance of planet from sun) ? ═══ 5.1.21. Stack ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Abstract/Reference Classes Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.1.21.1. Class Description - Stack ═══ A stack is a sequence with restricted access. It is an ordered collection of elements with no key and no element equality. The elements are arranged so that each collection has a first and a last element, each element except the last has a next element, and each element but the first has a previous element. The type and value of the elements are irrelevant and have no effect on the behavior of the stack. Elements are added to and deleted from the top of the stack. Consequently, the elements of a stack are in reverse chronological order. A stack is characterized by a last-in, first-out (LIFO) behavior. An example of using a stack is a program that keeps track of daily tasks that you have begun to work on but that have been interrupted. When you are working on a task and something else comes up that is more urgent, you enter a description of the interrupted task and where you stopped it into your program, and the task is pushed onto the stack. Whenever you complete a task, you ask the program for the most recently saved task that was interrupted. This task is popped off the stack, and you resume your work where you left off. When you attempt to pop an item off the stack and no item is available, you have completed all your tasks and you can go home. ═══ Derivation ═══ Collection Ordered Collection Sequential Collection Sequence Stack Note that stack is based on sequence but is not actually derived from it or from the other classes shown above. See Restricted Access for further details. ═══ Variants and Header Files ═══ IStack, the first class in the table below, is the default implementation variant. If you want to use polymorphism you can replace the following class implementation variants by the reference class. To use Visual Builder features with your collections, change the name of the desired collection class template in the list below from I... to IV..., and use the ivstack.h header file instead of the header file that you would normally use without Visual Builder. Class Name Header File Implementation Variant IStack istack.h Linked sequence IGStack istack.h Linked sequence IStackOnTabularSequence istkts.h Tabular sequence IGStackOnTabularSequence istkts.h Tabular sequence IStackOnDilutedSequence istkds.h Diluted sequence IGStackOnDilutedSequence istkds.h Diluted sequence ═══ Members ═══ All members of flat collections are described in Introduction to Flat Collections. The following members are provided for stack:  Constructor  Copy Constructor  Destructor  operator=  add  addAllFrom  addAsLast  allElementsDo  anyElement  compare  elementAt  elementAtPosition  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  maxNumberOfElements  newCursor  numberOfElements  pop  position  push  removeAll  removeLast  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  top Stack also defines a cursor that inherits from IOrderedCursor. The members for IOrderedCursor are described in Cursor. ═══ 5.1.21.2. Template Arguments and Required Functions ═══ The following implementation variants are defined for stacks:  Stack  Stack on tabular sequence  Stack on diluted sequence ═══ 5.1.21.2.1. Stack ═══ IStack IGStack The default implementation of the class IStack requires the following element functions: Element Type  Copy constructor  Destructor  Assignment ═══ 5.1.21.2.2. Stack on Tabular Sequence ═══ IStackOnTabularSequence IGStackOnTabularSequence The implementation of the class IStackOnTabularSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment ═══ 5.1.21.2.3. Stack on Diluted Sequence ═══ IStackOnDilutedSequence IGStackOnDilutedSequence The implementation of the class IStackOnDilutedSequence requires the following element functions: Element Type  Default constructor  Copy constructor  Destructor  Assignment ═══ 5.1.21.3. Abstract Class and Reference Class ═══ For polymorphism, you can use the corresponding abstract class, IAStack, which is found in the iastack.h header file, or the corresponding reference class, IRStack, which is found in the irstack.h header file. See Polymorphic Use of Collections for further information. ═══ 5.1.21.3.1. Template Arguments and Required Functions ═══ IRStack IAStack The concrete base class is one of the classes defined above. The required functions are the same as the required functions of the concrete base class. ═══ 5.1.21.4. Coding Example for Stack ═══ The following program creates two stacks (Stack1 and Stack2) using the default class, IStack. It adds a number of words to Stack1, removes them from Stack1, adds them to Stack2, and finally removes them from Stack2 so that they can be printed. The push() and pop() functions are used for adding and removing elements, respectively. Between these stack operations the stacks are printed. To prevent the stack from changing during printing, the program uses the constant version of the iterator class, IConstantIterator with the allElementsDo() function. The words print in the same order as they were originally added to Stack1. Because of the nature of the stack class, the program must use the constant iterator class, IConstantIterator, when printing the stacks. It uses the push() and pop() functions for adding and removing elements, respectively. The allElementsDo() function is used when the collection is printed. // pushpop.C - An example of using a Stack #include #include // Let's use the default stack: IStack #include typedef IStack SimpleStack; // The stack requires iteration to be const. typedef IConstantIterator StackIterator; // Test variables to put into our Stack: char *String[9] = { "The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog." }; // A class to display the contents of our Stack: class PrintClass : public StackIterator { public: IBoolean applyTo(char* const& w) { cout << w << endl; return(True); } }; // Main program int main() { SimpleStack Stack1, Stack2; char *S; PrintClass Print; // We specify two stacks. // First all the strings are pushed onto the first stack. // Next, they are popped from the first and pushed onto // the second. // Finally they are popped from the second and printed. // During this final print the strings must appear // in their original order. int i; for (i = 0; i < 9; i ++) { Stack1.push(String[i]); } cout << "Contents of Stack1:" << endl; Stack1.allElementsDo(Print); cout << "----------------------------" << endl; while (!Stack1.isEmpty()) { Stack1.pop(S); // Pop from stack 1 Stack2.push(S); // Add it on top of stack 2 } cout << "Contents of Stack2:" << endl; Stack2.allElementsDo(Print); cout << "----------------------------" << endl; while (!Stack2.isEmpty()) { Stack2.pop(S); cout << "Popped from Stack 2: " << S << endl; } return(0); } This program produces the following output: Contents of Stack1: The quick brown fox jumps over a lazy dog. ---------------------------- Contents of Stack2: dog. lazy a over jumps fox brown quick The ---------------------------- Popped from Stack 2: The Popped from Stack 2: quick Popped from Stack 2: brown Popped from Stack 2: fox Popped from Stack 2: jumps Popped from Stack 2: over Popped from Stack 2: a Popped from Stack 2: lazy Popped from Stack 2: dog. ═══ 5.2. Tree Collection Classes ═══ This section contains the following chapters: Introduction to Trees Introduces the concept of trees. N-ary Tree Describes n-ary tree, the tree collection of the Collection Class Library. Defines the class implementation variants, template arguments, and required functions for n-ary tree. Declarations for n-ary tree are provided, terms are defined, and the public member functions of n-ary tree are described. ═══ 5.2.1. Introduction to Trees ═══ A tree is a collection of nodes that can have an arbitrary number of references to other nodes. There can be no cycles or short-circuit references. A unique path connects every two nodes. One node is designated as the root of the tree. Formally, a tree can be defined recursively in the following manner: 1. A single node by itself is a tree. This node is also the root of the tree. 2. If N is a node and T-1, T-2, ..., T-k are trees with roots R-1, R-2, ..., R-k, respectively, then a new tree can be constructed by making N the parent of the nodes R-1, R-2, ..., R-k. In this new tree, N is the root and T-1, T-2, ..., T-k are the subtrees of the root N. Nodes R-1, R-2, ..., R-k are called children of node N. Associated with each node is a data item called element. Nodes without children are called leaves or terminals. The number of children in a node is called the degree of that node. The level of a given node is the number of steps in the path from the root to the given node. The root is at level 0 by definition. The height of a tree is the length of the longest path from the root to any node. ═══ 5.2.1.1. Defining the Traversal Order of Tree Elements ═══ You can define the order in which nodes of a tree are traversed by specifying a parameter of type ITreeIterationOrder in calls to the following member functions:  setToFirst  setToLast  setToNext  setToPrevious  allElementsDo, allSubtreeElementsDo These functions are described in N-ary Tree. The ITreeIterationOrder parameter can have one of two values: IPreorder or IPostorder. The effect of each of these values is explained below. IPreorder The search begins at the root of the tree, and continues with the leftmost child of the root. If the child is the root of a subtree, the search continues with the leftmost child of the subtree, and so on, until a terminal node is detected. The search continues with all siblings of the terminal node, from left to right. If any of these siblings is the root of a subtree, the subtree is searched the same way as described above for the tree. The preorder method can be summarized by the following recursive rules: 1. Visit the root. 2. Traverse the subtrees from left to right in preorder. IPostorder The IPostorder method is the opposite of IPreorder. The search begins with the leftmost terminal node in the tree. Then that node's siblings are searched from left to right. If any of these siblings is the root of a subtree, the subtree is searched for its leftmost terminal node. The postorder method can be sumarized by the following recursive rules: 1. Traverse the subtrees from left to right in postorder. 2. Visit the root. The following figure shows a tree with 12 nodes, and the order of traversal for both preorder and postorder methods. Numbers indicate the preorder method (node 1 is searched before node 2) while letters indicate the postorder method (node A is searched before node B). Preorder and Postorder Iteration Methods for Trees ═══ 5.2.2. N-ary Tree ═══ Description Derivation Variants/Header Files Members Template Arguments and Required Functions Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.2.2.1. Class Description - ITree ═══ An n-ary tree is a special tree where each node can have up to n children. n must be greater than one. If n is one, the tree is a list. If n is zero, the structure loses its meaning. An example of using an n-ary tree is a program used to build a family tree. (For simplicity, assume that the family tree is not concerned with information about spouses.) Whenever you discover a relative who is not already in your family tree, you enter the relative's name. If you know the parent's name, and the parent is already in the collection, the new relative is added as a child of the existing parent. If the parent is known but is not in the collection, a new collection is created, with the parent as the root element and the child as a child node of the parent. If you do not know the parent, the relative is entered as the root element of a new collection. You can also enter information about the children of a given relative; this information is used to attach a subtree, whose root node is the child, to the node of the parent of that child. Once you have established the collection, you can determine who is the parent or oldest known ancestor of a given relative, and you can display a list of all descendents of a given family member. ═══ Derivation ═══ There are no bases or derived classes for N-ary Tree. ═══ Variants and Header Files ═══ ITree is the default implementation variant based on tabular tree. IGTree is the default implementation variant with generic operations class. Both classes are declared in itree.h. No reference class exists for tree classes. ═══ Members ═══ Tree Functions lists the member functions for N-ary Tree. ═══ 5.2.2.2. Template Arguments and Required Functions ═══ ITree IGTree The default implementation of ITree requires the following element functions: Element Type  Copy constructor  Destructor  Assignment The argument value of numberOfChildren() specifies the maximum number of children for each node. ═══ 5.2.2.3. Terms Used ═══ Some of the terms used in this chapter are defined below. You can also use the Glossary to look up terms you are unfamiliar with. this tree The tree to which a function is applied, in contrast to the given tree. given ... Referring to a tree, element, or function that is given as a function argument. returned element An element returned as a function return value. iteration order The order in which elements are visited in functions allElementsDo(), allSubtreeElementsDo(), setToNext(), and setToPrevious(). ═══ 5.2.2.4. Coding Example for N-ary Tree ═══ The following sample constructs a binary tree for the following expression: (8+2) * (2+4) / (7-5). The program prints this tree in preorder, using prefix notation. It then calculates the result of the expression. The program identifies subtrees consisting of an operand and two operators, calculates the result and replaces the subtree by its result. Finally, the tree consists of one node that is the result of the expression. Note that the code does not respect precedence of "/" and "*" over "+" and "-". // nary.C - An example of using an n-ary tree #include #include #include //////////////////////////////////////////////////////////// // The tree for this expression is as follows: // // // // / // // * - // // + + 7 5 // // 8 2 2 4 // //////////////////////////////////////////////////////////// typedef ITree BinaryTree; IBoolean printNode(IString const& node, void* dummy) { // Prints one node of an n-ary tree cout << node << "|"; return True; } void prefixedNotation(BinaryTree const& naryTree) { // Prints an n-ary tree in prefixed notation naryTree.allElementsDo(printNode , IPreorder); cout << endl; } void identifyChildren (IString &child1, IString &child2, BinaryTree &binTree, ITreeCursor &binTreeCursor) { // Identifies the children of a node binTree.setToNext(binTreeCursor, IPreorder); child1 = binTree.elementAt(binTreeCursor); binTree.setToNextExistingChild(binTreeCursor); child2 = binTree.elementAt(binTreeCursor); binTree.setToParent(binTreeCursor); } IBoolean isNumber(IString child) { // Checks whether a node contains a number if ((child != '+') && (child != '-') && (child != '*') && (child != '/')) { return True; } else { return False; } } void lookForNextOperator(BinaryTree &binTree, ITreeCursor &binTreeCursor) { // Looks for the next operator in the tree IBoolean operatorFound = False; do { if (!isNumber(binTree.elementAt(binTreeCursor))) { operatorFound = True; } else { binTree.setToNext(binTreeCursor, IPreorder); } } while (! operatorFound); } void calculateSubtree(double &result, double &operand1, double &operand2, IString &operatorSign) { // Calculates the result from a subtree in the complete tree switch (*(char*)operatorSign) { case '+': result = operand1+operand2; break; case '-': result = operand1-operand2; break; case '/': result = operand1/operand2; break; case '*': result = operand1*operand2; break; } // end of switch } /************************ main ****************************/ int main () { // Construct the tree: BinaryTree binTree; BinaryTree::Cursor binTreeCursor(binTree); BinaryTree::Cursor binTreeSaveCursor(binTree); binTree.addAsRoot("/"); binTree.setToRoot(binTreeCursor); binTree.addAsChild(binTreeCursor, 1, "*"); binTree.setToChild(1, binTreeCursor); binTree.addAsChild(binTreeCursor, 1, "+"); binTree.setToChild(1, binTreeCursor); binTree.addAsChild(binTreeCursor, 1, "8"); binTree.addAsChild(binTreeCursor, 2, "2"); binTree.setToParent(binTreeCursor); binTree.addAsChild(binTreeCursor, 2, "+"); binTree.setToChild(2, binTreeCursor); binTree.addAsChild(binTreeCursor, 1, "2"); binTree.addAsChild(binTreeCursor, 2, "4"); binTree.setToRoot(binTreeCursor); binTree.addAsChild(binTreeCursor, 2, "-"); binTree.setToChild(2, binTreeCursor); binTree.addAsChild(binTreeCursor, 1, "7"); binTree.addAsChild(binTreeCursor, 2, "5"); // Print complete tree in prefix notation cout << "Printing the original tree in prefixed notation:" << endl; prefixedNotation(binTree); cout << " " << endl; // Calculate tree double operand1 = 0; double operand2 = 0; double result = 0; INumber replacePosition; IString operatorSign, child1, child2; binTree.setToRoot(binTreeCursor); do { lookForNextOperator(binTree, binTreeCursor); operatorSign = binTree.elementAt(binTreeCursor); identifyChildren (child1, child2, binTree, binTreeCursor); if ((isNumber(child1)) && (isNumber(child2))) { operand1 = child1.asDouble(); operand2 = child2.asDouble(); calculateSubtree(result, operand1, operand2, operatorSign); if (binTree.numberOfElements() > 3) { // If tree contains more than three elements, replace // the calculated subtree by its result as follows. // (Save the cursor, because it will become invalidated after // removeSubtree) binTreeSaveCursor = binTreeCursor; binTree.setToParent(binTreeSaveCursor); replacePosition = binTree.position(binTreeCursor); binTree.removeSubtree(binTreeCursor); binTree.addAsChild(binTreeSaveCursor, replacePosition, (IString)result); cout << "Tree with calculated subtree replaced: " << endl; prefixedNotation(binTree); binTree.setToRoot(binTreeCursor); } else { // If tree contains root with two children only, replace // this calculated subtree by its result as follows: binTree.removeAll(); binTree.addAsRoot(IString(result)); cout << "Now the tree contains the result only:" << endl; prefixedNotation(binTree); } } else { binTree.setToNext(binTreeCursor, IPreorder); } } while (binTree.numberOfElements() > 1); return 0; } The program produces the following output: Printing the original tree in prefixed notation: /|*|+|8|2|+|2|4|-|7|5| Tree with calculated subtree replaced: /|*|10|+|2|4|-|7|5| Tree with calculated subtree replaced: /|*|10|6|-|7|5| Tree with calculated subtree replaced: /|60|-|7|5| Tree with calculated subtree replaced: /|60|2| Now the tree contains the result only: 30| ═══ 5.2.2.5. Tree Functions ═══ This section lists the public member functions of n-ary trees. The following member functions are described: Constructor Copy Constructor Destructor operator= addAsChild addAsRoot allElementsDo (Using a function) allElementsDo (Using an iterator) allSubtreeElementsDo (Using a function) allSubtreeElementsDo (Using an iterator) attachAsChild attachSubtreeAsChild attachAsRoot attachSubtreeAsRoot copy copySubtree elementAt hasChild isEmpty isLeaf isRoot newCursor numberOfChildren numberOfElements numberOfSubtreeElements numberOfLeaves numberOfSubtreeLeaves position removeAll removeSubtree replaceAt setToChild setToFirst setToFirstExistingChild setToLast setToLastExistingChild setToNext setToNextExistingChild setToParent setToPrevious setToPreviousExistingChild setToRoot ═══ 5.2.2.5.1. Constructor ═══ ITree ( ) ; Constructs a tree. The tree is initially empty; that is, it does not contain any nodes. ═══ 5.2.2.5.2. Copy Constructor ═══ ITree ( ITree const& tree ) ; Constructs a tree by copying all elements from the given tree. Exception IOutOfMemory ═══ 5.2.2.5.3. Destructor ═══ ~ITree ( ) ; Removes all elements from this tree. Side Effects All cursors of the tree become undefined. ═══ 5.2.2.5.4. operator= ═══ ITree & operator= ( ITree const& tree ) ; Copies all elements of the given tree to this tree. Return Value A reference to this tree. Side Effects All cursors of this tree become undefined. Exception IOutOfMemory ═══ 5.2.2.5.5. addAsChild ═══ void addAsChild ( ITreeCursor const& cursor, IPosition position, Element const& element ) ; Adds the given element as a child with the given position to the node of this tree denoted by the given cursor. Preconditions  The cursor must point to an element of this tree.  (1 <= position <= numberOfChildren()).  The node denoted by the given cursor (of this tree) must not have a child at the given position. Exceptions  IOutOfMemory  ICursorInvalidException  IPositionInvalidException  IChildAlreadyExistsException ═══ 5.2.2.5.6. addAsRoot ═══ void addAsRoot ( Element const& element ) ; Adds the given element as root of the tree. Precondition The tree must not have a root; that is, it must be empty. Exceptions  IOutOfMemory  IRootAlreadyExistsException ═══ 5.2.2.5.7. allElementsDo, allSubtreeElementsDo ═══ IBoolean allElementsDo ( IBoolean (*function) (Element&, void*), ITreeIterationOrder iterationOrder, void* additionalArgument = 0 ) ; IBoolean allElementsDo ( IBoolean (*function) (Element const&, void*), ITreeIterationOrder iterationOrder, void* additionalArgument = 0 ) const; IBoolean allSubtreeElementsDo ( ITreeCursor const& cursor, IBoolean (*function) (Element const&, void*), ITreeIterationOrder iterationOrder, void* additionalArgument = 0 ) const; IBoolean allSubtreeElementsDo ( ITreeCursor const& cursor, IBoolean (*function) (Element&, void*), ITreeIterationOrder iterationOrder, void* additionalArgument = 0 ) ; Calls the given function for all elements of the subtree denoted by the given cursor (of this tree) until the given function returns False. The elements are visited in the given iteration order. Additional arguments can be passed to the given function using additionalArgument. The additional argument defaults to zero if no additional argument is given. The allElementsDo() function (without a subtree cursor argument) iterates over all elements of the tree. Note: The given function must not remove elements from or add elements to the tree. Return Value Returns True if the given function returns True for every element it is applied to. Preconditions  The cursor must belong to this tree.  The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.8. allElementsDo, allSubtreeElementsDo ═══ IBoolean allElementsDo ( IIterator & iterator, ITreeIterationOrder iterationOrder ) ; IBoolean allElementsDo ( IConstantIterator & iterator, ITreeIterationOrder iterationOrder ) const; IBoolean allSubtreeElementsDo ( ITreeCursor const& cursor, IIterator & iterator, ITreeIterationOrder iterationOrder ) ; IBoolean allSubtreeElementsDo ( ITreeCursor const& cursor, IConstantIterator & iterator, ITreeIterationOrder iterationOrder ) const; Calls the applyTo() function of the given iterator for all elements of the subtree denoted by the given cursor (of this tree) until the applyTo() function returns False. The elements are visited in the given iteration order. The allElementsDo() function (without a subtree cursor argument) iterates over all elements of the tree. Note: The applyTo() function must not remove elements from or add elements to the tree. Preconditions  The cursor must belong to this tree.  The cursor must point to an element of this tree. Return Value Returns True if the applyTo() function returns True for every element it is applied to. Exceptions ICursorInvalidException ═══ 5.2.2.5.9. attachAsChild, attachSubtreeAsChild ═══ void attachAsChild ( ITreeCursor const& cursor, IPosition position, ITree & tree ) ; void attachSubtreeAsChild ( ITreeCursor const& cursor, IPosition position, ITree & tree, ITreeCursor const& subTreeCursor ) ; Copies the subtree denoted by the given subtree cursor as a child with the given position of the node (of this tree) denoted by the given cursor. Removes this subtree from the given tree. The attachAsChild() function (without a subtree cursor argument) copies and removes the whole given tree. Be careful when this tree and the given tree are the same. In such cases you must not attach a subtree to one of its own children, because a cyclic tree structure would result. Because attachSubtreeAsChild() removes this subtree from this tree, you will never be able to access either this subtree or the given subtree attached to it. This practice can also lead to memory not being properly freed. This warning applies to both attachAsChild() and attachSubtreeAsChild(). Note: These functions are implemented by copying a pointer to the subtree, rather than by copying all elements in the subtree. Preconditions  The cursor must point to an element of this tree.  The subtree cursor must point to an element of the given tree.  (1 <= position <= numberOfChildren()).  The node denoted by the given cursor (of this tree) must not have a child at the given position.  If this tree and the given tree are the same, a subtree must not be attached to one of its own children. Exceptions  ICursorInvalidException  IPositionInvalidException  IChildAlreadyExistsException  ICyclicAttachException ═══ 5.2.2.5.10. attachAsRoot, attachSubtreeAsRoot ═══ void attachAsRoot ( ITree & tree ) ; void attachSubtreeAsRoot ( ITree & tree, ITreeCursor const& cursor ) ; Copies the subtree denoted by the cursor of the given tree to (the root of) this tree, and removes this subtree from the given tree. The attachAsRoot() function (without a cursor argument) copies and removes the whole given tree. Note: These functions are implemented by copying a pointer to the subtree, rather than by copying all elements in the subtree. Preconditions  The cursor must point to an element of this tree.  The tree must not have a root; that is, it must be empty. Exceptions  ICursorInvalidException  IRootAlreadyExistsException ═══ 5.2.2.5.11. copy, copySubtree ═══ void copy ( (ITree const& tree ) ; void copySubtree ( ITree const& tree, ITreeCursor const& cursor ) ; Removes all elements from this tree, and copies the subtree denoted by the given cursor of the given tree to (the root of) this tree. The copy function (without a cursor argument) copies the whole given tree. Preconditions The cursor must point to an element of the given tree. Exceptions  IOutOfMemory  ICursorInvalidException ═══ 5.2.2.5.12. elementAt ═══ Element const& elementAt ( ITreeCursor const& cursor ) const; Element& elementAt ( ITreeCursor const& cursor ) ; Returns a reference to the element pointed to by the given cursor. Precondition The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.13. hasChild ═══ IBoolean hasChild ( IPosition position, ITreeCursor const& cursor ) const; Returns True if the node pointed to by the given cursor has a child at the given position. Preconditions  The cursor must point to an element of this tree.  (1 <= position <= numberOfChildren()) Exceptions  ICursorInvalidException  IPositionInvalidException ═══ 5.2.2.5.14. isEmpty ═══ IBoolean isEmpty ( ) const; Returns True if the tree is empty. ═══ 5.2.2.5.15. isLeaf ═══ IBoolean isLeaf ( ITreeCursor const& cursor ) const; Returns True if the node pointed to by the given cursor is a leaf node of the tree. A leaf node is a node with no children. Precondition The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.16. isRoot ═══ IBoolean isRoot ( ITreeCursor const& cursor ) const; Returns True if the node pointed to by the given cursor is the root node of the tree. Precondition The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.17. newCursor ═══ ITreeCursor* newCursor ( ) const; Creates a cursor for the tree. The cursor is initially invalid. Return Value Pointer to the cursor. Exception IOutOfMemory ═══ 5.2.2.5.18. numberOfChildren ═══ INumber numberOfChildren ( ) const; Returns the number of children a node can possibly have. The actual number of children of any node will always be less than or equal to this number. ═══ 5.2.2.5.19. numberOfElements, numberOfSubtreeElements ═══ INumber numberOfElements ( ) const; INumber numberOfSubtreeElements ( ITreeCursor const& cursor ) const; Returns the number of elements that the subtree denoted by the given cursor contains. The subtree root, inner, and leaf nodes are counted. The numberOfElements() function (without a cursor argument) counts the number of elements in the whole tree. Preconditions The cursor must belong to the tree and must point to an element in the tree. Exception ICursorInvalidException ═══ 5.2.2.5.20. numberOfLeaves, numberOfSubtreeLeaves ═══ INumber numberOfLeaves ( ) const; INumber numberOfSubtreeLeaves ( ITreeCursor const& cursor ) const; Returns the number of leaf elements that the subtree denoted by the given cursor contains. Leaves are nodes that have no children. The numberOfLeaves() function (without a cursor argument) counts the number of leaves in the whole tree. Preconditions The cursor must belong to the tree and must point to an element in the tree. Exception ICursorInvalidException ═══ 5.2.2.5.21. position ═══ INumber position ( ITreeCursor const& cursor ) const; Returns the position of the node pointed to by the given cursor as a child with respect to its parent node. The position of the root node is 1. Precondition The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.22. removeAll, removeSubtree ═══ void removeAll ( ) ; void removeSubtree ( ITreeCursor const& cursor ) ; Removes the subtree denoted by the given cursor (of this tree). The removeAll() function (without a cursor argument) removes all elements from this tree. Precondition The cursor must point to an element of this tree. Side Effects For removeSubtree(), the given cursor is invalidated after removal. Exception ICursorInvalidException ═══ 5.2.2.5.23. replaceAt ═══ void replaceAt ( ITreeCursor const& cursor, Element const& element ) ; Replaces the element pointed to by the cursor with the given element. Precondition The cursor must point to an element of this tree. Exception ICursorInvalidException ═══ 5.2.2.5.24. setToChild ═══ IBoolean setToChild ( IPosition position, ITreeCursor& cursor ) const; Sets the cursor to the child with the given position of the node denoted by the given cursor (of this tree). Invalidates the cursor if this child does not exist. Preconditions  The cursor must point to an element of this tree.  (1 <= position <= numberOfChildren()). Return Value Returns True if the child exists. Exceptions  ICursorInvalidException  IPositionInvalidException ═══ 5.2.2.5.25. setToFirst ═══ IBoolean setToFirst ( ITreeCursor& cursor, ITreeIterationOrder iterationOrder ) const; Sets the cursor to the first node in the given iteration order. Invalidates the cursor if the tree is empty. Precondition The cursor must belong to this tree. Return Value Returns True if the tree is not empty. Exception ICursorInvalidException ═══ 5.2.2.5.26. setToFirstExistingChild ═══ IBoolean setToFirstExistingChild ( ITreeCursor& cursor ) const; Sets the cursor to the first child of the node denoted by the given cursor (of this tree). Invalidates the cursor if the node has no child. A node with no child is a leaf node of the tree. Preconditions The cursor must point to an element of this tree. Return Value Returns True if the node has a child. Exception ICursorInvalidException ═══ 5.2.2.5.27. setToLast ═══ IBoolean setToLast ( ITreeCursor& cursor, ITreeIterationOrder iterationOrder ) const; Sets the cursor to the last node in the given iteration order. Invalidates the cursor if the tree is empty. Precondition The cursor must belong to this tree. Return Value Returns True if the tree is not empty. Exception ICursorInvalidException ═══ 5.2.2.5.28. setToLastExistingChild ═══ IBoolean setToLastExistingChild ( ITreeCursor& cursor ) const; Sets the cursor to the last child of the node denoted by the given cursor (of this tree). Invalidates the cursor if the node has no child. A node with no child is a leaf node of the tree. Precondition The cursor must point to an element of this tree. Return Value Returns True if the node has a child. Exception ICursorInvalidException ═══ 5.2.2.5.29. setToNext ═══ IBoolean setToNext ( ITreeCursor& cursor, ITreeIterationOrder iterationOrder ) const; Sets the cursor to the next node in the given iteration order. Invalidates the cursor if there is no next node. Precondition The cursor must point to an element of this tree. Return Value Returns True if the given cursor does not point to the last node (in iteration order). Exception ICursorInvalidException ═══ 5.2.2.5.30. setToNextExistingChild ═══ IBoolean setToNextExistingChild ( ITreeCursor& cursor ) const; Sets the cursor to the next existing sibling of the node denoted by the given cursor (of this tree). Invalidates the cursor if the node has no next sibling. A node with no next sibling is the last existing child of its parent. Precondition The cursor must point to an element of this tree. Return Value Returns True if the node has a next sibling. Exception ICursorInvalidException ═══ 5.2.2.5.31. setToParent ═══ IBoolean setToParent ( ITreeCursor& cursor ) const; Sets the cursor to the parent of the node denoted by the given cursor (of this tree). Invalidates the cursor if the node has no parent. A node with no parent is the root node of its tree. Precondition The cursor must point to an element of this tree. Return Value Returns True if the node has a parent. Exception ICursorInvalidException ═══ 5.2.2.5.32. setToPrevious ═══ IBoolean setToPrevious ( ITreeCursor& cursor, ITreeIterationOrder iterationOrder ) const; Sets the cursor to the previous node in the given iteration order. Invalidates the cursor if there is no previous node. Precondition The cursor must point to an element of this tree. Return Value Returns True if the given cursor does not point to the first node (in iteration order). Exception ICursorInvalidException ═══ 5.2.2.5.33. setToPreviousExistingChild ═══ IBoolean setToPreviousExistingChild ( ITreeCursor& cursor ) const; Sets the cursor to the previous existing sibling of the node denoted by the given cursor (of this tree). Invalidates the cursor if the node has no previous sibling. A node with no previous sibling is the first existing child of its parent. Precondition The cursor must point to an element of this tree. Return Value Returns True if the node has a previous sibling. Exception ICursorInvalidException ═══ 5.2.2.5.34. setToRoot ═══ IBoolean setToRoot ( ITreeCursor& cursor ) const; Sets the cursor to the root node of the tree. Invalidates the cursor if the tree is empty (that is, if no root node exists). Precondition The cursor must belong to this tree. Return Value Returns True if the tree is not empty. Exception ICursorInvalidException ═══ 5.3. Auxiliary Collection Classes ═══ This section contains the following chapters: Cursor Describes the declarations and public member functions for the cursor classes. Tree Cursor Describes the declarations and public member functions for the tree cursor classes. Iterator and Constant Iterator Classes Describes the declarations and public member functions for the classes that define the interface for iterator objects. Pointer Classes Describes the declarations and public member functions for the classes that allow you to access collection classes through pointers. ═══ 5.3.1. Cursor ═══ Description Header File Constructors Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.3.1.1. Class Description - ICursor ═══ Each collection class defines its own nested cursor class. All of these cursor classes are derived from one of the following classes:  IElementCursor  IOrderedCursor IOrderedCursor is derived from IElementCursor, and IElementCursor is in turn derived from ICursor. Only cursors of ordered collections are derived from IOrderedCursor. Cursors from unordered collections are derived from IElementCursor, and only know the member functions from IElementCursor and ICursor. This chapter describes the general member functions of these three cursor classes as well as the specific member functions provided for specific collections. Because the cursor classes are all abstract classes, no objects of type IOrderedCursor, IElementCursor, or ICursor can be declared. You can obtain cursor objects by using the collection member newCursor(), or by defining a cursor of a specific collection cursor class. The newCursor() member creates a cursor of the collection to which it is applied. The newCursor() member returns a pointer to the newly created cursor object. Each cursor object is associated with a collection object. A cursor function merely calls the corresponding function for this collection. For example, cursor.setToFirst() is the same as collection.setToFirst(cursor), where collection is the object associated with cursor. ═══ Header File ═══ The cursor classes are declared in icursor.h. Note that individual collection header files already include icursor.h; you do not need to include the file in your programs. ═══ 5.3.1.2. Members ═══ The following member functions are described:  Constructor  copy  isValid  invalidate  element  operator!=  operator==  setToFirst  setToLast  setToNext  setToPrevious ═══ 5.3.1.2.1. Constructor ═══ Cursor ( Collection const& collection ) ; Constructs the cursor and associates it with the given collection. The cursor is initially invalid. The name of the constructor is that of the nested cursor class. ═══ 5.3.1.2.2. copy ═══ void copy (ICursor const& cursor) ; Copies the given cursor to this cursor. This cursor now points to where the given cursor points. Precondition The given cursor and this cursor must refer to the same collection type. Note: This precondition cannot be checked. ═══ 5.3.1.2.3. isValid ═══ IBoolean isValid ( ) const; Returns True if the cursor points to an element of the associated collection. ═══ 5.3.1.2.4. invalidate ═══ void invalidate ( ) ; Invalidates the cursor; that is, it no longer points to an element of the associated collection. ═══ 5.3.1.2.5. element ═══ Element const& element ( ) const; Returns a constant reference to the element of the associated collection to which the cursor points. Precondition The cursor must point to an element of the associated collection. Exception ICursorInvalidException ═══ 5.3.1.2.6. operator!= ═══ IBoolean operator!= ( Cursor const& cursor ) const; IBoolean operator!= ( ICursor const& cursor ) const; Returns True if the cursor does not point to the same element (of the same collection) as the given cursor. ═══ 5.3.1.2.7. operator== ═══ IBoolean operator== ( Cursor const& cursor ) const; IBoolean operator== ( ICursor const& cursor ) const; Returns True if the cursor points to the same element (of the same collection) as the given cursor. ═══ 5.3.1.2.8. setToFirst ═══ IBoolean setToFirst ( ) ; Sets the cursor to the first element of the associated collection in iteration order. Invalidates the cursor if the collection is empty (if no first element exists). Return Value Returns True if the associated collection is not empty. ═══ 5.3.1.2.9. setToLast ═══ IBoolean setToLast ( ) ; Sets the cursor to the last element of the associated collection in iteration order. Invalidates the cursor if the collection is empty (no last element exists). This function is only available for cursors of ordered collections. Returns True if the associated collection was not empty. ═══ 5.3.1.2.10. setToNext ═══ IBoolean setToNext ( ) ; Sets the cursor to the next element in the associated collection in iteration order. Invalidates the cursor if no more elements are left to be visited. Returns True if there was a next element. Precondition The cursor must point to an element of the associated collection. Exception ICursorInvalidException ═══ 5.3.1.2.11. setToPrevious ═══ IBoolean setToPrevious ( ) ; Sets the cursor to the previous element of the associated collection in iteration order. Invalidates the cursor if no such element exists. This function is only available for cursors of ordered collections. Return Value Returns True if a previous element exists. Precondition The cursor must point to an element of the associated collection. Exception ICursorInvalidException ═══ 5.3.2. Tree Cursor ═══ Description Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.3.2.1. Class Description - ITreeCursor ═══ For n-ary trees, cursors are used to point to nodes in the tree. Unlike cursors of flat collections, tree cursors stay defined when elements are added to the tree, or when elements other than the one pointed to are removed. Cursors are used in operations to access the element information stored in a node. They are also used to designate a subtree of the tree, namely the subtree whose root node the cursor points to. As for flat collections, a distinction is made between the abstract base class ITreeCursor, and cursor classes local to the tree classes themselves. The local, or nested, cursor classes are derived from the abstract base class. ═══ Header Files ═══ The declarations for ITreeCursor can be found in itcursor.h. ═══ Members ═══ Tree Cursor defines the following member functions:  Constructor  operator!=  operator==  element  isValid  invalidate  setToChild  setToFirstExistingChild  setToLastExistingChild  setToNextExistingChild  setToParent  setToPreviousExistingChild  setToRoot ═══ 5.3.2.2. Constructor ═══ Cursor ( Tree const& tree ) ; Constructs the cursor and associates it with the given tree. The cursor is initially invalid. ═══ 5.3.2.3. operator!= ═══ IBoolean operator!= ( Cursor const& cursor ) ; Returns True if the cursor does not point to the same node of the same tree as the given cursor. ═══ 5.3.2.4. operator== ═══ IBoolean operator== ( Cursor const& cursor ) ; Returns True if the cursor points to the same node of the same tree as the given cursor. ═══ 5.3.2.5. element ═══ Element const& element ( ) ; Returns a reference to the element of the associated tree to which the cursor points. Preconditions The cursor must point to a node of the associated tree. Exception ICursorInvalidException ═══ 5.3.2.6. isValid ═══ IBoolean isValid ( ) ; Returns True if the cursor points to a node of the associated tree. ═══ 5.3.2.7. invalidate ═══ void invalidate ( ) ; Invalidates the cursor so that it no longer points to a node of the associated tree. ═══ 5.3.2.8. setToChild ═══ IBoolean setToChild ( IPosition position ) ; Sets the cursor to the child node with the given position. If the child does not exist, the cursor is invalidated. If the child at the given position exists, setToChild() returns True. Preconditions  (1 <= position <= numberOfChildren).  The cursor must point to a node of the associated tree. Exceptions  IPositionInvalidException  ICursorInvalidException ═══ 5.3.2.9. setToFirstExistingChild ═══ IBoolean setToFirstExistingChild ( ) ; Sets the cursor to the first existing child of the associated tree. If the node pointed to by the cursor has no children (that is, if the node is a leaf) the cursor is invalidated. If the node pointed to by the cursor has a child, setToFirstExistingChild() returns True. ═══ 5.3.2.10. setToLastExistingChild ═══ IBoolean setToLastExistingChild ( ) ; Sets the cursor to the last existing child of the associated tree. If the node pointed to by the cursor has no children (that is, if the node is a leaf) the cursor is invalidated. If the node pointed to by the cursor has a child, setToLastExistingChild() returns True. ═══ 5.3.2.11. setToNextExistingChild ═══ IBoolean setToNextExistingChild ( ) ; Sets the cursor to the next existing sibling of the node to which the cursor points. If the node to which the cursor points is the last child of its parent, no next existing child exists and the cursor is invalidated. Return Value Returns False if a next existing child exists. Preconditions The cursor must point to a node of the associated tree. Exception ICursorInvalidException ═══ 5.3.2.12. setToParent ═══ IBoolean setToParent ( ) ; Sets the cursor to the parent of the node pointed to by the cursor. If the cursor points to the root, the node has no parent, and the cursor is invalidated. Return Value Returns True if the node has a parent. Preconditions The cursor must point to a node of the associated tree. Exception ICursorInvalidException ═══ 5.3.2.13. setToPreviousExistingChild ═══ IBoolean setToPreviousExistingChild ( ) ; Sets the cursor to the previous existing sibling of the node to which the cursor points. If the node to which the cursor points is the last child of its parent, no more children exist and the cursor is invalidated. Return Value Returns True if there was a previous child. Precondition The cursor must point to a node of the associated tree. Exception ICursorInvalidException ═══ 5.3.2.14. setToRoot ═══ IBoolean setToRoot ( ) ; Sets the cursor to the root of the associated tree. If the collection is empty (if no root element exists), the cursor is invalidated. Otherwise, setToRoot() returns True. ═══ 5.3.3. Iterator and Constant Iterator Classes ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.3.3.1. Class Description - IIterator ═══ The classes IIterator and IConstantIterator define the interface for iterator objects. The redefinition of the function applyTo() defines the actions that are performed with the version of allElementsDo() that takes an iterator argument. (See allElementsDo for more information on this function.) Iteration stops when applyTo() returns False. ═══ Derivation ═══ These classes do not derive from any other class. ═══ Header File ═══ iiter.h ═══ Members ═══ These classes define only one function, as a virtual function.  applyTo() ═══ 5.3.3.2. applyTo ═══ virtual IBoolean applyTo (Element const& element) = 0; This function applies a series of specified statements or a function to all elements of a collection for which you use the iterator. For example, myCollection.allElementsDo(myIterator); causes the code in the applyTo() function that you code for your iterator object myIterator to be applied to all elements of the collection myCollection. For an example on how to use iterators, see Iteration Using Iterators in the Open Class Library User's Guide. ═══ 5.3.4. Pointer Classes ═══ Description Header File Members Examples To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.3.4.1. Class Description - Pointer Classes ═══ The Collection Class Library defines five pointer classes:  IAutoPointer  IAutoElemPointer  IElemPointer  IMngPointer  IMngElemPointer You can select from these classes depending on your requirements:  Pointers from classes named I...ElemPointer (also called element pointers) route the operations on the pointers to the referenced elements.  Pointers from classes named IAuto...Pointer (also called automatic pointers) delete the elements they reference when the pointers are destructed. No reference count is kept.  Pointers from classes named IMng...Pointer (also called managed pointers) keep a reference count for each referenced element. When the last managed pointer to the element is destructed, the element is automatically deleted. For further information on the characteristics of these pointer types and how to use them, see Using Pointer Classes. ═══ Header File ═══ The pointer classes are declared in the header file iptr.h. ═══ 5.3.4.2. Members ═══ The pointer classes define constructors, a destructor, and four operators. An equality test operator, although not actually a member of the pointer classes, is also available.  Constructors  Constructors from a Given C++ Pointer  Copy Constructors from a Given Collection Class Pointer  Destructors  operator*  Conversion operator  operator->  operator=  operator== ═══ 5.3.4.2.1. Constructors ═══ IAutoPointer (); IElemPointer (); IMngPointer (); Constructs a pointer of the indicated type and initializes it with NULL. ═══ 5.3.4.2.2. Constructors from a Given C++ Pointer ═══ IAutoPointer (Element *ptr, IExplicitInit) IAutoElemPointer (Element *ptr, IExplicitInit) IElemPointer (Element *ptr, IExplicitInit = IINIT) IMngPointer (Element *ptr, IExplicitInit) IMngElemPointer (Element *ptr, IExplicitInit) Constructs a pointer object of the indicated type from a given C++ pointer. For managed pointers, the reference count of the referenced element is set to 1. ═══ 5.3.4.2.3. Copy Constructors from a Given Collection Class Pointer ═══ IAutoPointer (IAutoPointer < Element > const& ptr) IMngPointer (IMngPointer < Element > const& ptr) Constructs a new pointer and initializes it with the given pointer. For automatic pointers, the given pointer is set to NULL. For managed pointers, the reference count of the referenced element is incremented by 1. ═══ 5.3.4.2.4. Destructors ═══ ~IAutoPointer () ~IAutoElemPointer () Deletes the object referenced to by the automatic pointer. ~IMngPointer () ~IMngElemPointer () Destructs the pointer and decrements the reference count of the referenced element. If the reference count is 0, the referenced element is deleted. ═══ 5.3.4.2.5. operator* ═══ Element& operator * () const; Returns a reference to the object to which the pointer refers. ═══ 5.3.4.2.6. Conversion operator ═══ operator Element* () const Implicitly convert this pointer to a C++ pointer. ═══ 5.3.4.2.7. operator-> ═══ Element* operator-> () const Returns a C pointer to the object to which the pointer refers. ═══ 5.3.4.2.8. operator= ═══ void operator = (IAutoPointer < Element > const& ptr) IMngPointer < Element >& operator = (IMngPointer < Element > const& ptr) IMngElemPointer < Element >& operator = (IMngElemPointer < Element > const& ptr) Assigns the given pointer to this pointer. For automatic pointers, the given pointer is set to NULL and the previously referenced element is deleted. For managed pointers, the reference count of the referenced element is incremented and the reference count of the previously referenced element is decremented. ═══ 5.3.4.2.9. operator== ═══ The pointer classes do not have an operator== explicitly defined for them. However, for equality test you can use the syntax: pointerVariable1 == pointerVariable2; The conversion operator (operator Element*) implicitly converts the objects to C pointers, and then the operator== for C pointers is invoked. Because the operator== is not actually a member of the class, you cannot write an equality test like the following: if (pointerVariable1.operator==(pointerVariable2)) {/* ... */} ═══ 5.3.4.3. Coding Example for Managed Element Pointer ═══ The following sample allows you to store managed pointers for various graphical objects into a key sorted set. The graphical objects, namely lines, curves, and circles, inherit from a base class Graphics. Using these pointers, you can draw the various shapes from the collection. // graph.C - demonstrate how to use Collection Class pointers #include #include "graph.h" #include "line.h" #include "circle.h" #include "curve.h" #include #include typedef IMngElemPointer MngGraphicsPointer; typedef IKeySortedSet MngPointerKSet; ostream & operator << (ostream & sout, MngPointerKSet const& mgdPointerKSet) { MngGraphicsPointer drawObject; MngPointerKSet::Cursor gpsCursor(mgdPointerKSet); forCursor(gpsCursor) { drawObject = gpsCursor.element(); sout << "\n Key is: " << drawObject->graphicsKey() << "\n ID is: " << drawObject->id() << endl; drawObject->draw(); } /* endfor */ return sout; } int main () { MngPointerKSet graphMngPointerKSet; // Add curve pointers, circle pointers and line // pointers to the graphMngPointerKSet. //Creating curve objects and adding pointers to the collections MngGraphicsPointer pcurve1 (new Curve (10, "Curve 1", 1.1, 4.3, 2.1, 6.4, 3.1, 9.7, 4.1, 6.5, 5.1, 7.4), IINIT); MngGraphicsPointer pcurve2 (new Curve (20 ,"Curve 2", 1.2, 3.9, 2.2, 5.9, 3.2, 8.8, 4.2, 7.5, 5.2, 9.4), IINIT); graphMngPointerKSet.add(pcurve1); graphMngPointerKSet.add(pcurve2); //Creating circle objects and adding pointers to the collections MngGraphicsPointer pcircle1 (new Circle (40 , "Circle 1" , 1.0, 1.0, 1.0), IINIT); MngGraphicsPointer pcircle2 (new Circle (50 , "Circle 2", 2.0, 2.0, 2.0), IINIT); graphMngPointerKSet.add(pcircle1); graphMngPointerKSet.add(pcircle2); //Creating line objects and adding pointers to the collections MngGraphicsPointer pline1 (new Line (70 , "Line 1" , 1.1 , 1.1 , 5.1 , 5.1), IINIT); MngGraphicsPointer pline2 (new Line (80 , "Line 2" , 2.2 , 2.2 , 5.2 , 5.2), IINIT); // if you want to have a normal C-pointer: Line* cPointerToLine = new Line (90 , "Line 3" , 3.3 , 3.3 , 5.3 , 5.3); MngGraphicsPointer pline3 (cPointerToLine, IINIT); graphMngPointerKSet.add(pline1); graphMngPointerKSet.add(pline2); graphMngPointerKSet.add(pline3); cout << "Drawing the shapes from the key set " << "of Managed Pointers: \n" << graphMngPointerKSet << "\n " << endl; graphMngPointerKSet.elementWithKey(70)->draw(); cPointerToLine->draw(); pline3->draw(); // Now we are about to end the program. The objects referenced // by managed pointers are automatically deleted. See what // happens in the output of the program. return 0; } ═══ 5.4. Abstract Collection Classes ═══ This part describes the abstract Collection Classes. The following classes are described:  Collection  Equality collection  Equality key collection  Equality key sorted collection  Equality sorted collection  Key collection  Key sorted collection  Ordered collection  Sequential collection  Sorted collection ═══ 5.4.1. Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.1.1. Class Description - Collection ═══ Collection is the base class for almost all classes defined by the Collection Class Library. Because collection is an abstract class, it cannot be used to create any objects. ═══ Derivation ═══ Collection does not have any bases. The following abstract classes are derived from collection:  Key collection  Equality collection  Ordered collection The concrete class heap is defined by collection. The Abstract Class Hierarchy shows the relationship of collection to the class hierarchy. ═══ Header File ═══ Collection is declared in the header file iacllct.h. ═══ Members ═══ All the member functions of collection are defined as virtual functions and are described in Introduction to Flat Collections. The following member functions are provided for collection:  Destructor  add  addAllFrom  anyElement  compare  Copy Constructor  elementAtPosition  isBounded  isEmpty  isFull  maxNumberOfElements  newCursor  numberOfElements  removeAll  removeAt  replaceAt  setToFirst  setToNext ═══ 5.4.2. Equality Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.2.1. Class Description - Equality Collection ═══ Because equality collection is an abstract class, it cannot be used to create any objects. The equality collection defines the interfaces for the property of element equality. ═══ Derivation ═══ Collection Equality Collection The following abstract classes are derived from equality collection:  Equality key collection  Equality sorted collection The following concrete classes are defined by equality collection:  Set  Bag  Equality Sequence The Abstract Class Hierarchy shows the relationship of equality collection to the class hierarchy. ═══ Header File ═══ The equality collection class is declared in the header file iaequal.h. ═══ Members ═══ The equality collection class defines the following member functions, described in Introduction to Flat Collections, as virtual functions:  Destructor  contains  containsAllFrom  locate  locateNext  locateOrAdd  numberOfOccurrences  remove  removeAllOccurrences ═══ 5.4.3. Equality Key Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.3.1. Class Description - Equality Key Collection ═══ Because equality key collection is an abstract class, it cannot be used to create any objects. It defines the interfaces for the following properties:  Element equality  Key equality ═══ Derivation ═══ Collection Equality Collection Key Collection Equality Key Collection Equality key sorted collection is an abstract class that is derived from equality key collection. The following concrete classes are defined by equality key collection:  Map  Relation The Abstract Class Hierarchy shows the relationship of equality key collection to the whole class hierarchy. ═══ Header File ═══ The equality key collection class is declared in the header file iaeqkey.h. ═══ Members ═══ All the members of equality key sorted collection are inherited from its base classes. ═══ 5.4.4. Equality Key Sorted Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.4.1. Class Description - Equality Key Sorted Collection ═══ Equality key sorted collection is an abstract class that defines the interfaces for the following properties:  Element equality  Key equality  Sorted elements Because equality key sorted collection is an abstract class, it cannot be used to create any objects. ═══ Derivation ═══ Equality key sorted collection is derived from the following three abstract classes:  Key sorted collection  Equality sorted collection  Equality key sorted collection For information on the bases of these classes, see the figure "Abstract Class Hierarchy" in section Abstract Classes. The following concrete classes are defined by equality key sorted collection:  Sorted map  Sorted relation The Abstract Class Hierarchy shows the relationship of equality key sorted collection to the class hierarchy. ═══ Header File ═══ The equality key sorted collection class is declared in the header file iaeqksrt.h. ═══ Members ═══ All the members of equality key sorted collection are inherited from its base classes. ═══ 5.4.5. Equality Sorted Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.5.1. Class Description - Equality Sorted Collection ═══ Because equality sorted collection is an abstract class, it cannot be used to create any objects. It defines the interfaces for the following properties:  Element equality  Sorted elements ═══ Derivation ═══ Collection Ordered Collection Equality Collection Sorted Collection Equality Sorted Collection Equality key sorted collection is an abstract class that is derived from equality sorted collection. The following concrete classes are defined by equality sorted collection:  Sorted set  Sorted bag The Abstract Class Hierarchy shows the relationship of equality sorted collection to the class hierarchy. ═══ Header File ═══ The equality sorted collection class is declared in the header file iaeqsrt.h. ═══ Members ═══ All members of equality sorted collection are inherited from its base classes. ═══ 5.4.6. Key Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.6.1. Class Description - Key Collection ═══ Because key collection is an abstract class, it cannot be used to create any objects. The key collection inherits from collection and defines the interfaces for the key property. ═══ Derivation ═══ Collection Key Collection The following abstract classes are derived from key collection:  Equality key collection  Key sorted collection The following concrete classes are defined by key collection:  Key set  Key bag The Abstract Class Hierarchy shows the relationship of key collection to the class hierarchy. ═══ Header File ═══ The key collection class is declared in the header file iakey.h. ═══ Members ═══ The key collection class defines the following member functions, described in Introduction to Flat Collections, as virtual functions:  Destructor  addOrReplaceElementWithKey  containsAllKeysFrom  containsElementWithKey  elementWithKey  key  locateElementWithKey  locateNextElementWithKey  locateOrAddElementWithKey  numberOfDifferentKeys  numberOfElementsWithKey  removeAllElementsWithKey  removeElementWithKey  replaceElementWithKey  setToNextWithDifferentKey ═══ 5.4.7. Key Sorted Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.7.1. Class Description - Key Sorted Collection ═══ Because key sorted collection is an abstract class, it cannot be used to create any objects. The key sorted collection inherits from sorted collection and key collection. It defines the interfaces for the following properties:  Key equality  Sorted elements ═══ Derivation ═══ Collection Ordered Collection Key Collection Sorted Collection Key Sorted Collection The equality key sorted collection is an abstract class that is derived from key sorted collection. The following concrete classes are defined by key sorted collection:  Key sorted set  Key sorted bag The Abstract Class Hierarchy shows the relationship of key sorted collection to the class hierarchy. ═══ Header File ═══ The key sorted collection class is declared in the header file iaksrt.h. ═══ Members ═══ The key sorted collection class inherits all member functions from its base classes. ═══ 5.4.8. Ordered Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.8.1. Class Description - Ordered Collection ═══ Because ordered collection is an abstract class, it cannot be used to create any objects. The ordered collection defines the interfaces for the property of ordered elements. ═══ Derivation ═══ Collection Ordered Collection The following abstract classes are derived from ordered collection:  Sorted collection  Sequential collection The Abstract Class Hierarchy shows the relationship of ordered collection to the class hierarchy. ═══ Header File ═══ The ordered collection class is declared in the header file iaorder.h. ═══ Members ═══ The ordered collection class defines the following member functions, described in Introduction to Flat Collections, as pure virtual functions:  Destructor  elementAtPosition  firstElement  isFirst  isLast  lastElement  position  removeAtPosition  removeFirst  removeLast  setToLast  setToPosition  setToPrevious ═══ 5.4.9. Sequential Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.9.1. Class Description - Sequential Collection ═══ Because sequential collection is an abstract class, it cannot be used to create any objects. The sequential collection inherits from ordered collection and defines the interfaces for the properties of ordered elements. ═══ Derivation ═══ Collection Ordered Collection Sequential Collection The following concrete classes are defined by sequential collection:  Sequence  Equality sequence The Abstract Class Hierarchy shows the relationship of sequential collection to the class hierarchy. ═══ Header File ═══ The sequential collection class is declared in the header file iasqntl.h. ═══ Members ═══ Sequential collection defines the following member functions as pure virtual functions:  Destructor  operator=  add  addAllFrom  addAsFirst  addAsLast  addAsNext  addAsPrevious  addAtPosition  allElementsDo  anyElement  compare  elementAt  elementAtPosition  firstElement  isBounded  isEmpty  isFirst  isFull  isLast  lastElement  maxNumberOfElements  newCursor  position  removeAll  removeAt  removeAtPosition  removeFirst  removeLast  replaceAt  setToFirst  setToLast  setToNext  setToPosition  setToPrevious  sort ═══ 5.4.10. Sorted Collection ═══ Description Derivation Variants/Header Files Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 5.4.10.1. Class Description - Sorted Collection ═══ Because sorted collection is an abstract class, it cannot be used to create any objects. The sorted collection inherits from ordered collection and defines the interfaces for the properties of sorted elements. ═══ Derivation ═══ Collection Ordered Collection Sorted Collection The following abstract classes are derived from sorted collection:  Equality sorted collection  Key sorted collection The Abstract Class Hierarchy shows the relationship of sorted collection to the class hierarchy. ═══ Header File ═══ The sorted collection class is declared in the header file iasrt.h. ═══ Members ═══ The sorted collection class inherits all its members from its bases. ═══ 5.5. Header Files for Collection Class Library Coding Examples ═══ This section contains edited header files used by some coding examples found in this book. The following header files are shown: animal circle.h curve.h demoelem dsur graph.h line.h parcel planet toyword transelm trmapops xebc2asc These header files can be found in ...\ibmclass\samples\iclcc. Some comments and white space have been removed. ═══ 5.5.1. animal.h ═══ // animal.h - Class Animal for use with the example animals.C #include // For definition of Boolean #include // Class IString #include class Animal { IString nm; IString attr; public: Animal(IString n, IString a) : nm(n), attr(a) {} // For copy constructor we use the compiler generated default. // For assignment we use the compiler generated default. IBoolean operator==(Animal const& p) const { return ((nm == p.name()) && (attr == p.attribute())); } IString const& name() const { return nm; } IString const& attribute() const { return attr; } friend ostream& operator<<(ostream& os, Animal const& p) { return os << "The " << p.name() << " is " << p.attribute() << "." << endl; } }; // Key access: inline IString const& key(Animal const& p) { return p.name(); } // We need a hash function for the key type as well. // Let's just use the default provided for IString. inline unsigned long hash(Animal const& animal, unsigned long n) { return hash(animal.name(), n); } ═══ 5.5.2. circle.h ═══ // circle.h #include class Circle : public Graphics { public: float ivXCenter; float ivYCenter; float ivRadius; Circle(int graphicsKey, IString id , double xCenter, double yCenter, double radius) : Graphics(graphicsKey, id), ivXCenter(xCenter), ivYCenter(yCenter), ivRadius(radius) { } IBoolean operator== (Circle const& circle) const { return (this->ivXCenter == circle.ivXCenter && this->ivYCenter == circle.ivYCenter && this->ivRadius == circle.ivRadius); } void draw() const { cout << "drawing " << Graphics::id() << endl << "with center: " << "(" << this->ivXCenter << "|" << this->ivYCenter << ")" << " and with radius: " << this->ivRadius << endl; } void circumference() const { cout << "The circumference of " << Graphics::id() << " is: " << ((this->ivRadius)*2*3.14) << endl; } }; ═══ 5.5.3. curve.h ═══ // curve.h #include class Curve : public Graphics { public: float ivXStart, ivYStart; float ivXFix1, ivYFix1; float ivXFix2, ivYFix2; float ivXFix3, ivYFix3; float ivXEnd, ivYEnd; Curve(int graphicsKey, IString id, float xstart, float ystart, float xfix1, float yfix1, float xfix2, float yfix2, float xfix3, float yfix3, float xend, float yend) : Graphics(graphicsKey, id), ivXStart(xstart), ivYStart(ystart), ivXFix1(xfix1), ivYFix1(yfix1), ivXFix2(xfix2), ivYFix2(yfix2), ivXFix3(xfix3), ivYFix3(yfix3), ivXEnd(xend), ivYEnd(yend) { } IBoolean operator== (Curve const& curve) const { return (this->ivXStart == curve.ivXStart && this->ivYStart == curve.ivYStart && this->ivXFix1 == curve.ivXFix1 && this->ivYFix1 == curve.ivYFix1 && this->ivXFix2 == curve.ivXFix2 && this->ivYFix2 == curve.ivYFix2 && this->ivXFix3 == curve.ivXFix3 && this->ivYFix3 == curve.ivYFix3 && this->ivXEnd == curve.ivXEnd && this->ivYEnd == curve.ivYEnd); } void draw() const { cout << "drawing " << Graphics::id() << "\nwith starting point: " << "(" << this->ivXStart << "|" << this->ivYStart << ")" << " and with fix points: " << "(" << this->ivXFix1 << "|" << this->ivYFix1 << ")" << "(" << this->ivXFix2 << "|" << this->ivYFix2 << ")" << "(" << this->ivXFix3 << "|" << this->ivYFix3 << ")\n" << "and with ending point: " << "(" << this->ivXEnd << "|" << this->ivYEnd << ")" << endl; } void lengthOfCurve() const { cout << "Length of " << Graphics::id() << " is: " << (sqrt(pow(((this->ivXFix1) - (this->ivXStart)),2) + pow(((this->ivYFix1) - (this->ivYStart)),2)) + sqrt(pow(((this->ivXFix2) - (this->ivXFix1)),2) + pow(((this->ivYFix2) - (this->ivYFix1)),2)) + sqrt(pow(((this->ivXFix3) - (this->ivXFix2)),2) + pow(((this->ivYFix3) - (this->ivYFix2)),2)) + sqrt(pow(((this->ivXEnd) - (this->ivXFix3)),2) + pow(((this->ivYEnd) - (this->ivYFix3)),2))) << endl; } }; ═══ 5.5.4. demoelem.h ═══ // demoelem.h - DemoElement for use with Key Collections #ifndef _DEMOELEM_H #define _DEMOELEM_H #include #include #include #include class DemoElement { int i, j; public: DemoElement () : i(0), j(0) {} DemoElement (int i,int j) : i (i), j(j) {} operator int () const { return i; } IBoolean operator == (DemoElement const& k) const { return i == k.i && j == k.j; } IBoolean operator < (DemoElement const& k) const { return i < k.i || (i == k.i && j < k.j); } friend unsigned long hash (DemoElement const& k, unsigned long n) { return k.i % n; } int const & geti () const { return i; } int const & getj () const { return j; } }; inline ostream & operator << (ostream &sout, DemoElement const& e) { sout << e.geti () << "," << e.getj (); return sout; } inline int const& key (DemoElement const& k) { return k.geti (); } // NOTE: You must return a const & in the key function! Otherwise the // standard element operations will return a reference to a temporary. // This would lead to incorrect behavior of the collection operations. // The key function must be declared in the header file of // the collection's element type. // If either of these is not possible or is undesirable, // an element operations class must be used. #endif ═══ 5.5.5. dsur.h ═══ // dsur.h - Class for Disk Space Usage Records // Used by Sorted Map and Sorted Relation example #include #include #include const int bufSize = 62; class DiskSpaceUR { int blocks; char* name; public: DiskSpaceUR() {} DiskSpaceUR (DiskSpaceUR const& dsur) { init(dsur); } void operator= (DiskSpaceUR const& dsur) { deInit(); init(dsur); } DiskSpaceUR (istream& DSURfile) { DSURfile >> *this; } ~DiskSpaceUR () { deInit(); } IBoolean operator == (DiskSpaceUR const& dsur) const { return (blocks == dsur.blocks) && strcmp (name, dsur.name) == 0; } friend istream& operator >> (istream& DSURfile, DiskSpaceUR& dsur) { DSURfile >> dsur.blocks; char temp[bufSize]; DSURfile.get(temp, bufSize); if (DSURfile.good()) { // Remove leading tabs and blanks for (int cnt=0; (temp[cnt] == '\t') || (temp[cnt] == ' '); cnt++) {} dsur.name = new char[strlen(temp+cnt)+1]; strcpy(dsur.name, temp+cnt); } else { dsur.setInvalid(); dsur.name = new char[1]; dsur.name[0] = '\0'; } return DSURfile; } friend ostream& operator << (ostream& outstream, DiskSpaceUR& dsur) { outstream.width(bufSize); outstream.setf(ios::left, ios::adjustfield); outstream << dsur.name; outstream.width(9); outstream.setf(ios::right, ios::adjustfield); outstream << dsur.blocks; return outstream; } inline int const& space () const {return blocks;} inline char* const& id () const {return name;} inline IBoolean isValid () const {return (blocks > 0);} protected: inline void init (DiskSpaceUR const& dsur) { blocks = dsur.blocks; name = new char[strlen(dsur.name) + 1]; strcpy(name, dsur.name); } inline void deInit() { delete[] name; } inline void setInvalid () { blocks = -1;} }; // Key access on name inline char* const& key (DiskSpaceUR const& dsur) { return dsur.id(); } // Key access on space used // Since we can not have two key functions with same args // in global name space, we need to use an operations class. #include // We can inherit all from the default operations class // and then define just the key access function ourselves. // We cannot use StdKeyOps here, because they in turn // use the key function in global name space, which is // already defined for keys of type char* above. class DSURBySpaceOps : public IStdMemOps, public IStdAsOps< DiskSpaceUR >, public IStdEqOps< DiskSpaceUR > { public: IStdCmpOps < int > keyOps; // Key Access int const& key (DiskSpaceUR const& dsur) const { return dsur.space(); } }; ═══ 5.5.6. graph.h ═══ #include #include class Graphics { protected: IString ivId; //*** graphics ID ****/ int ivKey; //*** graphics key ****/ public: Graphics (int graphicsKey, IString id) : ivKey(graphicsKey), ivId(id) { } ~Graphics() { cout << this->ivId << " will now be deleted ... " << endl; } IBoolean operator== (Graphics const& graphics) const { return (this->ivId == graphics.ivId); } IString const& id() const { return ivId; } virtual void draw() const =0; /**** This member function returns the graphic's key ****/ /* Note that we are returning the int by reference, */ /* because this member function will be used by the */ /* key(...) function, which must return a reference. */ /********************************************************/ int const& graphicsKey() const { return ivKey; } }; /**************** key function *********************/ /**** note that this interface must always be used with: ****/ /**** Keytype const& key(....) ****/ /**** We are providing this key function for the element ****/ /**** type Graphics and not for the managed pointer. ****/ /***************************************************************/ inline int const& key (Graphics const& graphics) { return graphics.graphicsKey(); } ═══ 5.5.7. line.h ═══ #include #include class Line : public Graphics { public: double ivXStart, ivYStart; double ivXEnd, ivYEnd; Line(int graphicsKey, IString id, double xstart, double ystart, double xend, double yend) : Graphics(graphicsKey, id), ivXStart(xstart), ivYStart(ystart), ivXEnd(xend), ivYEnd(yend) { } IBoolean operator== (Line const& line) const { return (this->ivXStart == line.ivXStart && this->ivYStart == line.ivYStart && this->ivXEnd == line.ivXEnd && this->ivYEnd == line.ivYEnd); } void draw() const { cout << "drawing " << Graphics::id() << endl << "with starting point: " << "(" << this->ivXStart << "|" << this->ivYStart << ")" << " and with ending point: " << "(" << this->ivXEnd << "|" << this->ivYEnd << ")" << endl; } void lengthOfLine() const { cout << "The length of line " << Graphics::id() << " is: " << sqrt(pow(((this->ivXEnd) - (this->ivXStart)),2) + pow(((this->ivYEnd) - (this->ivYStart)),2)) << endl; } }; ═══ 5.5.8. parcel.h ═══ // parcel.h - Class Parcel and its parts for use with the // example for Key Sorted Set and Heap. #include // For definition of Boolean: #include // Class IString: #include class PlaceTime { IString cty; int daynum; // Keeping it simple: January 9 is day 9 public: PlaceTime(IString acity, int aday) : cty(acity), daynum(aday) {} PlaceTime(IString acity) : cty(acity) {daynum = 0;} IString const& city() const { return cty; } int const& day() const { return daynum; } void operator=(PlaceTime const& pt) { cty = pt.cty; daynum = pt.daynum; } IBoolean operator==(PlaceTime const& pt) const { return ( (cty == pt.cty) && (daynum == pt.daynum) ); } }; class Parcel { PlaceTime org, lstAr; IString dst, id; public: Parcel(IString orig, IString dest, int day, IString ident) : org(orig, day), lstAr(orig, day), dst(dest), id(ident) {} void arrivedAt(IString const& acity, int const& day) { PlaceTime nowAt(acity, day); // Only if not already there before if (nowAt.city() != lstAr.city()) lstAr = nowAt; } void wasDelivered(int const& day) {arrivedAt(dst, day); } PlaceTime const& origin() const { return org; } IString const& destination() const { return dst; } PlaceTime const& lastArrival() const { return lstAr; } IString const& ID() const { return id; } friend ostream& operator<<(ostream& os, Parcel const& p) { os << p.id << ": From " << p.org.city() << "(day " << p.org.day() << ") to " << p.dst; if (p.lstAr.city() != p.dst) { os << endl << " is at " << p.lstAr.city() << " since day " << p.lstAr.day() << "."; } else { os << endl << " was delivered on day " << p.lstAr.day() << "."; } return os; } }; // Key access: inline IString const& key( Parcel const& p) { return p.ID(); } // We need a compare function for the key. // Let's use the default provided for IString: inline long compare(Parcel const& p1, Parcel const& p2) { return compare(p1.ID(), p2.ID()); } ═══ 5.5.9. planet.h ═══ // planet.h - Class Planet for use in our Sorted Set example class Planet { private: char* plname; float dist, mass, bright; public: // Use the compiler generated default for the copy constructor Planet(char* aname, float adist, float amass, float abright) : plname(aname), dist(adist), mass(amass), bright(abright) {} // For any Set we need to provide element equality. IBoolean operator== (Planet const& aPlanet) const { return plname == aPlanet.plname; } // For a Sorted Set we need to provide element comparision. IBoolean operator< (Planet const& aPlanet) const { return dist < aPlanet.dist; } char* name() { return plname; } IBoolean isHeavy() { return (mass > 1.0); } IBoolean isBright() { return (bright < 0.0); } }; // Iterator #include class SayPlanetName : public IIterator { public: virtual IBoolean applyTo(Planet& p) { cout << " " << p.name() << " "; return True;} }; ═══ 5.5.10. toyword.h ═══ // toyword.h - Class Word for use with coding examples. #include class Word { IString ivWord; unsigned ivKey; public: //Constructor to be used for sample: wordbag.c Word (IString word, unsigned theLength) : ivWord(word), ivKey(theLength) {} //Constructor to be used for sample: wordseq.c Word (IString word) : ivWord(word) {} IBoolean operator> (Word const& w1) { return this->ivWord > w1.ivWord; } unsigned setKey() { this->ivKey = this->ivWord.length(); return this->ivKey; } IString const& getWord() const { return this->ivWord; } unsigned const& getKey() const { return this->ivKey; } }; // Key access. The length of the word is the key. inline unsigned const& key (Word const &aWord) { return aWord.getKey(); } ═══ 5.5.11. transelm.h ═══ // transelm.h - For use with the Translation Table example. #ifndef _TRANSELM_H #define _TRANSELM_H #include class TranslationElement { char ivAscCode; char ivEbcCode; public: /* Let the compiler generate Default and Copy Constructor,*/ /* Destructor and Assignment for us. */ char const& ascCode () const { return ivAscCode; } char const& ebcCode () const { return ivEbcCode; } TranslationElement (char asc, char ebc) : ivAscCode(asc), ivEbcCode(ebc) {}; /* We need to define the equality relation. */ IBoolean operator == (TranslationElement const& te) const { return ivAscCode == te.ivAscCode && ivEbcCode == te.ivEbcCode; }; /* An ordering relation must not be defined for */ /* elements in a map. */ /* We need to define the key access for the elements. */ /* We decided to define all key operations in a */ /* separate operations class in file trmapops.h. */ }; #endif ═══ 5.5.12. trmapops.h ═══ // trmapops.h - Translation Map Operations // Base class for element operations for Translation Map example #ifndef _TRMAPOPS_H #define _TRMAPOPS_H // Get the standard operation classes. #include #include "transelm.h" class TranslationOps : public IEOps < TranslationElement > { public: class KeyOps : public IStdEqOps < char >, public IStdHshOps < char > { } keyOps; }; // Operations Class for the EBCDIC-ASCII mapping: class TranslationOpsE2A : public TranslationOps { public: // Key Access char const& key (TranslationElement const& te) const { return te.ebcCode (); } }; // Operations Class for the ASCII-EBCDIC mapping: class TranslationOpsA2E : public TranslationOps { public: // Key Access char const& key (TranslationElement const& te) const { return te.ascCode (); } }; #endif ═══ 5.5.13. xebc2asc.h ═══ // xebc2asc.h : EBCDIC - ASCII Translation Table. const unsigned char translationTable[256] = { 0x00,0x01,0x02,0x03,0xCF,0x09,0xD3,0x7F,0xD4,0xD5,0xC3,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0xC7,0xB4,0x08,0xC9,0x18,0x19,0xCC,0xCD,0x83,0x1D,0xD2,0x1F, 0x81,0x82,0x1C,0x84,0x86,0x0A,0x17,0x1B,0x89,0x91,0x92,0x95,0xA2,0x05,0x06,0x07, 0xE0,0xEE,0x16,0xE5,0xD0,0x1E,0xEA,0x04,0x8A,0xF6,0xC6,0xC2,0x14,0x15,0xC1,0x1A, 0x20,0xA6,0xE1,0x80,0xEB,0x90,0x9F,0xE2,0xAB,0x8B,0x9B,0x2E,0x3C,0x28,0x2B,0x7C, 0x26,0xA9,0xAA,0x9C,0xDB,0xA5,0x99,0xE3,0xA8,0x9E,0x21,0x24,0x2A,0x29,0x3B,0x5E, 0x2D,0x2F,0xDF,0xDC,0x9A,0xDD,0xDE,0x98,0x9D,0xAC,0xBA,0x2C,0x25,0x5F,0x3E,0x3F, 0xD7,0x88,0x94,0xB0,0xB1,0xB2,0xFC,0xD6,0xFB,0x60,0x3A,0x23,0x40,0x27,0x3D,0x22, 0xF8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x96,0xA4,0xF3,0xAF,0xAE,0xC5, 0x8C,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x97,0x87,0xCE,0x93,0xF1,0xFE, 0xC8,0x7E,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0xEF,0xC0,0xDA,0x5B,0xF2,0xF9, 0xB5,0xB6,0xFD,0xB7,0xB8,0xB9,0xE6,0xBB,0xBC,0xBD,0x8D,0xD9,0xBF,0x5D,0xD8,0xC4, 0x7B,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xCB,0xCA,0xBE,0xE8,0xEC,0xED, 0x7D,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0xA1,0xAD,0xF5,0xF4,0xA3,0x8F, 0x5C,0xE7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0xA0,0x85,0x8E,0xE9,0xE4,0xD1, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xB3,0xF7,0xF0,0xFA,0xA7,0xFF }; ═══ 6. Database Access Classes ═══ Use the database access classes to connect and disconnect from your DB2/2 database and to perform transactions in the database. Database Access C++ Classes This chapter describes the C++ version of the database access class library. Use these classes when you create applications or components with C++ or the Visual Builder. Database Access C++ Exception Classes This chapter describes the exception classes. Database Access SOM Classes This chapter describes the SOM version of the database access class library. Use these classes when you want to use SOM objects to access your database. ═══ 6.1. Database Access C++ Classes ═══ This chapter describes the C++ version of the database access classes. Use these classes when you generate Visual Builder parts. ═══ 6.1.1. IDatastore ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.1.2. Class Description - IDatastore ═══ The IDatastore provides client connection to the database, disconnect from the database, and commit and rollback of transactions. The following attributes are used by IDatastore:  authentication The authentication is the password. When logon is performed, if the userName is a null string, authentication is not used.  datastoreName This is the name of the datastore to connect to.  userName When attempting a connect, if userName or authentication are not specified (""), IDatastore throws the exception IDatastoreLogonFailed if there is no current user logged on. If userName and authentication are both specified, IDatastore.connect attempts a logon if the current logged on user is different than userName. - If logon was performed during IDatastore.connect, IDatastore.disconnect will logoff. - If already connected, IDatastore.connect disconnects and reconnects (including logon if necessary). Two classes are provided to allow IDatastore to be used within Visual Builder when building your applications. They are:  IDatastore  IDSConnectCanvas These parts can be found in the file VBDAX.VBB. IDatastore is a nonvisual part provided in VBDAX.VBB. This part is the visual interface to the Data Access Builder class IDatastore. It is a reusable part that can be dropped into the nonvisual portion of your application. Use this part to connect to the datastore when the application is started. Use the settings page for this part to set the datastoreName after placing it into the composition editor edit area. Then use the ready event of the frame to call the connect() method, and the close event of the frame to call the disconnect() method. IDSConnectCanvas is a visual part (a child of ICanvas), provided in VBDAX.VBB. This part provides a user interface to access the functions of IDatastore. It is a reusable part that can be dropped into the main frame window of your visual applications. Use this part when the connect panel is to be the primary window of an application, or to access IDatastore from other places within the application in addition to the connect window. Use this part by dropping onto the canvas of the primary frame window of the application. IDatastoreInterface is an exposed attribute of this part. Use the exposed events, methods and attributes to control IDatastore in addition to the controls provided on the canvas. ═══ Derivation ═══ IStandardNotifier IDatastore ═══ Header File ═══ IDatastore is declared in idsmcon.hpp. ═══ 6.1.2.1. Members ═══ The following methods are provided:  Constructor  Destructor  authentication  commit  connect()  connect  datastoreName  isConnected  disconnect  rollback  setAuthentication  setDatastoreName  setUserName  userName ═══ 6.1.2.1.1. Constructor ═══ IDatastore (); IDatastore ( const IString& datastoreName, const IString& userName = "", const IString& authentication = ""); The IDatastore constructor allocates an object. This object is used to manage a connection to the datastore. ═══ 6.1.2.1.2. Destructor ═══ virtual ~IDatastore (); The IDatastore destructor frees space allocated by the constructor. ═══ 6.1.2.1.3. authentication ═══ IString authentication() const; IDatastore& setAuthentication(const IString& aAuthentication); Gets the authentication. ═══ 6.1.2.1.4. commit ═══ void commit () Commits the transactions. Exceptions  IDatastoreAccessError  IDatastoreConnectionNotOpen ═══ 6.1.2.1.5. connect() ═══ void connect () Performs the connect using the current settings specified. If there is already a connection to the database, it is disconnected and then reconnected using the current settings. For information regarding userName, see page IDatastore. Exceptions  IConnectFailed  IDatastoreAccessError  IDatastoreConnectionInUse  IDatastoreLogoffFailed  IDatastoreLogonFailed ═══ 6.1.2.1.6. connect ═══ void connect ( const IString& datastoreName, const IString& userName = "", const IString& authentication = ""); Performs the connect using the input parameters specified. If there is already a connection to the database, it is disconnected and then reconnected using the current settings. For information regarding userName, see page IDatastore. Exceptions  IConnectFailed  IDatastoreAccessError  IDatastoreConnectionInUse  IDatastoreLogoffFailed  IDatastoreLogonFailed ═══ 6.1.2.1.7. datastoreName ═══ IString datastoreName() const; Gets the current datastore name setting. ═══ 6.1.2.1.8. disconnect ═══ void disconnect () Closes the connection to a database. If a logon was performed on the connect, userName is logged off. Exceptions  IDatastoreConnectionNotOpen  IDatastoreLogoffFailed  IDisconnectError ═══ 6.1.2.1.9. isConnected ═══ Boolean isConnected (); Returns true if there is a connection to the database. ═══ 6.1.2.1.10. rollback ═══ void rollback () Performs a rollback on the transactions. Exceptions  IDatastoreAccessError  IDatastoreConnectionNotOpen ═══ 6.1.2.1.11. setAuthentication ═══ IDatastore& setAuthentication(const IString& aAuthentication); Sets the authentication (password). For information regarding authentication, see page IDatastore. ═══ 6.1.2.1.12. setDatastoreName ═══ IDatastore& setDatastoreType(const IString& aDatastoreName); Sets the datastore name that is used when a connection is established. ═══ 6.1.2.1.13. setUserName ═══ IDatastore& setUserName(const IString& aUserName); Sets the user name. For information regarding userName, see page IDatastore. ═══ 6.1.2.1.14. userName ═══ IString userName() const; Gets the current user name setting. For information regarding userName, see page IDatastore. ═══ 6.1.3. IPersistentObject ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.1.4. Class Description - IPersistentObject ═══ The IPersistentObject class provides the basic data manipulation operations where a client can call directly to add, update, delete or retrieve a row from a table. It is the abstract base class for all of the parts generated by the tool. The generated part also contains the methods for getting and setting the attribute values. These methods are:  () const  const IString & AsString() const  void set(attribute type)  void set(const IString &)  Boolean isNullabe() const  Boolean isNull() const  void setToNull(Boolean = true) ═══ Derivation ═══ IStandardNotifier IPersistentObject ═══ Header File ═══ IPersistentObject is declared in ipersist.hpp. ═══ Members ═══ The following methods are provided:  Constructors  Destructor  add  delete  isDefaultReadOnly  isReadOnly  operator!=  operator==  operator=  retrieve  setReadOnly  update ═══ 6.1.4.1. Public Members ═══ The following member functions are described:  constructors  destructor  add  delete  isDefaultReadOnly  isReadOnly  operator!=  operator==  operator=  retrieve  setReadOnly  update ═══ 6.1.4.1.1. Constructors ═══ IPersistentObject (); IPersistentObject (const IPersistentObject& partCopy); The IPersistentObject constructor allocates space for keeping the values of the selected columns from a single row of a table. ═══ 6.1.4.1.2. Destructor ═══ virtual ~IPersistentObject (); The IPersistentObject destructor frees the allocated space by the constructor. ═══ 6.1.4.1.3. add ═══ virtual IPersistentObject &add () = 0; Add a row to a table using the data attribute values set in the object. The object should be uniquely identified by the data identifier. Exceptions  IDSAccessError ═══ 6.1.4.1.4. delete ═══ virtual IPersistentObject &del () = 0; Delete rows from a table using the data identifier set in the object. The composition of the data identifier is defined for the concrete class. Exceptions  IDSAccessError ═══ 6.1.4.1.5. isDefaultReadOnly ═══ virtual void isDefaultReadOnly(); This function returns a value of true if the table is read-only by default. Otherwise, it returns a value of false. If the table is read-only by default, an exception occurs on an add, delete or update statement. In this case, you can only use the retrieve statement to read the row from the table. Also, when the table is read-only by default, you can not use setReadOnly to change the setting. ═══ 6.1.4.1.6. isReadOnly ═══ virtual Boolean isReadOnly(); This function returns a value of true if the table is read-only. Otherwise, it returns a value of false. If the table is read-only, an exception occurs on an add, delete or update statement. ═══ 6.1.4.1.7. operator!= ═══ Boolean operator != (const IPersistentObject& value) const, operator != (const IPersistentObject* value) const; Compares the values of two persistent objects. ═══ 6.1.4.1.8. operator== ═══ Boolean operator == (const IPersistentObject& value) const, operator == (const IPersistentObject* value) const, Compares the values of two persistent objects. ═══ 6.1.4.1.9. operator= ═══ IPersistentObject& operator= (const IPersistentObject& aIPersistentObject); This function assigns the values kept in the other object to this object. ═══ 6.1.4.1.10. retrieve ═══ virtual IPersistentObject &retrieve () = 0; Retrieve a row from a table using the data identifier set in the object. The composition of the data identifier is defined by the concrete class. The data identifier must be set on the object before calling retrieve. Exceptions  IDSAccessError ═══ 6.1.4.1.11. setReadOnly ═══ virtual void setReadOnly (Boolean flag=true); This function sets the table to read-only or updateable. ═══ 6.1.4.1.12. update ═══ virtual IPersistentObject &update () = 0; Update the row using the data identifier set in the object. The composition of the data identifier is defined by the concrete class. Exceptions  IDSAccessError ═══ 6.1.5. IPOManager ═══ Description Derivation Header File Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.1.6. Class Description - IPOManager ═══ The IPOManager class provides operations to deal with collections of rows from a table. It is the abstract base class for all of the generated collection parts. The collection is pointed by a private data member and its data type is a pointer to IVSequence. You can manipulate the items in the collection with the functions in the IVSequence class. ═══ Derivation ═══ IStandardNotifier IPOManager ═══ Header File ═══ IPOManager is declared in ipersist.hpp. ═══ 6.1.6.1. Members ═══ The following methods are provided:  Constructors  Destructor  items()  refresh  select ═══ 6.1.6.1.1. Constructors ═══ IPOManager(); IPOManager(const IPOManager& partCopy); IPOManager& operator= (const IPOManager& aIPOManager); The IPOManager constructor allocates space for supporting collection parts. ═══ 6.1.6.1.2. Destructor ═══ virtual ~IPOManager(); The IPOManager destructor frees allocated space. ═══ 6.1.6.1.3. items() ═══ virtual IVSequence* items(); Returns the pointer to the cllection containing objects. This is a template and is not implemented in the base class. ═══ 6.1.6.1.4. refresh ═══ virtual IPOManager &refresh () = 0; Retrieves a collection of all rows on the table from the database. Exceptions  IDSAccessError ═══ 6.1.6.1.5. select ═══ virtual IPOManager &select (const IString& clause) = 0; Retrieves a collection of all rows on the table that match the specified predicate from the datastore. The predicate must be specified in the syntax of the SQL where clause. Exceptions  IDSAccessError ═══ 6.2. Database Access C++ Exception Classes ═══ The following classes are described:  IConnectFailed  IDatastoreAccessError  IDatastoreAdaptorException  IDatastoreConnectionInUse  IDatastoreConnectionNotOpen  IDatastoreLogoffFailed  IDatastoreLogonFailed  IDisconnectError  IDSAccessError ═══ 6.2.1. IConnectFailed ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.2. Class Description - IConnectFailed ═══ Objects of the IConnectFailed class represent an exception. This class creates and throws an object when one of the following occurs:  maximum number of IDatastoreMgr connections has already been reached  a connection was attempted while a transaction was in progress ═══ Derivation ═══ IException IDatastoreAdaptorException IConnectFailed ═══ Header File ═══ idsexc.hpp. ═══ 6.2.2.1. Constructors ═══ public: IConnectFailed( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.2.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.2.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.3. IDatastoreAccessError ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.4. Class Description - IDatastoreAccessError ═══ Objects of the IDatastoreAccessError class represent an exception. This class creates and throws an object when one of the following occurs:  bind file not found  connect error  bind error. ═══ Derivation ═══ IException IDatastoreAdaptorException IDatastoreAccessError ═══ Header File ═══ idsexc.hpp ═══ 6.2.4.1. Constructors ═══ public: IDatastoreAccessError( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.4.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.4.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.5. IDatastoreAdaptorException ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.6. Class Description - IDatastoreAdaptorException ═══ Objects of the IDatastoreAdaptorException class represent an exception. This class is a generic exception message of accessing datastore. ═══ Derivation ═══ IException IDatastoreAdaptorException ═══ Header File ═══ idsexc.hpp ═══ 6.2.6.1. Constructors ═══ public: IDatastoreAdaptorException( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.6.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.6.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.7. IDatastoreConnectionInUse ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.8. Class Description - IDatastoreConnectionInUse ═══ Objects of the IDatastoreConnectionInUse class represent an exception. This class creates and throws an object when a connection is attempted using a connection which is already in use. ═══ Derivation ═══ IException IDatastoreAdaptorException IDatastoreConnectionInUse ═══ Header File ═══ idsexc.hpp ═══ 6.2.8.1. Constructors ═══ public: IDatastoreConnectionInUse( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.8.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.8.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.9. IDatastoreConnectionNotOpen ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.10. Class Description - IDatastoreConnectionNotOpen ═══ Objects of the IDatastoreConnectionNotOpen class represent an exception. This class creates and throws an object when an operation which requires a connection was attempted but the connection has not been established yet. For example, a call to disconnect before a connection was made. ═══ Derivation ═══ IException IDatastoreAdaptorException IDatastoreConnectionNotOpen ═══ Header File ═══ idsexc.hpp ═══ 6.2.10.1. Constructors ═══ public: IDatastoreConnectionNotOpen( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.10.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.10.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.11. IDatastoreLogoffFailed ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.12. Class Description - IDatastoreLogoffFailed ═══ Objects of the IDatastoreLogoffFailed class represent an exception. The class creates and throws an object when a logoff failes. ═══ Derivation ═══ IException IDatastoreLogoffFailed ═══ Header File ═══ idsexc.hpp ═══ 6.2.12.1. Constructors ═══ public: IDatastoreLogoffFailed( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.12.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.12.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.13. IDatastoreLogonFailed ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.14. Class Description - IDatastoreLogonFailed ═══ Objects of the IDatastoreLogonFailed class represent an exception. The class creates and throws an object when a logon attempt fails. ═══ Derivation ═══ IException IDatastoreLogonFailed ═══ Header File ═══ idsexc.hpp ═══ 6.2.14.1. Constructors ═══ public: IDatastoreLogonFailed( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.14.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.14.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.15. IDisconnectError ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.16. Class Description - IDisconnectError ═══ Objects of the IDisconnectError class represent an exception. This class creates and throws an object when a disconnect error occurs. ═══ Derivation ═══ IException IDatastoreAdaptorException IDisconnectError ═══ Header File ═══ idsexc.hpp ═══ 6.2.16.1. Constructors ═══ public: IDisconnectError( const char *errorText, unsigned long errorId, Severity severity = IException::unrecoverable); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. ═══ 6.2.16.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.16.3. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.2.17. IDSAccessError ═══ Description Derivation Header File Constructors Member - name Inherited Public Members To close all the panels in a chapter, double-click on this panel's system menu. ═══ 6.2.18. Class Description - IDSAccessError ═══ Objects of the IDSAccessError class represent an exception thrown from generated code. When thrown, errorId is set with the following values: DAX_ADD_READONLY // Add used on a readonly table/view DAX_ADD_SQLERR // SQL error occurred on add DAX_UPD_READONLY // Update used on a readonly table/view DAX_UPD_SQLERR // SQL error occurred on update DAX_DEL_READONLY // Delete used ona readonly table/view DAX_DEL_SQLERR // SQL error occurred on delete DAX_RET_SQLERR // SQL error occurred on retrieve DAX_REF_SQLERR // SQL error occurred on refresh DAX_SEL_SQLERR // SQL error occurred on select DAX_ADD_NONNULL // Add with non-nullable column not mapped DAX_NUL_NONNULL // Cannot SetToNull non-nullable column DAX_DFT_READONLY // Cannot SetReadOnly to false on a readonly table/view DAX_SYS_LOCK // Error occurred during system semaphore/locking call DAX_ADD_NULL_DATAID // Add with a null DataId DAX_UPD_NULL_DATAID // Update with a null DataId DAX_DEL_NULL_DATAID // Delete with a null DataId DAX_RET_NULL_DATAID // Retrieve with a null DataId ═══ Derivation ═══ IException IDatastoreAdaptorException IDSAccessError ═══ Header File ═══ idsexc.hpp ═══ 6.2.18.1. Constructors ═══ public: IDSAccessError( const char* a, unsigned long b = 0, Severity c = IException::unrecoverable, struct sqlca* sqlca_p=0 ); You can create objects of this class by doing the following:  Using the constructor. errorText The text describing this particular error. errorId The identifier you want to associate with this particular error. severity Use the enumeration IException::Severity to specify the severity of the error. The default is unrecoverable. sqlca Uses the contents of the sqlca at the time of the exception. ═══ 6.2.18.2. Public Member - name ═══ virtual const char *name() const; Returns the name of the object's class. ═══ 6.2.18.3. Public Member - getSqlca ═══ struct sqlca const& getSqlca() const; Returns the contents of the sqlca at the time of the exception. ═══ 6.2.18.4. Inherited Public Members ═══ For information on the members inherited from the IException class, see IException ═══ 6.3. Database Access SOM Classes ═══ This chapter describes the SOM version of the Database Access classes. Use these classes when you want to use SOM objects. ═══ 6.3.1. Datastore & DatastoreFactory ═══ Datastore and DatastoreFactory provide client connection to the database, disconnect from the database, and commit and rollback of transactions. For additional information, see IDatastore. interface DatastoreFactory : SOMClass { Datastore create_object(); Datastore create_object_defaults(in string datastore_name, in string user_name, in string authentication); #ifdef __SOMIDL__ implementation { releaseorder : create_object; create_object_defaults; }; #endif }; interface Datastore : SOMObject { void connect ( in string datastore_name, in string user_name, in string authentication, raises (DaxExcep::ConnectFailed, DaxExcep::DatastoreConnectionInUse, DaxExcep::DatastoreAccessError, DaxExcep::DatastoreLogonFailed, DaxExcep::DatastoreLogoffFailed); void connect_defaults () raises (DaxExcep::ConnectFailed, DaxExcep::DatastoreConnectionInUse, DaxExcep::DatastoreAccessError, DaxExcep::DatastoreLogonFailed, DaxExcep::DatastoreLogoffFailed); void disconnect () raises (DaxExcep::DatastoreConnectionNotOpen, DaxExcep::DisconnectError, DaxExcep::DatastoreLogoffFailed); void commit () raises DaxExcep::DatastoreAccessError, DaxExcep::DatastoreConnectionNotOpen); void rollback () raises DaxExcep::DatastoreAccessError, DaxExcep::DatastoreConnectionNotOpen); boolean is_connected (); boolean is_sharemode_exclusive(); void enable_sharemode_exclusive (in boolean enable); attribute string datastore_name; attribute string user_name; attribute string authentication; #ifdef __SOMIDL__ implementation { metaclass = DatastoreFactory; releaseorder: connect, connect_defaults, disconnect, commit, rollback, is_connected, is_sharemode_exclusive, enable_sharemode_exclusive, _get_datastore_name, _set_datastore_name, _get_user_name, _set_user_name, _get_authentication, _set_authentication, datastore_name: noset, noget; user_name: noset, noget; authentication: noset, noget; somInit: override; somUninit: override; }; #endif }; #endif ═══ 6.3.2. PersistentObject & POFactory ═══ The PersistentObject class provides the basic data manipulation operations where a client can call directly to add, update, delete or retrieve a row from a table. It is the abstract base class for all of the parts generated by the tool. For additional information, see IPersistentObject. The POFactory class provides operations to deal with collections of rows from a table. For additional information, see IPOManager. interface POFactory : SOMClass { exception POFError { long error_code; long sqlcode; }; sequence retrieveAll() raises(POFError); sequence select(in string clause) raises(POFError); void setPOFException(in long errorCode, in long sqlcode); #ifdef __SOMIDL__ implementation { releaseorder : retrieveAll, select, setPOFException; }; #endif }; interface PersistentObject : SOMObject { exception POError { long error_code; long sqlcode; }; void add() raises(POError); void update() raises(POError); void del() raises(POError); void retrieve() raises(POError); void setPOException(in long errorCode, in long sqlcode); #ifdef __SOMIDL__ implementation { releaseorder : add, update, del, retrieve, setPOException; metaclass = POFactory; }; #endif }; When an exception occurs, error_code is set with the following values: DAX_ADD_READONLY // Add used on a readonly table/view DAX_ADD_SQLERR // SQL error occurred on add DAX_UPD_READONLY // Update used on a readonly table/view DAX_UPD_SQLERR // SQL error occurred on update DAX_DEL_READONLY // Delete used ona readonly table/view DAX_DEL_SQLERR // SQL error occurred on delete DAX_RET_SQLERR // SQL error occurred on retrieve DAX_REF_SQLERR // SQL error occurred on refresh DAX_SEL_SQLERR // SQL error occurred on select DAX_ADD_NONNULL // Add with non-nullable column not mapped DAX_NUL_NONNULL // Cannot SetToNull non-nullable column DAX_DFT_READONLY // Cannot SetReadOnly to false on a readonly table/view DAX_SYS_LOCK // Error occurred during system semaphore/locking call DAX_ADD_NULL_DATAID // Add with a null DataId DAX_UPD_NULL_DATAID // Update with a null DataId DAX_DEL_NULL_DATAID // Delete with a null DataId DAX_RET_NULL_DATAID // Retrieve with a null DataId If the exception is an SQL exception, the sqlcode is set with the SQLCODE returned from the static SQL statement.