Building an Existing File If the .CPP source file already exists, as it does for the example programs in this book, select Openfrom the File menu.. If you’re compiling an example program
Trang 1Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
Introduction
Object-Oriented Programming (OOP) is the most dramatic innovation in software development inthe last decade It ranks in importance with the development of the first higher-level languages atthe dawn of the computer age Sooner or later, every programmer will be affected by the object-oriented approach to program design
Advantages of OOP
Why is everyone so excited about OOP? The chief problem with computer programs is complexity.Large programs are probably the most complicated entities ever created by humans Because of thiscomplexity, programs are prone to error, and software errors can be expensive and even life
threatening (in air-traffic control, for example) Object-Oriented Programming offers a new andpowerful way to cope with this complexity Its goal is clearer, more reliable, more easily
maintained programs
Languages and Development Platforms
Of the Object-Oriented Programming languages, C++ is by far the most widely used (Java, a recentaddition to the field of OO languages, lacks certain features, such as pointers, that make it lesspowerful and versatile than C++.)
In past years the standards for C++ have been in a state of evolution This meant that each compilervendor handled certain details differently However, in November 1997, the ANSI/ISO C++
standards committee approved the final draft of what is now known as Standard C++ (ANSI standsfor American National Standards Institute, and ISO stands for International Standards Institute.)Standard C++ adds many new features to the language, such as the Standard Template Library(STL) In this book we follow Standard C++ (except for a few places which we’ll note as we goalong)
The most popular development environments for C++ are manufactured by Microsoft and Borlandand run on the various flavors of Microsoft Windows In this book we’ve attempted in ensure thatall example programs run on the current versions of both Borland and Microsoft compilers (SeeAppendixes C and D for more on these compilers.)
What this Book Does
Trang 2This book teaches Object-Oriented Programming with the C++ programming language, using eitherMicrosoft or Borland compilers It is suitable for professional programmers, students, and kitchen-table enthusiasts.
New Concepts
OOP involves concepts that are new to programmers of traditional languages such as Pascal, Basic,and C These ideas, such as classes, inheritance, and polymorphism, lie at the heart of Object-Oriented Programming But it’s easy to lose sight of these concepts when discussing the specifics
of an object-oriented language Many books overwhelm the reader with the details of languagefeatures, while ignoring the reason these features exist This book attempts to keep an eye on thebig picture and relate the details to the larger concepts
The Gradual Approach
We take a gradual approach in this book, starting with very simple programming examples andworking up to full-fledged object-oriented applications We introduce new concepts slowly so thatyou will have time to digest one idea before going on to the next We use figures whenever possible
to help clarify new ideas There are questions and programming exercises at the end of mostchapters to enhance the book’s usefulness in the classroom Answers to the questions and to thefirst few (starred) exercises can be found in Appendix D The exercises vary in difficulty to pose avariety of challenges for the student
What You Need to Know to Use this Book
You can use this book even if you have no previous programming experience However, suchexperience, in BASIC or Pascal, for example, certainly won’t hurt
You do not need to know the C language to use this book Many books on C++ assume that youalready know C, but this one does not It teaches C++ from the ground up If you do know C, itwon’t hurt, but you may be surprised at how little overlap there is between C and C++
You should be familiar with the basic operations of Microsoft Windows, such as startingapplications and copying files
Software and Hardware
You should have the latest version of either the Microsoft or the Borland C++ compiler Bothproducts come in low-priced “Learning Editions” suitable for students
Appendix C provides detailed information on operating the Microsoft compiler, while Appendix Ddoes the same for the Inprise (Borland) product Other compilers will probably handle most of theprograms in this book as written, if they adhere to Standard C++
Your computer should have enough processor speed, memory, and hard disk space to run thecompiler you’ve chosen You can check the manufacturer’s specifications to determine theserequirements
Console-Mode Programs
Trang 3The example programs in this book are console-mode programs They run in a character-modewindow within the compiler environment, or directly within an MS-DOS box This avoids thecomplexity of full-scale graphics-oriented Windows programs Go for It!
You may have heard that C++ is difficult to learn It’s true that it might be a little more challengingthan BASIC, but it’s really quite similar to other languages, with two or three “grand ideas” thrown
in These new ideas are fascinating in themselves, and we think you’ll have fun learning aboutthem They are also becoming part of the programming culture; they’re something everyone shouldknow a little bit about, like evolution and psychoanalysis We hope this book will help you enjoylearning about these new ideas, at the same time that it teaches you the details of programming in
We devote a new chapter to the STL (Standard Template Library), which is now included inStandard C++
Object-Oriented Design
Students are frequently mystified by the process of breaking a programming project intoappropriate classes For this reason we’ve added a chapter on object-oriented design This chapter isplaced near the end of the book, but we encourage students to skim it earlier to get the flavor ofOOD Of course, small programs don’t require such a formal design approach, but it’s helpful toknow what’s involved even when designing programs in your head C++ is not the same as C.Some institutions want their students to learn C before learning C++ In our view this is a mistake
C and C++ are entirely separate languages It’s true that their syntax is similar, and C is actually asubset of C++ But the similarity is largely a historical accident In fact, the basic approach in a Cprogram is radically different from that in a C program
C++ has overtaken C as the preferred language for serious software development Thus we don’tbelieve it is necessary or advantageous to teach C before teaching C++ Students who don’t know Care saved the time and trouble of learning C and then learning C++, an inefficient approach
Students who already know C may be able to skim parts of some chapters, but they will find that aremarkable percentage of the material is new
Optimize Organization for OOP
We could have begun the book by teaching the procedural concepts common to C and C++, and
Trang 4moved on to the new OOP concepts once the procedural approach had been digested That seemedcounterproductive, however, because one of our goals is to begin true Object-Oriented
Programming as quickly as possible Accordingly, we provide a minimum of proceduralgroundwork before getting to objects in Chapter 7 Even the initial chapters are heavily steeped in
C++, as opposed to C, usage
We introduce some concepts earlier than is traditional in books on C For example, structures are akey feature for understanding C++ because classes are syntactically an extension of structures Forthis reason, we introduce structures in Chapter 5 so that they will be familiar when we discussclasses
Some concepts, such as pointers, are introduced later than in traditional C books It’s not necessary
to understand pointers to follow the essentials of OOP, and pointers are usually a stumbling blockfor C and C++ students Therefore, we defer a discussion of pointers until the main concepts ofOOP have been thoroughly digested
Substitute Superior C++ Features
Some features of C have been superseded by new approaches in C++ For instance, the andfunctions, input/output workhorses in C, are seldom used in C++ because and do a better job.Consequently, we leave out descriptions of these functions Similarly, constants and macros in Chave been largely superseded by the qualifier and inline functions in C++, and need be mentionedonly briefly
Minimize Irrelevant Capabilities
Because the focus in this book is on Object-Oriented Programming, we can leave out some features
of C that are seldom used and are not particularly relevant to OOP For instance, it isn’t necessary
to understand the C bit-wise operators (used to operate on individual bits) to learn Object-OrientedProgramming These and a few other features can be dropped from our discussion, or mentionedonly briefly, with no loss in understanding of the major features of C++
The result is a book that focuses on the fundamentals of OOP, moving the reader gently but brisklytoward an understanding of new concepts and their application to real programming problems
Programming Examples
There are numerous listings of code scattered throughout the book that you will want to try out foryourself The program examples are available for download by going to Macmillan ComputerPublishing’s web site, http://www.mcp.com/product_support, and go to this book’s page byentering the ISBN and clicking Search To download the programming examples, just click theappropriate link on the page
Programming Exercises
One of the major changes in the second edition was the addition of numerous exercises Each ofthese involves the creation of a complete C++ program There are roughly 12 exercises per chapter
Trang 5these involves the creation of a complete C++ program There are roughly 12 exercises per chapter.Solutions to the first three or four exercises in each chapter are provided in Appendix D For theremainder of the exercises, readers are on their own, although qualified instructors can suggestedsolutions Please visit Macmillan Computer Publishing’s Web site,
http://www.mcp.com/product_support, and go to this book’s page by entering the ISBN andclicking Search Click on the appropriate link to receive instructions on downloading the encryptedfiles and decoding them
The exercises vary considerably in their degree of difficulty In each chapter the early exercises arefairly easy, while later ones are more challenging Instructors will probably want to assign onlythose exercises suited to the level of a particular class
Previous Table of Contents Next
Trang 6Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
We’ve also introduced other features from Standard C++, including new header files, the string class,new-style casts, namespaces, and so on
The design of object-oriented programs has received increasing emphasis in recent years, so we’veadded a chapter on object-oriented design
The advent of Standard C++ means that, at least to a greater extent than before, all compilers shouldtreat source code in the same way Accordingly, we’ve modified our emphasis on Borland
compilers, and now focus on code that should work with any Standard C++ compiler Of course, thereality seldom matches the ideal, so so the programs in this book have been tested with both
Microsoft and Borland compilers, and modified when necessary to work with both of them
Previous Table of Contents Next
Trang 7Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
About the Author
Robert Lafore has been writing books about computer programming since 1982 His best-selling
titles include Assembly Language Programming for the IBM PC, C Programming Using Turbo
C++ , C++ Interactive Course, and Data Structures and Algorithms in Java Mr Lafore holds
degrees in mathematics and electrical engineering, and has been active in programming since thedays of the PDP-5, when 4K of main memory was considered luxurious His interests includehiking, windsurfing, and recreational mathematics
Acknowledgments to the Third Edition
I’d like to thank the entire team at Macmillan Computer Publishing In particular, TracyDunkelberger ably spearheaded the entire project and exhibited great patience with what turned out
to be a lengthy schedule Jeff Durham handled the myriad details involved in interfacing between
me and the editors with skill and good humor Andrei Kossorouko lent his expertise in C++ toensure that I didn’t make this edition worse instead of better
Acknowledgments to the Second Edition
My thanks to the following professor—susers of this book as a text at their respective colleges anduniversities—for their help in planning the second edition: Dave Bridges, Frank Cioch, JackDavidson, Terrence Fries, Jimmie Hattemer, Jack Van Luik, Kieran Mathieson, Bill McCarty,Anita Millspaugh, Ian Moraes, Jorge Prendes, Steve Silva, and Edward Wright
I would like to thank the many readers of the first edition who wrote in with corrections andsuggestions, many of which were invaluable
At Waite Group Press, Joanne Miller has ably ridden herd on my errant scheduling and filled in asacademic liaison, and Scott Calamar, as always, has made sure that everyone knew what they weredoing Deirdre Greene provided an uncannily sharp eye as copy editor
Thanks, too, to Mike Radtke and Harry Henderson for their expert technical reviews
Special thanks to Edward Wright, of Western Oregon State College, for reviewing andexperimenting with the new exercises
Acknowledgments to the First Edition
Trang 8My primary thanks go to Mitch Waite, who poured over every inch of the manuscript withpainstaking attention to detail and made a semi-infinite number of helpful suggestions.
Bill McCarty of Azusa Pacific University reviewed the content of the manuscript and its suitabilityfor classroom use, suggested many excellent improvements, and attempted to correct my dyslexicspelling
George Leach ran all the programs, and, to our horror, found several that didn’t perform correctly incertain circumstances I trust these problems have all been fixed; if not, the fault is entirely mine
Scott Calamar of The Waite Group dealt with the myriad organizational aspects of writing andproducing this book His competence and unfailing good humor were an important ingredient in itscompletion
I would also like to thank Nan Borreson of Borland for supplying the latest releases of the software(among other useful tidbits), Harry Henderson for reviewing the exercises, Louise Orlando of TheWaite Group for ably shepherding the book through production, Merrill Peterson of MatrixProductions for coordinating the most trouble-free production run I’ve ever been involved with,Juan Vargas for the innovative design, and Frances Hasegawa for her uncanny ability to decipher
my sketches and produce beautiful and effective art
Dedication
This book is dedicated to GGL another inodomitable spirit.222
Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’d like
to see us publish in, and any other words of wisdom you’re willing to pass our way
As the Executive Editor for the Advanced Programming and Distributed Architectures team atMacmillan Computer Publishing, I welcome your comments You can fax, email, or write medirectly to let me know what you did or didn’t like about this book—as well as what we can do tomake our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your name andphone or fax number I will carefully review your comments and share them with the author andeditors who worked on the book
Fax: 317-817-7070Email: programming@mcp.com
Mail: Tracy Dunkelberger
Executive EditorAdvanced Programming and Distributed ArchitecturesMacmillan Computer Publishing
Trang 9201 West 103rd StreetIndianapolis, IN 46290 USA
Previous Table of Contents Next
Trang 10Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
APPENDIX A ASCII Chart
Table A.1 IBM Character Codes
Trang 16254 FE < Alt 254
Those key sequences consisting of “Ctrl” are typed by pressing the CTRL key, and while it is beingheld down, pressing the key indicated These sequences are based on those defined for PC PersonalComputer series keyboards The key sequences may be defined differently on other keyboards
IBM Extended ASCII characters can be displayed by pressing the Alt key and then typing thedecimal code of the character on the keypad
Previous Table of Contents Next
Trang 17Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
APPENDIX B STANDARD C++ KEYWORDS
Keywords implement specific C++ language features They cannot be used as names for variables
or other user-defined program elements Many of the keywords are common to both C and C++,while others are specific to C++ Some compilers may support additional keywords, which usuallybegin with one or two underscores, as in _cdecl or int16
A
asm auto
B
bool break
C
case catch char class const const_cast continue
D
default delete do double dynamic_cast
E
else
Trang 18enum explicit export extern
F
false float for friend
G
goto
I
if inline int
L
long
M
main mutable
N
namespace new
O
operator
P
private protected public
R
register reinterpret_cast return
Trang 19short signed sizeof static static_cast struct switch
T
template this throw true try typedef typeid typename
U
union unsigned using
V
virtual void volatile
W
wchar_t while
Previous Table of Contents Next
Trang 20Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
APPENDIX C MICROSOFT VISUAL C++
This appendix tells you how to use Microsoft Visual C++ to create console-mode applications,which are the kind of applications used in this book This discussion is based on Visual C++ version5.0
The present version of Visual C++ has good (although not perfect) adherence to Standard C++ Itcomes in various versions, including a student version for under $100
We’ll assume that Visual C++ is installed in your system, and that you know how to start it by usingthe Windows Start button and navigating to the appropriate menu item: Microsoft Visual C++.You’ll want to make sure you can see file extensions (like .CPP) when operating MVC++ InWindows Explorer, make sure that the option Hide MS-DOS File Extensions for File Types Thatare Registered is not checked
Screen Elements
When you start Microsoft Visual C++ you’ll see that the resulting application is actually calledMicrosoft Developer Studio The studio can work with other languages besides C++, but we won’tworry about that here
The Developer Studio window is initially divided into three parts On the left is the View Pane.This has three tabs, for ClassView, FileView, and InfoView Once you have a project going, theClassView tab will show you the class hierarchy of your program, and FileView will show you thefiles used in the project InfoView allows you to navigate through the documentation and help filestructure Click the plus signs to expand the hierarchies, then double-click the document you want
to read
The largest part of the screen usually holds a document window It can be used for variouspurposes, including displaying your source files It can also display the contents of help files At thebottom of the screen is a long window with more tabs: Build, Debug, and so on This will displaymessages when you perform operations such as compiling your program
Single-File Programs
It’s easy to build and execute a single-file console program using Microsoft Visual C++ There are
Trang 21It’s easy to build and execute a single-file console program using Microsoft Visual C++ There aretwo possibilities: the file already exists or the file needs to be written.
In either case you should begin by making sure that no project is currently open (We’ll discussprojects in a moment.) Click the File menu If the Close Workspace item is active (not grayed) click
it to close the current workspace
Building an Existing File
If the .CPP source file already exists, as it does for the example programs in this book, select Openfrom the File menu (Note that this is not the same as Open Workspace.) Use the Open dialog box
to navigate to the appropriate file, select it, and click the Open button The file will appear in thedocument window (If you’re compiling an example program that uses Console Graphics Lite, such
as the CIRCSTRC program in Chapter 5, “Functions,” or the CIRCLES program in Chapter 6, “Objectsand Classes,” turn to the section “Building Console Graphics Lite Programs.”)
To compile and link this file, select Build from the Build menu A dialog box will appear asking ifyou want to create a Default Project Workspace Click Yes The file will be compiled and linkedwith any necessary library files
To run the program, select Execute from the Project menu If all goes well, a console window willappear with the program’s output displayed in it
When the program terminates, you’ll see the phrase Press any key to continue The compiler
arranges for this to be inserted following the termination of any program It keeps the consoledisplay on the screen long enough to see the program’s output
You can also run programs directly from MS-DOS In Windows 95 and 98, you can obtain a boxfor MS-DOS by clicking the Start button, selecting Programs and then the MS-DOS Prompt item
In the resulting window you’ll see what’s called the C-prompt: the letter C, usually followed by the
name of the current directory You can navigate from one directory to another by typing cd (for
Change Directory) and the name of the new directory To execute a program, including any of theexamples from this book, make sure you’re in the same directory as the appropriate .EXE file, andtype the name of the program (with no extension) You can find out more about MS-DOS using theWindows help system
Writing a New File
To start writing your own .CPP file, select New from the File menu and click the Files tab Select
C++ Source File, and click OK A blank document window will appear Type in your program.Save the new file by selecting Save As from the File menu, navigating to the correct directory, andtyping the file name with the .CPP extension (such as myProg.cpp) As before, select Build from theBuild menu and click Yes to the default workspace question Your program will be compiled andlinked
If there are errors, they will appear in the Build window at the bottom of the screen (You may need
to click the Build tab to make this window appear.) If you double-click the error line, an arrow willappear next to the line containing the error in the source file Also, if you position the cursor on theerror number in the Build window (such as C2143) and press the F1 key, an explanation of the errorwill appear in the document window You can correct the errors and repeat the build process untilthe message reads “0 error(s), 0 warning(s).” To execute the program, select Execute from theBuild menu
Trang 22Before working on a new program, don’t forget to select Close Workspace from the File menu.This ensures that you begin with a clean workspace To open a program you’ve already built, selectOpen Workspace from File menu, navigate to the right directory, and double-click the file with theappropriate name and the .DSW extension.
Run-Time Type Information (RTTI)
A few programs, such as EMPL_IO.CPP in Chapter 12, “Streams and Files,” use RTTI WithMicrosoft Visual C++ you need to enable a compiler option to make this feature work SelectSettings from the Project menu and click the C/C++ tab From the Category list box, select C++
Language Click the checkbox named Enable Run-Time Type Information This will avoid variouscompiler and linker errors, some of which are misleading
Multifile Programs
We’ve shown the quick and dirty approach to building programs This approach works with file programs When projects have more than one file things become slightly more complicated
one-We’ll start by reviewing what’s meant by the terms workspace and project.
Projects and Workspaces
Visual C++ uses a concept called a workspace, which is one level of abstraction higher than a
project A workspace can contain many projects It consists of a directory and several configurationfiles Within it, each project can have its own directory, or the files for all the projects can simplyreside in the workspace directory
Conceptually it’s probably easiest, at least for the small programs in this book, to assume that everyproject has its own separate workspace That’s what we’ll assume in this discussion
A project corresponds to an application (program) that you’re developing It consists of all the filesneeded to create that application as well as information about how these files are to be combined.The result of building a project is usually a single .EXE file that a user can execute (Other resultsare possible, such as .DLL files.)
Source Files Already Exist
Let’s assume that the files you want to include in a new project already exist, and that they are in aparticular directory Select New from the File menu, and click the Projects tab in the New dialogbox Select Win32 Console Application from the list First, in the Location box, type the path to the
directory, but do not include the directory name itself Next, type the name of the directory
containing the files in the Project Name box (By clicking the button to the right of the Locationfield you can navigate to the appropriate directory, but make sure to delete the directory name itselffrom the location field.) Make sure the Create New Workspace box is checked, and click OK
For example, if the files are in C:\Book\Ch13\Elev, then you would first type C:\Book\Ch13\ in the Location field and then Elev in the Project Name field When you type the project name, it’s
automatically added to the location (If it was there already it would be added again, resulting in alocation of C:\Book\Ch13\Elev\Elev, which is not what you want.)
Trang 23At this point various project-oriented files, with extension .DSP, DSW, and so forth, have beenadded to the directory.
Now you need to add your source files to the project This includes both .CPP and .H files SelectAdd To Project from the Project menu, click Files, select the files you want to add, and click OK.You can review the files you’ve selected by clicking the FileView tab and then the plus sign for theproject You can also see the class structure, complete with member functions, by clicking theClassView tab
To open a file so you can see it and modify it, select Open from the File menu and select the file
Sometimes a file (such as the msoftCon.h file necessary for console graphics programs) is not in thesame directory as the other source files for your program You can nevertheless add it to yourproject in the same way that you add other files Select Add To Project from the Project menu,select Files, and then navigate to the file you want (or type in the complete pathname)
Saving, Closing, and Opening Projects
To save the project, select Save Workspace To close the project, select Close Workspace (AnswerYes to the query Close All Document Windows.) To open an existing project, select Open
Workspace from the file menu, navigate to the proper directory, select the .DSW file, and clickOpen
Compiling and Linking
As with one-file programs, the easiest way to compile, link, and run a multifile program is to selectExecute from the Build menu You can compile and link your project without running it by
selecting Build from the Build menu
Building Console Graphics Lite Programs
Building programs that use the Console Graphics Lite functions (described in Appendix E,
“Console Graphics Lite”) requires some steps in addition to those needed for ordinary exampleprograms Programs that use these functions should include the line #include “msoftcon.h”
• Open the source file for the program as described earlier.
• Select Build from the Build menu Answer Yes when asked if you want to create a default
project workspace A project will be created, but the compiler will complain it can’t find
MSOFTCON.H.
• To tell it where to find this file, select Options from the Tools menu Click on the
Directories tab Select Include Files from the Show Directories For list On the bottom line ofthe Directories list, type the complete pathname of the directory where MSOFTCON.H isstored (This directory should be called MSOFTCON.) Click on OK
• Now try building your file again Now the compiler can find the header file, but there will
be numerous linker errors because the linker doesn’t know where to find the code for thegraphics functions This code is in MSOFTCON.CPP.
• Select Add To Project from the Project menu; then select Files In the resulting dialog box
(called Insert Files into Project), navigate to the MSOFTCON directory Select the
MSOFTCON.CPP file Click OK
Trang 24Now your program should compile and link correctly Select Execute from the Build menu to see itrun.
Debugging
In Chapter 3, “Loops and Decisions,” we suggest using the debugger to provide an insight into howloops work Here’s how to do that with Microsoft Visual C++ These same steps can help youdebug your program if it behaves incorrectly We’ll be discussing one–file programs here, but thesame approach applies, with appropriate variations, to larger multifile programs
Start by building your program as you normally would Fix any compiler and linker errors Makesure your program listing is displayed in the Edit window
Now press the F10 key This causes the debugger to step to the next executable statement Theyellow arrow will show where you are Each press of F10 moves it to the next statement If you’re
in a loop, you’ll see the yellow arrow move down through the statements in the loop and then jumpback to the top of the loop
Watching Variables
You’ll see a Watch window in the bottom right corner of your screen To observe the values ofvariables change as you step through the program, you’ll need to place these variable’s names inthis Watch window To do this, right–click a variable name in the source code A pop–up menu willappear Select QuickWatch from this menu In the resulting QuickWatch dialog box, click AddWatch The variable and its current value will appear in the Watch window If a variable is out ofscope, such as before it’s been defined, the Watch window will show an error message instead of avalue next to the variable name
Stepping Into Functions
If your program uses functions, you can step into them (single–step through the statements within the function) by using the F11 key By contrast, the F10 key steps over function calls (treats them
as a single statement) If you use F11 to trace into library routines like cout <<, you can tracethrough the source code of the library routine This can be a lengthy process, so avoid it unlessyou’re really interested You need to switch judiciously between F11 and F10, depending onwhether you want to explore a particular function’s inner workings or not
Breakpoints
Trang 25Breakpoints allow you to stop the program at any arbitrary location Why are they useful? We’vealready shown that you can execute the program up to the cursor location by selecting Run toCursor However, there are times when you want to be able to stop the program in multiplelocations For example, you might want to stop it after an if and also after the corresponding else.Breakpoints solve this problem because you can insert as many as you need (They also haveadvanced features we won’t describe here.)
Here’s how to insert a breakpoint in your listing First, position the cursor on the line where youwant the breakpoint Then click the right mouse button, and from the resulting menu selectInsert/Remove Breakpoint You’ll see a red circle appear in the left margin Now whenever you runyour program at full speed (by selecting Build/Start Debug/Go, for example) it will stop at thebreakpoint You can then examine variables, single–step through the code, or run to anotherbreakpoint
To remove a breakpoint, right–click it and select Remove Breakpoint from the menu
There are many other features of the Debugger, but what we’ve discussed here will get you started
Previous Table of Contents Next
Trang 26Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
APPENDIX D BORLAND C++BUILDER
This appendix tells you how to use Borland C++Builder to create console-mode applications, whichare the kind of applications used in this book
C++Builder is Borland’s most advanced development product, and, as of this writing, the C++
product that adheres most closely to Standard C++ It’s available in a student version for under
$100 This discussion is based on C++Builder 3.0
We’ll assume that C++Builder is installed on your system, and that you can start it by using theWindows Start button and navigating to the appropriate menu item: C++Builder
You’ll want to make sure you can see file extensions (like CPP) when operating C++Builder InWindows Explorer, make sure that the option Hide MS-DOS File Extensions for File Types Thatare Registered is not checked
Running the Example Programs in C++Builder
The programs in this book require minor modifications to run under C++Builder Here’s a quicksummary
You can compile most of the example programs and run them without modification in Window’sMS-DOS window (Start/Programs/MS-DOS Prompt) However, if you want to run them fromwithin C++Builder, using the Run command from the Run menu, then you’ll need to install astatement at the end of the program to keep the console window on the screen long enough to see.You can do this in two steps:
• Insert the statement getch(); just before the final return statement in main() This enables you
to see the program’s output
• Insert the statement #include <conio.h> at the beginning of main() This is necessary for getch()
If you’re creating a multifile program, (as in Chapters 13, “Multifile Programs,” and 16, Oriented Design”), insert the statement #include <condefs.h> at the beginning of main()
“Object-If the program you’re building uses Console Graphics Lite functions (described in Appendix E,
“Console Graphics Lite”), you’ll need to take some additional steps These are summarized later inthis appendix
Trang 27In the balance of this appendix we’ll cover these points in more detail and describe how to use
C++Builder to edit, compile, link and execute console-mode programs
Cleaning up the Screen
When it’s first started, C++Builder shows you some screen objects you won’t need for mode programs You’ll see a window on the right called Form1 Click on its close button (the X inthe upper-right corner) to make it go away Likewise, you won’t need the Object Inspector, so clickits close button too You’ll need to get rid of these two items every time you start C++Builder.You may see a window titled Unit1.CPP with a source file in it This means C++Builder has started askeleton project for you However, it’s not the kind of project you want, so click Close All on theFile menu to get rid of it
console-You won’t need the Component Palette This is a toolbar with tabs labeled Standard, Additional,Win32, and so on To get rid of it, click the Component Palette item near the bottom of the Viewmenu This unchecks the item, so the palette will no longer be displayed (If you want it back, youcan check this item again.)
If you need additional screen space, you can also turn off the standard toolbar This toolbar containsbuttons for opening, saving, and other common tasks All these tasks can also be accessed from themenu bar, so if you don’t mind doing without the marginal convenience of the buttons, you canremove the toolbar by clicking the Toolbar item near the bottom of the View menu
Creating a New Project
C++Builder (as do other modern compilers) thinks in terms of projects when creating programs A
project consists of one or more source files It can also contain many other kinds of files which wedon’t need to be concerned with here, such as resource files and definition files The result of aproject is usually a single EXE file that a user can execute
To begin a new project, select New from the File menu You’ll see a dialog box called NewItems Click the New tab (if necessary) Then double-click the Console Wizard icon In theresulting dialog box, make sure that the Window Type is Console and the Execution Type is EXE
Click Finish and you’ll see the following source file appear in the Project Source window:
#pragma hdrstop
#include <condefs.h>
// -#pragma argsused int main(int argc, char **argv) {
return 0;
}
This is a skeleton version of a console-mode program You don’t need some of the lines in thisprogram, and you will need to add some others We’ll make these changes, and add a statement toprint some text so you can see if the program works Here’s the result:
Trang 28//test1.cpp //#include <condefs.h> //not needed for one-file programs
#include <iostream>
#include <conio.h>
//#pragma hdrstop //not needed // - //#pragma argsused //not needed
//int main(int argc, char **argv) //arguments not needed int main()
{ cout << “Happy are they whose programs ” << “compile the first time.”;
header file, so you’ll need to include it at the beginning of your program
If you’re creating your own program, you can start with the skeleton program and type in your ownlines If your starting with an existing file, read the section “Starting with Existing Files.”
Saving A Project
The text you see in the Project Source window is a source file, which has the extension CPP
C++Builder (as do other modern compilers) thinks in terms of a project, which can consist of(potentially) many such source files Information about a project is recorded in a file with theextension BPR Thus when you save a project, you’re actually saving both the CPP file (or files)and the BPR file When you first create it, the project is called Project1 (or a higher number)
To save the project and change its name, select Save Project As from the File menu, navigate to thedirectory where you want to store the file, type the name you want to give the project, followed bythe BPR extension, and click OK
Starting with Existing Files
You may be starting a project with files that already exist, such as the ones in this book If so,you’ll need a little trick You want the main file in your project, that is, the one containing main()
have the same name as the project However, C++Builder will automatically create a file with thisname, the skeleton file It will then try to override your file with the skeleton file when you try tosave the project
Here’s how to avoid the problem Suppose your project is called myProj, and your main file is
myProj.cpp Implement the following steps:
Trang 29• Temporarily rename your main file (myProj.cpp) to a name other than the project name, say
XmyProj.cpp
• Use Save Project As to save your project Give the project the same name as the original
file, but with the BPR extension: myProj.BPR Click Save The skeleton file that was created,
myProj.cpp, will be saved as well
• Close the project with Close All.
• Delete the skeleton file (myProj.cpp)
• Rename your source file (XmyProj.cpp) to the same name as the project (myProj.cpp)
Now when you open the project again (using Open Project from the File menu), your source filewill be the project’s source file as well You can then modify it or compile it
Compiling, Linking, and Executing
To build an executable program, select Make or Build from the Project menu This causes your file to be compiled into an OBJ file, and the OBJ file to be linked (with various library files) into an.EXE file For example, if you’re compiling MYPROG.CPP, the result will be MYPROG.EXE If thereare compiler or linker errors, they will be displayed Edit your program until you’ve eliminatedthem
Executing from C++Builder
If you’ve modified your program by inserting getch() as described earlier, then you can compile,link, and run your program directly in C++Builder by simply selecting Run from the Run menu Ifthere are no errors, the console window will appear, along with the output of the program
Executing from MS-DOS
You can also run programs directly from MS-DOS In Windows 95 and Windows 98, you canobtain a box for MS-DOS by clicking the Start button, selecting Programs and then the MS-DOS
Prompt item In the resulting window you’ll see what’s called the C-prompt: the letter C, usually
followed by the name of the current directory You can navigate from one directory to another by
typing cd (for Change Directory) and the name of the new directory To execute a program,
including any of the examples from this book, make sure you’re in the same directory as theappropriate EXE file, and type the name of the program (with no extension) You can find out moreabout MS-DOS using the Windows help system
Precompiled Header Files
You can speed up compilation times dramatically by selecting Options from the Project menu,selecting the Compiler tab, and clicking on Use Precompiled Headers In a short program most ofthe compile time is spent compiling the C++ header files such as iostream Using the PrecompiledHeaders option causes these header files to be compiled only once, instead of each time youcompile your program
Closing and Opening Projects
Trang 30When you’re done with a project, you can close it by selecting Close All from the File menu Toopen a previously-saved project, select Open Project from the File menu, navigate to the
appropriate .BPR file, and double-click it
Adding a Header File to Your Project
Most C++ programs employ one more user-written header file (in addition to many library headerfiles, like IOSTREAM and CONIO.H) Here’s how to create a header file
Creating a New Header File
Select New from the File menu, make sure the New tab is selected, and double-click the Texticon You’ll see a source window titled FILE1.TXT Type in the text of your file and save it usingSave As on the File menu, with an appropriate name, followed by the H file extension Save it inthe same file as your source (.CPP) files The new filename will appear on a tab next to the otherfiles in the project You can switch from file to file by clicking the tabs
Editing an Existing Header File
To open an existing header file, select Open from the File menu, and select Any File (*.*) from theFiles Of Type list You can then select the header file from the list
When you write the include statement for the header file in your .CPP file, make sure you enclosethe filename in quotes:
#include “myHeader.h”
The quotes tell the compiler to look for the header file in the same directory as your source files
Telling C++Builder the Header File’s Location
If you add a .H file, the compiler must know where to find it If it’s in the same directory as yourother files, then you don’t need to do anything
However, if your H file is in a different directory, you’ll need to tell C++Builder where to find it.(This is true of the borlaCon.h file necessary for console-mode graphics.) Go to Options on theProject menu and select the Directories/Conditionals tab In the Directories section, click the buttonwith the three dots on the right of the Include Path list A Directories dialog box will appear
In the bottom field of the Directories dialog box, type the complete pathname of the directory wherethe .H file is located Click the Add button to place the path in the list of include paths Then click
OK twice more to close the dialog boxes
Don’t try to add header files to the project with the Add To Project option in the Project menu
Projects with Multiple Source Files
Real applications, and some of the example programs in this book, require multiple source (.CPP)files Incidentally, in C++Builder, source files are often called units, a term specific to this product.
Trang 31files Incidentally, in C++Builder, source files are often called units, a term specific to this product.
In most C++ development environments, files are called files or modules.
If you use more than one source file in your project, you’ll need to include the file CONDEFS.H:
#include <condefs.h> //necessary for multifile programs
in the main source file; that is, the one containing main() This is not necessary for one-fileprograms, as we mentioned earlier, but is essential for multifile programs
Creating Additional Source Files
You make additional CPP files the same way you make header files: Select File/New, and click the Text Icon in the New dialog box Type in the source code, and use Save As to save thefile When using Save As, make sure to select C++Builder Unit (.CPP) from the Save File As Typelist This will automatically supply the CPP extension, so all you need to type is the name If youfail to do this, and simply type the CPP after the name, the file won’t be recognized as a C++Builderunit
double-Adding Additional Source Files to your Project
You may have created a new additional source file as just described, or one may already exist, such
as BORLACON.CPP, which is used for Console Graphics Lite programs To add a source file to theproject, select Add To Project from the Project menu, navigate to the appropriate directory, andselect the filename from the list Then click Open That tells C++Builder it’s part of the project.Multiple source files are displayed with tabs in the edit window (if they’re in full-size windows), soyou can quickly switch from one file to another You can open and close these files individually sothey don’t all need to be on the screen at the same time
The Project Manager
You can see what source files are part of the project by selecting Project Manager from the Viewmenu You’ll see a diagram of file relationships, similar to that shown in the Windows Explorer.Clicking the plus sign next to the project icon will display all the project’s source files The file youjust added to the project should be among them
If you right-click a file in the Project Manager the context menu will show you choices that includeOpen, Save, Save As, and Compile This is a handy way to perform these tasks on individual sourcefiles
In a multifile program you can compile individual files separately by selecting Compile Unit fromthe Project menu You can compile and link all the source files by selecting Make from the Projectmenu This will cause only those source files that have been changed since the previous compile to
be recompiled
Weird New Lines in Your Program
When you compile a multifile program, C++Builder automatically inserts lines into the source code
of your primary source file These lines specify what the other source files are For example, if youhad a two-file program consisting of FILE1.CPP and FILE2.CPP, you might see the following in
Trang 32USEUNIT(“file2.cpp”);
// -This is a permanent change to your source file It’s not a very elegant approach to compilingmultifile programs, but at least you don’t have to add these lines yourself
Console Graphics Lite Programs
Here’s how to build programs that use the Console Graphics Lite package This includes suchprograms as CIRCSTRC from Chapter 5, “Functions,” and CIRCLES in Chapter 6, “Objects andClasses.”
• Create a new project as described earlier, using the program name as the project name, but
with the BPR extension
• In the source file, change #include<msoftcon.h> to #include<borlacon.h>
• Tell the compiler where this MSOFTCON.H header file is by following the instructions in thesection earlier in this Appendix titled “Telling C++Builder the Header File’s Location.” (Theheader should be in a directory called BORLACON.)
• Add the source file BORLACON.CPP to your project by following the instructions in thesection earlier in this Appendix titled “Adding Additional Source Files to your Project.”
• Insert the line #include <condefs.h> at the beginning of your program This is necessary formultifile programs
• To keep the display on the screen, insert the line getch(); just before the return statement atthe end of main()
• To support getch(), insert the line #include <conio.h> at the beginning of your program
Debugging
In Chapter 3, “Loops and Decisions,” we suggest using a debugger to provide an insight into howloops work Here’s how to do that with Visual C++ These same steps can help you debug yourprogram if it behaves incorrectly We’ll be discussing one-file programs here, but the sameapproach applies, with appropriate variations, to large multifile programs
Start by building your program as you normally would Fix any compiler and linker errors Makesure your program listing is displayed in the Edit window
Single Stepping
To start the debugger, just press the F8 key The program will be recompiled, and the first line inthe program, usually the main() declarator, will be highlighted Repeated presses of F8 will causecontrol to move to each statement of the program in turn When you enter a loop, you’ll seehighlight move down through the loop, then return to the top of the loop for the next cycle
Watching Variables
Trang 33To see how the values of variables change as you single step through the program, select AddWatch from the Run menu The Watch Properties dialog box will appear Type the name of thevariable you want to watch into the Expression field of this dialog box, and click OK A windowcalled Watch List will appear By repeatedly using the Add Watch dialog box you can add as manyvariables as you want to the Watch List.
If you position the Edit Window and the Watch List so you can see them both at the same time, youcan watch the value of the variables change as you single step through the program If a variable isout of scope, such as before it’s been defined, the Watch List will show an error message instead of
a value next to the variable name
In the particular case of the CUBELIST program, the watch mechanism doesn’t recognize the validity
of the cube variable when it’s defined within the loop Rewrite the program so it’s defined before theloop; then its value will be displayed properly on the Watch List
Tracing Into Functions
If your program uses functions, you can trace into them (single-step through the statements within the function) by using the F7 key The F8 key steps over function calls (treats them as a single
statement) If you use F7 to trace into library routines like cout <<, you can trace through the sourcecode of the library routine This can be a lengthy process, so avoid it unless you’re really interested.You will need to switch judiciously between F7 and F8, depending on whether or not you want toexplore a particular function’s inner workings
Breakpoints
Breakpoints allow you to stop the program at any arbitrary location Why are they useful? We’vealready shown that you can execute the program up to the cursor location by selecting Run toCursor from the Run menu However, there are times when you want to be able to stop the program
in multiple locations For example, you might want to stop it after an if and also after thecorresponding else Breakpoints solve this problem because you can insert as many as you need.(They also have advanced features we won’t describe here.)
Inserting a breakpoint in your listing is easy Look at your program listing in the edit window.You’ll see a dot in the left margin opposite each executable program line Simply left-click the dotwhere you want to insert the breakpoint You’ll see a red circle appear in the left margin, and theprogram line will be highlighted Now whenever you run your program at full speed (by selectingRun from the Run menu, for example) it will stop at the breakpoint You can then examine
variables, single-step through the code, or run to another breakpoint
To remove the breakpoint, left-click it again It will vanish
There are many other features of the Debugger, but what we’ve described here will get you started
Previous Table of Contents Next
Trang 34Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore ISBN: 157169160x Publication Date: 11/25/98
Previous Table of Contents Next
APPENDIX E CONSOLE GRAPHICS LITE
It’s nice to be able to enliven example programs with graphics, so we’ve included many based examples ANSI Standard C++ does not include graphics specifications, but it certainlydoesn’t prohibit graphics, and Windows supports various kinds of graphics
graphics-Previous editions of this book were based on Borland C++, and used Borland graphics functions inmany examples In this edition, in keeping with making the book compliant with ANSI C++, we’veattempted to make the examples less compiler-specific However, every compiler handles graphicsdifferently, so we’ve used two approaches to graphics, one for Microsoft Visual C++ and one forBorland C++ (It’s possible the approach used for the Microsoft compiler will work with othercompilers as well.)
In this edition we use console graphics The console is a character-mode screen, typically arrangedwith 80 columns and 25 rows Most of the non-graphics example programs in this book write text
to the console window A console program can run in its own window within Windows, or as astandalone MS-DOS program
In console graphics, rectangles, circles, and so forth are made up of characters (such as the letter
‘X’ or a small character-size block) rather than pixels The results are crude but work fine asdemonstration programs
The example programs use calls to a set of “generic” console functions created specifically for thisbook, which we call Console Graphics Lite These functions translate function calls in the exampleprograms into different actual functions, depending on which of two files is compiled and linked toyour project These files are MSOFTCON.CPP for Microsoft compilers, and BORLACON.CPP forBorland compilers
In previous editions, some programs used pixel graphics (“real” graphics, in which individualscreen pixels are manipulated) rather than character graphics Unfortunately, it’s no longer practical
to accommodate pixel graphics Microsoft’s compilers have eliminated their support for pixelgraphics, unless you want to write a full-scale Windows program, with all the complexity that thatinvolves So all the graphics examples in this edition use console-mode graphics
Using the Console Graphics Routines
Trang 35To build an example program that uses graphics, you must add several steps to the normal buildprocedure These are as follows:
• Include the appropriate header file (MSOFTCON.H or BORLACON.H) in your source code andadd it to your project if necessary
• Add the appropriate source file (MSOFTCON.CPP or BORLACON.CPP) to your project
• Make sure the compiler can find the appropriate header file and source file.
The header files contain declarations for the Console Graphics Lite functions The source filescontain the definitions (source code) for these functions You need to compile the appropriatesource file and link the resulting .OBJ file with the rest of your program This happens automaticallyduring the build process if you add the source file to your project
To learn how to add a file to your project, read either Appendix C, “Microsoft Visual C++,” orAppendix D, “Borland C++Builder.” Then apply this process to the appropriate source file
MSOFTCON.CPP is located in the MSOFTCON directory, and BORLACON.CPP is in the BORLACON
directory on the CD that accompanies this book
To make sure your compiler can find the header file, you may need to add the pathname where it’slocated to the Directories option for your compiler Again, refer to the appropriate appendix to seehow this is done
The Console Graphics Functions
The Console Graphics Lite functions assume a console screen with 80 columns and 25 rows Theupper-left corner is defined as the point (1,1) and the lower-right corner is the point (80,25)
These functions were designed specifically for the example programs in this book and are notparticularly robust or sophisticated If you use them in your own programs you should be careful todraw all shapes entirely within the confines of the 80-by-25 character screen If you use invalidcoordinates, their behavior is undefined Table E.1 lists these functions
Table E.1 Functions for Console Graphics Lite
init_graphics() Initializes graphics system
set_color() Sets background and foreground colors
set_cursor_pos() Puts cursor at specific row and column
clear_screen() Clears entire console screen
wait(n) Pauses program for n milliseconds
clear_line() Clears entire line
draw_rectangle() Specify top, left, bottom, right
draw_circle() Specify center (x, y) and radius
draw_line() Specify end points (x1, y1) and (x2, y2)
draw_pyramid() Specify top (x, y) and height
set_fill_style() Specifies fill characterYou must call init_graphics() before you use any other graphics functions This function sets the fillcharacter, and in the Microsoft version it also initializes other essential parts of the console graphicssystem
Trang 36The set_color() function can use either one or two arguments The first sets the foreground color ofcharacters displayed subsequently, and the second (if present) sets the background color of thecharacter Usually you want to keep the background black.
set_color(cRED); //sets foreground to red set_color(cWHITE, cBLUE); //foreground white, background blue
Table E.2 shows the color constants that can be used for either foreground or background
Table E.2 Color Constants for set_color()
cBLACK cDARK_BLUE cDARK_GREEN cDARK_CYAN cDARK_RED cDARK_MAGENTA cBROWN
cLIGHT_GRAY cDARK_GRAY cBLUE
cGREEN cCYAN cRED cMAGENTA cYELLOW cWHITE
The functions beginning with draw_ create shapes or lines using a special character called the fill
character This character is set to a solid block by default, but can be modified using the
set_fill_style() function Besides the solid block, you can use uppercase ‘X’ or ‘O’ characters, or one
of three shaded block characters Table E.3 lists the fill constants:
Table E.3 Fill Constants for set_fill_style()
SOLID_FILL X_FILL O_FILL LIGHT_FILL MEDIUM_FILL DARK_FILL
The wait() function takes an argument in milliseconds, and pauses for that amount of time
wait(3000); //pauses for 3 seconds
The other functions are largely self-explanatory Their operation can be seen in those examples thatuse graphics
Implementations of the Console Graphics Lite functions
These routines used for Console Graphics Lite aren’t object-oriented, and could have been written
in C instead of C++ Thus there’s no real reason to study them, unless you’re interested in a
Trang 37quick-in C quick-instead of C++ Thus there’s no real reason to study them, unless you’re interested in a and-dirty approach to graphics operations like drawing lines and circles The idea was to create theminimum routines that would do the job You can examine the source files if you’re curious.
You might wonder why you can’t use the Borland compiler to access the console functions builtinto Windows The problem is that to create a console-mode program in Borland C++, you must useeither an EasyWin or a DOS target, both of which are 16-bit systems The Windows console
functions are 32-bit functions, and so can’t be used in Borland’s console mode
When you use Borland C++, the iostream approach to I/O (cout <<) doesn’t produce different colors.Thus some of the example programs, like HORSE.CPP, won’t show up in color in the Borlandversion If you want different colors, you’ll need to revert to console-mode functions like cputs() and
putch(), found in the CONIO.H file
Previous Table of Contents Next
Trang 38Table F.1 Algorithms
Non-mutating Sequence Operations
for_each Applies ‘function’ to each
object
first, last, function
find Returns iterator to first
object equal to ‘value’
first, last, value
find_if Returns iterator to first
object for which ‘predicate’
is true
first, last, predicate
adjacent_find Returns iterator to first
adjacent pair of objectsthat are equal
first, last
adjacent_find Returns iterator to first
adjacent pair of objectsthat satisfy ‘predicate’
first, last, predicate
count Adds to ‘n’ the number of
objects equal to ‘value’
first, last, value, n
count_if Adds to ‘n’ the number of
objects satisfying
‘predicate’
first, last, predicate, n
mismatch Returns first non-equal
pair of correspondingobjects intwo ranges
first1, last1, first2
mismatch Returns first pair of
corresponding objects intwo ranges that don’tsatisfy ‘predicate’
first1, last1, first2,
predicate
corresponding objects intwo ranges are all equal
first1, last1, first2
corresponding objects intwo ranges all satisfy
‘predicate’
first1, last1, first2, predicate
search Checks if second range is
contained within the first
Returns start of match, or
last1 if no match
first1, last1, first2, last2
search Checks if second range is
contained within the first,where equality is
determined by ‘predicate’.Returns startof match, or
last1 if no match
first1, last1, first2, last2, predicate
Mutating Sequence Operations
copy Copies objects from range
1 to range 2
first1, last1, first2
Trang 39copy_backward Copies objects from range
1 to range 2, insertingthem backwards, fromlast2 to first2
first1, last1, first2
iter_swap Interchanges objects
pointed to by twoiterators
iter1, iter2
swap_ranges Interchanges
corresponding elements intwo ranges
first1, last1, first2
transform Transforms objects in
range 1 into new objects
in range 2 by applying
‘operator’
first1, last1, first2, operator
transform Combines objects in range
1 and range 2 into newobjects in range 3 byapplying ‘operator’
first1, last1, first2, first3, operator
replace Replaces all objects equal
to ‘old’ with objects equal
to ‘new’
first, last, old, new
replace_if Replaces all objects that
satisfy ‘predicate’ withobjects equal to ‘new’
first, last, predicate, new
replace_copy Copies from range 1 to
range 2, replacing allobjects equal to ‘old’ withobjects equal to ‘new’
first1, last1, first2, old, new
replace_copy_if Copies from range 1 to
range 2, replacing allobjects that satisfy
‘predicate’ with objectsequal to ‘new’
first1, last1, first2, predicate, new
fill Assigns ‘value’ to all
objects in range
first, last, value
fill_n Assigns ‘value’ to all
objects from first to first+n
first,n, value
generate Fills range with values
generated by successivecalls to function ‘gen’
first, last, gen
generate_n Fills from first to first+n
with values generated bysuccessive calls tofunction ‘gen’
first, n, gen
objects equal to ‘value’
first, last, value remove_if Removes from range any first, last, predicate
Trang 40Removes from range anyobjects that satisfy
‘predicate’
remove_copy Copies objects, excepting
those equal to ‘value’, fromrange 1 to range 2
first1, last1, first2, value
remove_copy_if Copies objects, excepting
those satisfying ‘pred’,from range 1 to range 2
first1, last1, first2, pred
unique Eliminates all but the first
object from anyconsecutive sequence ofequal objects
first, last
unique Eliminates all but the first
object from anyconsecutive sequence ofobjects satisfying
‘predicate’
first, last, predicate
unique_copy Copies objects from range
1 to range 2, except onlythe first object from anyconsecutive sequence ofequal objects is copied
first1, last1, first2
unique_copy Copies objects from range
1 to range 2, except onlythe first object from anyconsecutive sequence ofobjects satisfying
reverse_copy Copies range 1 to range 2,
reversing the sequence ofobjects
first1, last1, first2
objects around iterator
‘middle’
first, last, middle
rotate_copy Copies objects from range
1 to range 2, rotating thesequence around iterator
random_shuffle Randomly shuffles objects
in range, using number function ‘rand’
random-first, last, rand
partition Moves all objects that
satisfy ‘predicate’ so theyprecede those that do notsatisfy it
first, last, predicate