Programming Principles and Practice Using C++

This book is for someone who has never programmed before but is willing to work hard to learn. It helps you understand the principles and acquire the practical skills of programming using the C++ programming language.


Bjarne Stroustrup


1268 Pages

128054 Reads

27 Downloads

English

PDF Format

150 MB

C, C++ Programming

Download PDF format


  • Bjarne Stroustrup    
  • 1268 Pages   
  • 03 Mar 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    Programming read more..

  • Page - 4

    read more..

  • Page - 5

    I .t . r-. Programming Prin cipl es and Practi ce Using C++ Bjarne Stroustrup .'. Addison-Wes ley Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • london • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City read more..

  • Page - 6

    ~Ia.ny of the desigll3tions used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where t11O$C design'llions app:ar in this book, and tIu:: publisher was aware of 3 tT"Jdcmark claim. the designations h,l\'e been primed with initial capitalleu",rs or in all capitals. A complete list o f photo sources and credits appears on pages 1235- read more..

  • Page - 7

    Preface xxiii Chapter 0 Noles to the Reader 0. 1 111C structure o f lhis book 2 0.1. 1 Gcncntl approach 3 0. 1.2 Drills, exercises, etc. 4 0. 1.3 What comes after this book? 5 Contents 0.2 A philosophy of teaching and learning 6 0.2. 1 lllC: order of topics 9 0.2.2 Programming and programming language 10 0.2.3 Portability I I 0.3 Programming and computer science read more..

  • Page - 8

    Chapter 1 Computers, People, and Programmi ng 17 1.1 Introduction 18 1.2 Software 19 1.3 People 2 1 1.4 Computer science 24 1.5 Computers are evel)"vhere 25 1.5.1 Screens and no screens 26 1.5.2 Shipping 26 1.5.3 l 'i::lecommunications 28 1.5.4 Medicine 30 1.5.5 lnfonnation 31 1.5.6 A "crtical view 32 1.5.7 So what? 34 1.6 Ideals for programmers 34 Part I The read more..

  • Page - 9

    CONTENTS 4.3 Expressio ns 94 4.3.1 Constan t expressions 95 4.3.2 Operators 96 4.3.3 Conversions 98 4.4 Statements 99 4.4 .1 Selection 10 1 4.4.2 Iteration 108 4.5 Functions 112 4.5.1 Why bother wilh functions? 114 4.5.2 Function declarations 115 4.6 Vcclor 116 4.6.1 Growing a vector 11 8 4.6.2 A numeric example 119 4.6.3 A text example 121 4.7 Language features 123 read more..

  • Page - 10

    viii Chapter 6 Writing a Program 171 6.1 A problem 172 6.2 111inking abo ut the pro blem 173 6.2. 1 Stages of dcvelopmcnt 174 6.2.2 Slralcgy 174 6 .3 Back to the ca1culaLOr! 176 6.3. 1 Firs t atte mpt 177 6.3.2 Tokens 179 6.3.3 Implementing tokcns 181 6.3.4 Using tokens 183 6.3.5 Back to the drawing board ) 8S 6.4 Granuna rs 186 6.4. 1 A de tour: English read more..

  • Page - 11

    CONTENTS he Chapter 8 Technicalities: Functions, etc. 253 8.1 Technicalities 254 8.2 Declarations and definjtions 255 8.2.1 Kinds of declarations 259 8.2.2 Variable and constant declarations 260 8.2.3 Default initialization 26 1 8.3 Header files 26 1 8.4 Scope 264 8.5 Function call and return 269 8.5.1 Declaring arguments and return type 270 8.5.2 Reluming a value 27 1 8.5.3 read more..

  • Page - 12

    " CONTEN TS Part II Input and Output 337 Chapter 10 Input and Output Streams 339 10.1 Input and output 340 10.2 TIle 110 stream model 341 10.3 Ftles 343 10.4 Opening a me 344 10.5 Reading and writing a me 346 10.6 1/0 error handling 348 10.7 Reading a single value 352 10.7. 1 B~aking the problem into manageable parts 353 10.7.2 Separating dialog from fu read more..

  • Page - 13

    CONTENT S Chapter 13 Chapter 14 12.4 UsingaGU Ilibrary 4 14 12.5 Coordinales 4 15 12.6 Shapes 4 16 12.7 Using Shape primitives 417 12.7.1 Graphics headers and main 417 12.7.2 An almost blank window 418 12.7.3 Axis 420 12.7.4 Graphing a function 422 12.7.5 Polygons 423 12.7.6 Rectangles 424 12.7.7 Ell 427 12.7.8 Text 427 12.7.9 Images 429 12.7. 10 And much more 430 read more..

  • Page - 14

    xii Chapte r 15 14.2 Shape 485 14 .2.1 An absmlct class 487 14.2.2 Access co ntrol 488 14.2.3 Drawing shapes 491 14.2.4 Copying and mutability 494 14.3 Base and deri ved classes 496 14 .3. 1 Objcct layout 497 CONTEN TS 14 .3.2 Deriving classes and defining virtual functiollS 499 14.3.3 Ove rriding 500 14.3.4 Access 501 14.3.5 Pure vinual funcuons 502 14.4 Benefits of read more..

  • Page - 15

    CONTENTS xiii Part lit Data and Algorithms 567 C hapte r 17 Vec tor and Free Store 5 69 17.1 Introductio n 570 17.2 ve ctor basics 572 17.3 Memory, add resses, and poimers 574 17.3.1 111C sizeof operator 576 17.4 Free store and pointe rs 577 17.4.1 Free-store allocation 578 17.4.2 Access throu gh pointers 579 17.4.3 Ranges 580 17.4.4 Initialization 582 17.4.5 TIle read more..

  • Page - 16

    xiv CONTENTS 18.5 Array, 627 18.5.1 Pointers to array clements 628 18.5.2 Pointers an d arrays 631 18.5.3 Array initialization 633 18.5.4 Pointer problems 634 18.6 Examples: palindrome 637 18.6.1 Palindro mes using Siring 637 18.6.2 Palindromes using arrays 638 18.6.3 Palindromes using pointers 640 Chapter 19 Vector, Templates, and Exceptions 645 19.1 1ne problems 646 19.2 Changing read more..

  • Page - 17

    CONTENTS xv 20.3 Sequences and ilerators 694 20.3.1 Back to the example 696 20.4 Linked lists 698 20.4.1 List operations 699 20.4.2 Iteration 70 1 20.5 Generalizing vector yet agai n 703 20.6 An example : a simple text editor 704 20.6. 1 Lines 707 20.7 20.8 20.9 20. 10 20.6.2 Itera tion 708 vector, list, a nd string 71 1 20.7. 1 inse rt and erase 713 Adapting read more..

  • Page - 18

    xvi CONTENTS Part IV Broadening the View 769 C hapte r 22 Ideals a nd H istory 77 1 22. 1 History, ideals, and prorcssionalism 772 22.1.1 Programmi.ng language ai.ms and philosophies 772 22.1.2 Progr.lIlll11ing ideals 774 22. 1.3 Styles/paradigms 78 1 22.2 Programming language history overview 783 22 .2.1 TIle earl iest languages 784 22.2.2 TIle roots of modem languages 786 read more..

  • Page - 19

    CONTENTS 24.5 Thc Matrix library 861 24.6 24.7 24.8 24.9 24. 10 24.5.1 Dimensions and access 862 24.5.2 ID Matrix 865 24.5.3 2D Matrix 868 24.5.4 Matrix 110 870 24.5.5 3D Matrix 871 An example: solving linear equations 872 24.6. 1 Classical Gaussian elimination 874 24.6.2 Pivoting 875 24.6.3 Testing 876 Rando m numbers 877 The standard mathcmaticaJ functions 879 Complex read more..

  • Page - 20

    xviii Chapter 26 Testing 949 26.1 What we wam 950 26. 1. 1 Caveat 95 1 26.2 Proofs 952 26.3 Testing 952 26.3.1 Regression tests 953 26.3.2 Unit tests 954 26.3 .3 Algo rithms and non·algorithms 961 26.3 .4 System tests 969 26.3.5 Testing classes 973 C ONTENTS 26.3.6 Finding as~umptions that do not hold 976 26.4 Design for testing 978 26.5 Debuggin g 979 26.6 read more..

  • Page - 21

    CONTENTS 27.6 Input/output: stdio 10 16 27.6.1 Output 1016 27.6.2 Input 1017 27.6.3 rues 1019 27.7 Constants and macros 1020 27.8 Macros 1021 27.8. 1 Function·likc macros 1022 27.8.2 Syntax macros 1023 27.8.3 Conditional compilation 1024 27.9 An example: intrusive containers 1025 Part V Appendi ces '035 Appendix A Language Su mmary 1037 Al General 1038 A.l.l Tcnninology 1039 read more..

  • Page - 22

    xx CONTENTS AS Built-in types 1062 A.8. 1 Pointers 1063 A.8.2 Arrays 1064 A.8.3 RefefCnces 1065 A.9 Functions 1066 A.9.1 Overload resolution 1067 A.9.2 Default arguments 1068 A.9.3 Unspecified arguments 1068 A.9.4 Linkage specifications 1069 AIO User·defmed types 1069 A. IO.I Operator overloading 1069 All Enumerations 1070 A 12 Classes 1071 A.12. 1 Member access 107 1 A.12.2 read more..

  • Page - 23

    CONTENTS B.4 Containers 1105 8.1.1 Overview 1107 B.4.2 Member types 1 !OS B.4.3 ConstTIlctors, destructors, and assignmcnts 11 OS B.4.4 Itcrators 1109 8.4.5 Element access 1109 8.4.6 Stack and queue operations 1110 8.4.7 List operations 1110 8.4.S Size and capacity 111 0 8.4.9 Other operations 1111 8.4.10 Associative container operations 1111 B.5 Algorithms 111 2 B.5. 1 Nonmodifying read more..

  • Page - 24

    uii RIO C standard library fu nctions 1140 B.lO.1 Fiies 1140 B.10.2 -nle prinlf() family 1141 B.10.3 Cstyle strings 11 45 B.I O.4 Memory 1146 B. IO.5 Date and time 1147 B.IO.6 Etc. 1149 B. II Other libraries 11 50 Appendix C Getting Started with Visual Stud io 1151 C. I Getting a program to run 11 52 C.2 Ins talling Visual Studio 1152 C.3 Creating and ru nning read more..

  • Page - 25

    Preface "Damn the torpedoes ! Full speed ahead." -Admiral Farrag ut Programming is the an of expressing solutions to problems so that a computer C;1.Il execute lhose solutions. Much of the effon in progranuning is spem fi nding and refining solutions. Often, a problem is only full y understood through the process of programming a solution for it. 111i5 book is for read more..

  • Page - 26

    u iv PREFA C E Why would you wam to program? Our civilization runs on software. With- out understanding software you are reduced to believing in "magic" and will be locked alit of many of tile most interesting, pro fitable , and socially usefu l techni- cal fie lds o f work. When I talk about programming, I think of the whole spec- trum of computer programs read more..

  • Page - 27

    PR EFACE ming as well as its value. I would hate for you lO acquire a dislike fo r program- ming because of a mismatch between what you need and the part of the software reality I describe. There arc many parts of the "information technology" world that do not require knowledge of programming. 111is book is aimed to serve those who do wallt to write or read more..

  • Page - 28

    xxvi PREFACE A note to students Of the 1000+ fIrst-year studcnts we havc taught so far using drafts of this book at Tcxas A&M Univcrsity, about 60% had programmcd bcfore and about 40% had ncver seen a linc of code in their lives . Most succcedcd , so you can do it, too. VOli don't have to read this book as part o f a course. r assume that the book read more..

  • Page - 29

    PREFACE chines, discrete math, C homsky grammars, etc.). Even hardware is ignored on the assumption that students have used computers in various ways since kinder- garten. This book docs not even try to mention most importam CS topics. It is a bout programming (or more generally about how to develop software), and as such it goes into more detail about fewer topics than read more..

  • Page - 30

    )(Xviii PREFACE Thanks to the students, teaching assistants, and peer teachers o f ENGR 11 2 at Texas A&M University who directly and indirectly helped us conSlnlct this book, and to Walter Daughe rity, who has also taught the cou rse. Also thanks to Damian Dcchev, Tracy Hammond , Ame Tolstrup Madsen, Gabriel Dos Reis, Nicholas Strousmlp,j . C. van 'Winkel, Greg read more..

  • Page - 31

    •• _1-. ,-- 0 Notes to the Reader "When the terrain disagrees with the map, trust the terrain." -Swiss army proverb T his chapter is a grab bag of information; it aims to give you an idea of what to expect from the rest of the book. Please skim through it and read what you fin d illlcresling. A teacher will find most parts inuncdiatcly usefuL If you read more..

  • Page - 32

    2 0.1 The structure of this book 0.1.1 Ge neral approach 0.1.2 Drills, exercises, etc. 0.1.3 What comes afle r th is bookl 0.2 A philosophy of leaching and learning 0.2.1 Th e orde r of topics 0.2.2 Prog rammin g and prog ra mming language 0.2.3 Portability C HAPTER 0 • NOTE S TO THE READER 0.3 Programming and computer science 0.4 Creativit y and problem read more..

  • Page - 33

    0.1 TH E ST RUC TURE OF THIS BOOK Unfortunately, the world of programming doesn' t really fall into four cleanly sep- arated parts. ~nlercfore, the "parts" of this book provide only a coarse classi fica- tion of topics. \'Ve consider it a useful classifi cation (obviously, or we wouldn 't have used it), but reality has a way of escaping neat classifications. For read more..

  • Page - 34

    4 CHAPTER 0 • NOTES TO THE READER worked on a few exercises, yo u'll often [md that you have to go back to reread a few sections and that several days have gOlle by. We have clustered the chapters imo "parts" focused on a major lopic. such as input/ampul. These parts make good units of review. Common praise for a textbook is " It answered all my read more..

  • Page - 35

    0.1 THE STRUCTU RE Of THIS BOOK Exercise;: Some exercises arc trivial and others are very hard, bUl most are intended to leave some scope for initiative and imagination. If you arc serious, you'll do quite a few exercises. At least do enough to k.now which arc difficult for you. Then do a few more of those. TIlat's how you 'Jlleam the most. Tbe exercises are meant read more..

  • Page - 36

    • C HAPTER 0 • NOTES TO THE READER should hope for, and what you can expect if yo u approach this book seriously. is to have a really good start that allows you to \vntc relatively simple useful pro- grams, to be able to read more complex programs, and to have a good concep- tual and practical background for further work. TIle best follow-up to this initial read more..

  • Page - 37

    0.2 A PHILO SOPHY OF TEACH ING AND LEARNING lvVorking our way through these topics, we cover the programming techniques called proceduraJ programming (as with the C programming language), data ab- slraction, object-orientcd programming, and generic prob'Tamming. The main topic of this book is jJrogralllwillg, that is, the ideals, techniques, and tools of ex- pressing ideas in code. read more..

  • Page - 38

    • CHAPTER 0 • NOTES TO THE READER Il is essential that you don'l gel stuck in an auempt to leam "everything" about some language detail or technique. Fo r example, YO LI could memorize all of C++'s built-in types and all the rules for their usc. Of course you could , and doing so m ight make you feel knowledgeable. H owever, it would not make yo u read more..

  • Page - 39

    0 , 2 A PHILOSOPHY OF TEACHING AND LEARNING On the other hand, we do not use "cute examples involving cuddly animals" to illustrate our points. We ass ume that you aim to write rea1 programs to be used by real people, so every example that is not presented as language-technical is taken from a real-world usc. Our basic tone is that of professionals addressing read more..

  • Page - 40

    I. CHAPTER 0 • NOTES TO THE READER 'lOp..Juwn: This approach, working from first principles toward details, lends 10 distract readers from the practical aspects of programming and force them to concentrate on high-level concepts before they have any chance of appreciating their importance. For example, yOll simply can't ap preciate proper software development principles before you read more..

  • Page - 41

    0, 2 A PHILOS OP HY OF TEA C HING AND LEARNING programming language. Our primary aim is to help you learn general concepts, principles , and techniques. However, those cannot be appreciated in isolation. For example, details of syntax, the kinds of ideas that can be directly expressed , and tool support differ from programming language to programming langu age. However, read more..

  • Page - 42

    12 CHA PTER 0 • NOTES TO TH E READ ER 0.3 Programming and computer science Is programming all that there is to compuler science? Of course not! lbc only reason we raise this question is that people have been known to be confused about this. We LOuch upon major topics from computer science, such as alga- riuuns and data structures, but our aim is to teach read more..

  • Page - 43

    0.6 REFERENCES errors, typos, unclear text, missing explanations, etc. We'd also ap preciate sug- gestions for better exercises, better examples, and topics to add, topics to delete, etc. Constructive comments will hel p future readers and we'll post errata o n our support website: www.slrouslrup.com/Programming. 0.6 References Along with listing the publications mentioned in this read more..

  • Page - 44

    14 CHAPTER 0 • NOTES TO THE READE R StrOuslrup , Bjarnc. 'The C++ Programmi1lg Language (Special £iii/ion). Addison- Wesley, 2000. ISBN 0201700735. Stroustrup, Bjarne. "C and C++: Siblings"; "C and C++: A Case for Compati- bility" ; and "C and C++: Case Studies in Compatibility." CIC++ UJerl JOIln/a/, Jul y, Aug. , Sept. 2002. Sutler, Herb. EYceptumai read more..

  • Page - 45

    0.7 BIOGRAPHIES first computer scientist ever, I received the 2005 William Procter Prize for Scien- tific Achievement from Sigma Xi (the scientific research society). I do have a life outside work. I'm married and have twO children, one a med· ical doctor and one a Ph.D. student. I read a lot (including history, science fiction, cri me, and current affairs) and like most read more..

  • Page - 46

    " (HAPTER 0 • NOTES TO THE READER Postscript Most chapters provide a short "postscript" trying to give some perspective on ,he infannation prescllIcd in the chapter. We do t.hat in lhe realization that the infor- mation can be - and o ften is - dau nting and will only be fully comprehended after doing exercises, reading furth er chapters (which apply the read more..

  • Page - 47

    Computers, People, and Programming "Specialization is for insects." -R . A. Heinlein I n lhis d lapter, we present some o f the lhings that we think make progranuning important, interes ting, and fun . We also present a few fundam ental ideas a nd ideals. We hope to d ebunk a couple of popular myths about progranuning and program- mers. This is a chapter to read more..

  • Page - 48

    18 1.1 Introduction 1.2 Software 1.3 People C HAPTER 1 • C OMP U TERS , P EOPL E, ANO PROGRAMMI N G 1.4 Computer science 1.5 Computers are everywhere 1.5.1 Screens and no screens 1.5.2 Shipping 1.5. 3 Telecommunications 1.5.4 Medicine 1.5.5 Information 1.5.6 Ii vertical view 1.5. 7 SowhaU 1.6 Ideals for programmers 1.1 Introduction Like most learning, learning how to read more..

  • Page - 49

    1.2 SOFTWAR E something thm can help with the current project and Lhat will nOt annoy the boss who controls Lhe next paycheck, promotions, and firin gs - but there has to be more to learning Lhan that! We work best when we feci that our work in some small way makes the world a beuer place for people to live in. Fo r tasks that we perform over a period of read more..

  • Page - 50

    CHAPTER 1 • COMP U TERS , PEOPLE , AND PROGRAMMIN G contain some, and we suspect that even the open/close controls of the windows are computer controlled. Newer models even have computers that continuously monnor ure pressure. H ow many computers do you depend on for what you do during a day? You eat; if you live in a modern city, gelting the food to you is a read more..

  • Page - 51

    1.3 PEOPLE from many physical constraints previously considered fundamental. If you get ill , the medicines given to cure you will bave been designed using computers. Finally, researdl - science itself - relics heavily on computers. The tele- scopes that probe the secrets of distant stars couJd not be designed, built, or oper- ated without computers, and the masses of data read more..

  • Page - 52

    22 ( HAPTER 1 • CO MP UTERS, PEOPLE. AND PROGRAMMING likely to want to destroy the world as he is to wam to save it. Obviously, milder vers ions of such caricatures exist in rcallifc, but in our experience they arc no more frcquem among software developers than they arc among lawyers, police officers, car salesmen, joumalists, arusts, or politicians. Tllink about the read more..

  • Page - 53

    1.] PEOPLE ing people we meet and the variety of places we get to visit as part of our profes- sionallives. One implication of all this is that people with a wide variety of skills, inter- ests, and work habits are essential for producing good sofn-vare. Our quality of life depends on those people - sometimes even our life itself. 0 one person could fill all the read more..

  • Page - 54

    2' CHAPTER 1 • COMPUTERS, PEOPL E, AND PROGRAMMING an advantage, maybe as a designer, writer, manager, or scientist. Maybe you will do programming at a professional level as part of your studies or work. Even if you do become a professional progranuncr it is unlikely that you will do nothing but programming. You might become an engineer focusing on computers or a read more..

  • Page - 55

    1.5 COMPUTERS ARE EVERYWHERE and information fields of science and engineering, as well as for physics, biology, medicine, history, literature, and any other academic or research field. Consider compuler science. A 1995 U.S. goverlUllenl "blue book n de[mes it like this: "TIle systematic study o f computing systems and computation. TIle body o f knowledge resu lting from read more..

  • Page - 56

    26 C HAPTER I • C OMP UTERS , PEOPLE , AN D PRO G RAMMIN G 1.5.1 Sc reens and no sc reens TIle idea of a computer as a fairl y large square box with a screen a nd a keyboard is common a nd often hard to shake off. However, consider these twO compute rs: Both o f these "gadgets" (which happen to be watches) arc primarily computers. In fact, read more..

  • Page - 57

    1.5 COMP UTERS ARE EVERYWHERE Consider where computers and software play key roles here: /Je5ig1l: Of course, the ship and the engine were both designed uSLIlg computers. ~nle list of uses is almost endless and includes architectural and engineering drawings, general calculations, visualization of spaces and parts, and simulations of the performance of parts. ums/me/ioll: A modern read more..

  • Page - 58

    2. CHAPTER I • CO MPUTER S, PEOPLE, AND PROGRAMMI NG transport is really amazingly low. You appreciate that when you buy something that wasn't manufactured locally. Sea transport has always been cheaper than land transport; these days one of the reasons is serious usc of computers and information. 1.5.3 Telecommuni catio ns "Illesc twO photos show a telephone switch read more..

  • Page - 59

    1.5 COMPUTERS ARE EVE RYWHERE many books much thicker than this one, but it involves a combination of hard- ware and software on hundreds of computers scattcred over the geographical area in question _ Ir you are unlucky, a few telecommunications satellites (them- selves computerized systems) arc also involved - "unlucky" because we cannot perfectly compensate fo r the read more..

  • Page - 60

    30 (HAPTER 1 • CO M P UTERS, P EOP LE, AND PROG RAMM ING 1.5.4 Medi ci ne These two photos show a C AT (computed axial tomography) scan n er and an op- erating theater for computer-aided surgery (also called "robol-assisted surgery" or "robotic sur gcIY"): Consider where computers and software play key roles here. 111C scanners basi- cally arc computers; read more..

  • Page - 61

    1.5 CO MP UTE RS ARE EVERYW H ERE 1.5 .5 Information These two photos show an ordinary PC (well, two) and part of a server fann: \o\'e have fOCllsed on "gadgets" for the lIslial reason: yOll ealUlot sec, feci, or hear software . \'\Ie cannOt present you with a photograph of a neat program, so we show YOll a "gadget" that runs one. However, much read more..

  • Page - 62

    32 CHAPTER 1 • COMPUTE RS, PEOPLE , AND PROGRAMMING personnel records, studclll records, patient reco rds, etc. - the records that essen- tially every organization (commercial and nonconlllcrcial, govcmm ental and pri- vate) keeps . These records arc the backbone o f their respective organizations. As a computing effort, processing such records seems simple: mostly some informa- read more..

  • Page - 63

    I .S COM PU TER S AR E EV ERYWH ERE If you want to do "rocket science," becoming a good programmer is one way. TIle vilriol,.lS space programs employ lots of software designers , especially ones who can also understand some of the physics, math, electrical engineering, me- chanical engineering, medical engineering, etc. that underlie the manned ,md un- manned space read more..

  • Page - 64

    J4 C H APTE R ' • COMPUTE RS, P EOPLE , ANO PROGRAMMING 1.5.7 So what? What do all these "fa ncy and complicated" applications and software systems have to do with learning programming and lIsing C++? '11C connection is sim- ply that many programmers do gel to work on projects like these. These arc the kinds of lhings that good programming can help read more..

  • Page - 65

    1.6 IDEAL S FOR PROGRAMMER S do a few operations, such as adding twO numbers and choosing the next instruc· tion to cxecute based on a comparison of two numbers. "n lC problem is that we don't want computers to do simple things. Wc want "lhe machine" to do lhings that arc difficult cnough for us to want help with them, but computers are nit- picking, read more..

  • Page - 66

    36 ( HAPTER 1 • COMP UTERS, PEOPLE , AND PROGRAMMING working with lhe design may suggest aspects of the problem that hitherto had been overlooked in the analysis. Actually using the system typically exposes weak- nesses of the illmlysis. The crucial concept here is ftedlmclr.. We learn from experience and modify our behavior based on what we learn. That's essential for read more..

  • Page - 67

    CHAPTE R I REV IEW we wam a Shape type, a Circle type, a Color type, and a Dialo&.-boJl: . "Vhen we want to deal with streams of data, say from a temperature sensor, we want an istream type (" i" for inp ut). Obviously, every such type should provide the ap- pro priate operations and only the appropriate operations. Illese arc just a few examples from read more..

  • Page - 68

    J8 C HA PTE R t • COMPUTE RS, PEOP LE , AN D PROGRAM MI NG Terms "Illese terms prescnt the basic voca bulary of program ming and of C + +. Ir yO Li waIll to understand what people say about program ming topics and to articulate your own ideas, you should know what each means. aITordabiJity analysis blackboard CAD/CAM communications correctness Exercises custo read more..

  • Page - 69

    CHAPTER 1 POSTSCRIPT 9. Write an explanation (at least 100 words, but fewer than 500) o f what role other than programmer you'd like to play in the computer industry (independently o f whether "programmer" is your first choice). 10. Do you think complilers will ever develop to be conscious, thinking be- ings, capable of competing with humans ? Write a short read more..

  • Page - 70

    read more..

  • Page - 71

    Part I The Basics read more..

  • Page - 72

    read more..

  • Page - 73

    \.1 . r 2 Hello, World! "Programming is learned by writing programs." -Brian Kernighan H ere, we presem the simplest C++ program that actually does anything. The purpose of writing this program is La Let YOli try your programming e nvironment • Give you a first feci of how you can gel a computer to do things for you Thus, we present the notion o f a read more..

  • Page - 74

    44 2.1 Programs 2.2 The classic first program 2.3 Compilatio n 2.4 Linking 2.5 Programming e nviro nme nts 2.1 Programs (HAPTER 2 • H EllO, WORLD! To get a computer to do somethi ng, YOli (or someone else) have to tell it exactl y - in excruciating detail - what to do. Such a description of "what to do" is called a program, a nd programmillg is the read more..

  • Page - 75

    22 THE ClASSIC FIRST PROGRAM 2.2 The classic first program Hen: is a version of l,he classic ftrst program. It writes "Hello, World !" to your screen: IIThis prog ram outputs the message "Hello, Worl d ! ~ to the monitor #include "SldJ ib_facililies. h" int main O ( II C++ programs start by executing the function main co ul « "Hello, Wo rld! read more..

  • Page - 76

    46 C HAPTER 2 • HEllO, WORLD! Comments arc wriucl1 to describe what lhc program is intended to do a nd in gcncrallo provide information useful for humans that can't be directl y expressed in code. TIle person most likely to benefit fro m the com me nts in yo ur code is you - when yo u come back to that code next week , or next year, and have for- read more..

  • Page - 77

    2. 2 THE Cl ASS IC FIR ST PROGRAM inl main O II C++ programs start by executing the (unction main { ) coul« "Hello, World!\n"; /I output "Hello. World!" relurn 0; Every C++ program must have a function called main to tell it where to Start ex- ecuting. A function is bas ically a named sequence of instructions fOT the COIll- puter to execute in read more..

  • Page - 78

    48 CHAPTER 2 • H Ell O , WO RL D ! "understand." "That trans lation is done by a program called a rompiler. What you read and write is called source {(XU or program ltxl, and what the computer excelllcs is called executable, Qi!jeci~, or lIIachinc code. Typ ically C + + source code files are given the suffix .cpp (e.g., hello_world .cpp) or .h (as read more..

  • Page - 79

    2 .3 COMPILATION Unfortunately, tllC compiler again complains: we misspelled sld_Iib_facilities. h. The compilcr also objects to this: #include "std_lib_facilities. h" int mainO ( cout « "Hello, World!\n ; return 0; We didn'ttenrunate lhe string with a n. The compiler also objects to this : #include "std_lib_facilitie s. h" integer mainO ( ) (out « "He read more..

  • Page - 80

    50 #includ e "std_lib_faciliti es. h" inl m ai nO { ) coul « "Hello, World !\n" return 0; CHAPTER 2 • HElLO , WORLD! We forgol to terminate the output statement with a semicolon. Note that many C++ statements are terminated by a semicolon (;). The compiler needs those semicolons to know where olle statement ends and the next begins. "n Iere is read more..

  • Page - 81

    2.4 LI N KI NG 2.4 Linking A program usually consists of several separate parts, often developed by difTerem people. For example, the "Hello, World! " program consists of the part we wrote plus pans of the C++ standard library. 111ese separate parts (so metimes called Inmslalioll III11~S) must be compiled and the resulting object code filcs must be linked together to read more..

  • Page - 82

    52 ( HAPTER 2 • H EllO, WORLD! 2.5 Programming environments To program, we usc a programming language. \lVc also lI SC a compiler to trans- late ollr source code into object code and a linker to link Ollf object code into an executable program. In addition , we lISC some program to e nl er OLlI' source code text into the computer and to edit it. lncsc arc read more..

  • Page - 83

    CHAPTER 2 D Rill sequencing is crucial, and each individual step should be easy (or even trivial). Please don't try to be clever and skip steps; on average that will slow you down or even confuse you. You might think you understand everything you read and everyth ing your Memor or instructor told you, but repetition and practice arc necessary to de- velop progranun ing read more..

  • Page - 84

    I .. #include<algo rithm> #indude<cmath> using namespace sid ; CHAPTE R 2 • Hel lO , WORLD ! inline void kee p_window_ope nO ( char Ch i cin» ch i ) TIlis uses the standard library directly, will keep you going u ntil Chapter 5, and will be explained in detail later (§8.7). 3. Compile and run the "Hello, World !" program. QyilC likel y, read more..

  • Page - 85

    (HAPTER 2 EXERCISES Most review questions have a clear answer in the chaptcr in which they appear. Howevcr, we do occasionally include questions to remind you of relcvalll infor· mation from other chaptcrs and sometimes even relating to thc world outside this book. We consider that fair; there is more to writing good software and thinking about the implications of doing so read more..

  • Page - 86

    CHAPTER 2 • HelLO, WORLD ! are attending some school ; if you are nOt, pick another target). Have a friend try to follow the instructions and annotate them with improve- ments as he or she goes along. To keep friends, it may be a good idea to "field lest" those instmctions before giving them to a friend . 4. Find a good cookbook. Read the instmctions for read more..

  • Page - 87

    CHAPTER 2 PO STSCRIPT Postscript What's so important about the "HeUo, World !" program? Its purpose is to get us acquainted with the basic tools of programming. We tend to do an extremely simple example, such as "H ello, World! ," whenever we approach a new tool. That way, we separate our learning into two parts: first we learn the basics of our tools read more..

  • Page - 88

    read more..

  • Page - 89

    1- r 3 Objects, Types, and Values "Fortune favor s the prepared mind." - louis Pasleur T his chapter illlroduces the basics of sLOring and using data in a program . To do so, we first conCClllratc o n reading in data from the keyboard. After establishing me fund am ental no- tions of objects, types, values, and variables, we introduce several operators and give read more..

  • Page - 90

    60 CHAPTE R 3 • OBJEC TS, TYPE S, AND VALUES 3.1 Input J.2 Variables 3.3 Input and type 3.4 Operations and operators J.S Assignment and initialization 3.S.1 An eumple: delete repeated words 3.1 Input 3.6 Composite assig nment o perators 1.6.1 An e.u.mple : co unt repea led wo rd s 3.7 Names 3.8 Types a nd objects 3.9 Type safe ty 3.9.1 Safe conve rsions 3.9.2 read more..

  • Page - 91

    ].1 INPUT The #include and the main O are familiar fr0111 C hapte r 2. Since the #include is needed for all our programs (up to Chapter 12), we'll leave it out of our presen- tation to avoid distraction. Similarly, we'll sometimes present code that will work onl y if it is placed in main () or some other function by itself, like this: co ut « "Please enter read more..

  • Page - 92

    .2 CHAP TER 3 • OB JE CT S, TY PE S, AND VA LUES them with others before hitting Enter. The newline will not be part of lhe string sto red in memory. H avi ng gotten the input string into fi rsCname, we can usc it : co ul « " He llo,"« firsCnam e « "!\n "; This prin ts Hello, followed by Nicholas (the value of fir sC na me) read more..

  • Page - 93

    3. 2 VAR I ABLES melll that defines a variable is (unsurpris ingly) called a dejillitiQTl, a nd a dermi tion can (a nd usually should) provide an initial value. Consider string nam e = "Anne ma rie "; int numbe r_o Cste ps = 39; You can visua lize these variables like this ; int; string ; numbe r_oCste ps ; 39 name ; I Annemarie I Yo u cannot read more..

  • Page - 94

    64 CHAPTE R 3 • OB JECTS, TYPES. AND VALUE S 3.3 Input and type The input operation » ("gel from ") is sensitive to type; that is, it reads according to the type o f variable you read into. For example: /I read name and age int main O { coul « "Please ent e r yo ur first name and age\n" ; string first_na me; II string va riable int read more..

  • Page - 95

    J .J IN I)UT AND TYPE ) string firscname = "???" ; II string variable II (U???'" means Ndon'( know the nameN) int age = - 1; II inleger variable (- 1 means Ndon', know the age") cin » fi rsCname» age ; II read a string follO\ved by an integer cout « "He llo ,"« firsCname«" (age"« age« ")\n "; Now th e input read more..

  • Page - 96

    66 CHAPTER 3 • OBJECTS, TYPE S, AND VALUES 3.4 Operations and operators In addition La specirying what values can be stored in a variable, the type or a variable detcnnincs what operations we can apply to it and what they mean. For example: int count ; ci n »count ; string nam e; d n » na me; int c2 = count+2; strin g 52 = na m e +" Jr. "; read more..

  • Page - 97

    3 .4 O PERA T IO N S AND O PE RAT OR S boo! char int do uble siring add 10 end += decremenl by n - = n - = n multiply and assign "= "= divide and assign 1= 1= remainder and assign %= read from s into x s » x s » x s » x s » x s » x wrile x 10 s s « x s«x s « x s« x s « x equals == == == == == not read more..

  • Page - 98

    .. CHAPTER 3 • O BJE C TS, TYPE S, ANO VAL U ES want to do to a noating-point number, such as taking iLS squa re root, is available as an operaLOr. Many operations are represcmcd as named fun ctions. In this case, we usc sqrt O fro m the standard library to gCllhc square roOt of n : sqrl(n). TIle notation is familiar from math. We'll lISC functions along read more..

  • Page - 99

    3.5 A SSICNMENT AND INITIALIZATION if (first < second) cout « first«" is alphabetically befo re " « second «'\n': if (first > second ) cout « first« " is a lphabe tically afte r " «seco nd «'\n ' : ) Here, we used an if-statement, which will be explained in detail in §4.4.1. 1, to se· lect actions based on conditions. 3.5 Assignment and read more..

  • Page - 100

    70 CHAPTE R 3 • OBJECTS , TYPE S, AND VALUES "Ve can a lso illustrate assignments using stri ngs: siring a = "alpha "; /I a starts oul with the value u alpha ~ a: I alpha a = "bela "; /I a gets the value " beta ~ (becomes ~ beta" ) a : I beta siring b = a; 1/ b starts out with a copy of a's value (that is, read more..

  • Page - 101

    3 .5 ASSIGNMENT AND IN ITI ALIZATI ON the variable empty. On the other hand, an assigmnent (in principle) must clear out the old value from the varia ble before puuing in the new value. You can think of the variable as a kind of small box and the value as a concTCte thing, such as a coin, that you put into it. Before initializatio n, the box is empty, but read more..

  • Page - 102

    72 ( HAPTER 3 • O BJECTS , TYPES. ANO VAL UES input. Remember that for a string, » reads whitespace-scparatcd words . You ter- minate this loop by giving the program an end-oC-input character (usually referred to as end "file). On a Windows machine, lhat's C trl+Z (Control and Z pressed to- gether) foUowoo by an Enter (return). On a Unix or Linux machine that's read more..

  • Page - 103

    1.6 COMPO SITE AS SIGNMENT OPERATORS TRY THI S Get the "repeated word detection program" to run. Test it with the sentence "She she laughed He He He because what he did did nol look very ve ry good good". How many repeated words were there? Why? "What is the defi- nition o f word used here? What is the definition of repealed word? (For exam- read more..

  • Page - 104

    74 ) C HAPTER 3 • OBJECTS, TYPE S, ANO VA LUES inl number_oC words = OJ string previous = .. "; 1/ nol a word Siring current; while (cin»current) { ) ++number_oCwords; /1 increase word count if (previous == currenl) coul« "word numbe r n « number_oCwords «" repeated : "« c urrent « '\n'; previous = current; We start our word counter at O. read more..

  • Page - 105

    3 .7 NAMES , number_oC eleme nts f o urier_transfo rm z2 Polygon Tne followi ng arc not names: 2, limeSloSmarkel Starl menu II a name must start with a leUer /I S is not a leiter, digit. or underscore /I space is not a letter, digit, or underscore When we say M not names" we mean that a C++ compiler will nOt accept them as names. If you read system code read more..

  • Page - 106

    76 (HAPTER J • OBJECTS, TY P ES , AND VALUES The C++ language reserves m any (about 70) names as "keywords." We list them in §A.3. 1. You can't usc those to name your variables, types, functions, etc. For CXillllplc: int if=7 ; II error: " if" is a keyword You can usc names of facilities in the sta ndard library, such as string, but you read more..

  • Page - 107

    J .8 TYPE S AND OBJECTS because that's conventionally reserved for macros (§27.8 and §A. 17.2), which we avoid . "Ve use an initial capital letter fo r types we define, such as Square and Graph . "111e C++ language and standard library don't use capitaileueTS, so it's inl ra ther tha n Inl and siring rather than Siring. TIlUS, our convention helps to read more..

  • Page - 108

    78 C HAPTER 3 • OBJECTS, TYPES , AND VAL U ES The representation of a string is a bit more complicated than that of an int be- cause a string keeps track of the number of characters it holds. Note that a double stores a number whereas a string stores characLCrs. For example, x Slores the number 1.2, whereas 52 Slores the three characters '1', ' .', and read more..

  • Page - 109

    3 . 9 TYPE SAFETY do uble y = X; double l = 2.0+x; /I the va lue of y is undefined /I the meaning of + and the value of z are undefined An implementation is even allowed to give a hardware error when the uninitiaJiz.cd X is used. Always initialize your variables! 'n lere arc a few - very few - exceptions to this rule, such as a variable we inunediatcl read more..

  • Page - 110

    '" (HAPTER] • OBJECTS , TYPES , AND VALUES In this sense - that a value is always converted to a n equal value or (for doubles) to me best approximation of an equal value - these cOllve rsions arc safe : bool to c har bool to int bool to d o uble char to inl char to double int to double The most useful conversion is int to double because it read more..

  • Page - 111

    3 . 9 TYPE SAFET Y problem is that an int is typically much larger than a char, so that it ca.l1 (and in this case docs) hold an int value that cannot be represented as a char. T ry it to see what value b gels on yo ur machine (32 is a common resul t); beuer still, experiment. : int mainO { double d =0; while (cin>>ti) ( /I repeat the s!atcmCnlS read more..

  • Page - 112

    82 int to bool char to bool CHAPTER 3 • O BJ ECTS. TYPE S, AND VALUES arc accepted by the compiler even though they arc unsafe. lllCY aTC unsafe in lhe sense tha t the value stored might differ from the value assigned. Why can this be a problem? Because often we don' t suspect that an unsafe conversion is taking place. Consider : do uble x = 2.7; II read more..

  • Page - 113

    C HAPTER 3 DRIL L sare conversions arc o rten manageable in small programs and ror experienced progra mmers. TIley can be a source or errors in larger programs, though, and a sign ificant cause or problems ror novice programmers. However, compilers can wam about narrowing conversions - and many do. So what should you do ir you think that a conversion might lead to a read more..

  • Page - 114

    / .. ( HAPTER 3 • O BJEC TS. TYPES , AND VALU ES 6. Add this to your letter : Ir your fri end is under 12, write " Next year you will be age+l ." If your friend is 17, write "Next year you will be able to vote." If your frie nd is over 70, write "I hope you arc cl~oying retirement." Check your program to make sure it responds read more..

  • Page - 115

    CHAPTER J EXE RCISES 19. Give five examples of legal names that you sho uldn't usc because they are likely to cause confusion. 20. What are some good rules for choosing names? 21. What is type safety a nd why is it important? 22. \¥hy can conversion f rom do uble to inl be a bad thing? 23. De fin e a rule to help decide if a conve rsion fro m o ne type read more..

  • Page - 116

    CHAPTE R 3 • O BJECTS , TYPES, AND VALUES 8. Write a program to test an imeger value to determine if it is odd or even. As always, make sure your output is dear and complete. In other words, don't juSt output "yes" or "no." Your Output should stand alone, like "111e val ue 4 is an even nu mber." Hint : See the remai nder (modulo) read more..

  • Page - 117

    CHAPTER J PO STSC RIPT Postscript Please don't underestimate the importance of the notion oftypc safety. Types an: at the center of most notions of correct programs, and some o f the mOst effective techniques for constructing programs rely on the des ign and use of types - as you'll see in C hapters 6 and 9, Parts II, III, and IV. 87 read more..

  • Page - 118

    read more..

  • Page - 119

    Computation "If it doesn't have to produce correct results, I can make it arbitrarily fast." - Gerald M. Weinberg T his chapter presents the basics of computation. In panicular, we d iscuss how to compute a value from a set o f operands (rxjJressifm), how to choose among alLemative actions (selection), and how to repeat a computation for a series of values read more..

  • Page - 120

    .. 4.1 Computation 4.2 Objectives and lools 4.3 Expre ssions 4.3.1 Constant e xpressions 4.3.2 Operators 4.3.3 Conversio ns 4.4 Statements 4.4.1 Sele ction 4 .4 .2 Ite ration 4.1 Computation C H AI)TER 4 • COM PUTATION 4.5 Functions 4.5.1 Why bothe r with fun ctio nsr 4.5.2 Fu nction d eclaratio ns 4.6 Vector 4.6. 1 Gro wing a vector 4.6.2 A numeric exampl e read more..

  • Page - 121

    4 .1 COMPUTATION Input comes from a wide variety of sources. Similarly, output can go to a wide variety of destinations. Output can be to a screen, to files, to other output devices, to other programs, and to other parts of a program. Examples of output devices include network interfaces, music synthesizers, electric motors, light gen- erators, heaters, etc. From a read more..

  • Page - 122

    92 C HAPTER 4 • COMPUTATION 4.2 Objectives and tools Our job as programmers is lO express computatio ns Correctly Simply Efficiently Please note the order of those ideals: it doesn't malter how fas t a program is ifit gives the wrong results. Similarly, a CO ITeet and efficient program can be so CO Ill- plicated that it must be thrown away or completely rewritten 10 read more..

  • Page - 123

    4 . 2 OBJECTIVES AND TOOLS refer to the beginning and the end of the phone book, res pectively. An- other example is the way we use computer memory. Direct use of mem- ory can be quite messy, so we access it th rough typed and named variables (§3 .2), standard library vectors (§4.6, C hapters 17- 19), maps (C hapter 2 1), etc. "Divitk and (01/(flU7''': Here read more..

  • Page - 124

    .. C HAPTER 4 • CO MP U TATION programming that - like what is described in Lhe rest of this chapter - arc COll - crete and immediately useful and to ignore the "softer," more conceptual pan s of the art of software development. However, good programmers and system de- signers know (often having learned it the hard way) that concerns abollt struc- ture lie read more..

  • Page - 125

    4. 3 EXP RE SS ION S That is, le ngth is the name of a n object of type int containing the value 99. Some- times (as an lvalue) le ngth refers to the box (object) and sometimes (as an rvalue) le ngth refers to the value in that box. We can make more complicated expressions by combining expressions using operators, such as + and · , in just the way that read more..

  • Page - 126

    .. ( HAPTER 4 • C OMPUTATION symbolic constant, that is , a named object to which you can't give a new value after it has been initialized. For example: const d o uble pi = 3. 141 59; pi = 7; II error: assignment to consl int v = 2· pilf; /I OK: we just read pi; we don't try to change it Such constan tS are useful for keeping code readable. YOli read more..

  • Page - 127

    4 .J EXPRE SSIONS Name f(a) function call ++Ival pre-increment -- Ivai pre-decrement " no. -, unary minus ,'b multiply o/b divide a%b modulo (remainder) .. b add ,-b subtract out«b write b to out in»b read from in into b ,<b less than a<=b less than Of equal o>b greater than a>=b greater than Of equal a==b equal a!=b not equal a&&b logical read more..

  • Page - 128

    .. CHAP TER 4 • COMP U TATION VVhich nOtation should we use? Why? We prefer the first version, ++a, because it more directly expresses the idea of incrementing. It says what we want to do (in· crement a) rather than how to do it (add 1 to a and then write the resul! to a). In general, a way of saying something in a program is better than another if it read more..

  • Page - 129

    4.'1 STATEMENT S d2 = dIi ; i2 = dIi ; /I d2 == 1.2 5 II i2 == I Beware that it is easy to forget abollt integer division in an expression that also contains floating-point operands. Consider the lISllal formula fo r convening dc- grees Celsius to degrees Fahrenheit:! = 9/5 · c + 32 . We might write double d c; cin » dc; do uble d f = 9/5- d c+32; read more..

  • Page - 130

    100 ( HAPTER 4 • COMP U TATION Without the semicolon, the compiler does n't know whether we mean a=b++; b; or a=b ; ++b ; .111is kind of problem is not TCStricted to computer languages; con- side r the exclamation "'man eatin g tiger! " ' '''ho is eating whom? Punctuation ex- ists to eliminate such problems, for example, "man-ea ting tiger!" When Slalcm read more..

  • Page - 131

    4.4 STATEM ENTS gardless. ' Illis is a common error for novice programmers, and it can be d ifficu lt 10 spot, so walch OUl for it. ' Ille next section is devoted to statements used to alter the order of evalua- tion to allow us to express more interesting computations than those we get by just executing statements in the order in which they were written. 4.4.1 read more..

  • Page - 132

    102 C HAPTER 4 • C OMP U TATI O N and if (Ira ffi c)ight==re d ) wail(); So, the basic notion is simple, but it is also easy La use if-slatcmcnts in a toO simpleminded manner. Consider what's wrong w ith this program (apart from leaving out the #include as usual): /I convert from inches to centimeters or cen timeters to inches /I a suffix 'i' or 'c' read more..

  • Page - 133

    4 . 4 STATEMENTS int mainO ( } const do uble cm_p er_inch = 2.54; II number of centimeters in an inch int le ngth = 1; II length in inches or centimeters char unit = ' ' ; II a space is not a unit eout« "Please e nter a length followed by a unit (e or i): \n "; cin» le ngth » unit; if (unit == 'i') eout « length « "in read more..

  • Page - 134

    104 C HAPTER 4 • COMPU TATION TRY THIS Use the example above as a model for a program that converts yen, curos, and pounds into dollars. If yo u like realism, you can find conversion rates on the web. 4.4 .1.2 switch-statements Actually, the comparison of unit to 'i' and to 'c' is an example of the most com- mon form of selection: a selection based on read more..

  • Page - 135

    4 . 4 S TATEMENTS don't already know, programming will teach you that it's hard to be absolutely certain (and right) about any thing. 4.4.1.3 Switch techni calities Here are some technical details abom switch·statements: 1. TIle value on which we switch must be of an integer, char, or enumera- tion (§9.5) type. In panicular, you cannot switch o n a string. 2. 111e read more..

  • Page - 136

    '06 ) const char n = ' n' ; const char m = '1'; cout « "Do you like fishl\n "; c har 3j cin »a; switch (a) { case n : II . .. break; ( H APTER 4 • COM PU TATION case y: 1/ error: variable in case label II . .. break; case m : II . .. break; case 'n ': II . .. brea k; default: ) II . .. break; 1/ error: duplicate case read more..

  • Page - 137

    4 . 4 STATEMEN T S } default : } cout « "is not a dig it\n "; break; The most common error with switch-statements is to forget to terminate a case \vilh a break. For example : int mainO II e)(ample of bad code (a break is missing) { ) eonst do uble cm_pe rj nch = 2.54; II number of centimeters in an inch intl e ngth = 1; II length in inches read more..

  • Page - 138

    108 ( HAPTE R 4 • C O MPUTAT ION 4.4.2 Iteration We rarel y do something only once. 111crcfOl'c, program ming languages provide convenient ways of doing something several times. ll1is is called repetitioll or - especially when you do something LO a series o f clements of a data st nlCtll rc - ileraJion. 4.4.2.1 while-statements As an example of iteration, consider the read more..

  • Page - 139

    4.4 STATEMENT S Otherwise, we print the number and its square, separated by a tab ('\1'), increase the number, and try again. Clearly, to do this we need A way to repeat some statement (to lOOP) A variable to keep track of how many times we have been through the loop (a loop IXIn'abfe or a collirol varinhle), here the inl called i An initializer for the loop read more..

  • Page - 140

    110 C HAPTE R 4 • COMPUTAT ION TRY THIS The character 'b ' is char('a'+l ), Ie' is char('a'+2), etc. Usc a loop to write o ut a table of characters with their corresponding integer values: a .7 b .8 z 122 4.4.2 .2 Blocks Note how we grouped the two statements that the while had to execute: w hile (i<100) ( cout « i « '\1' «squa re(i) « '\n ' read more..

  • Page - 141

    4.4 STATEMENTS for (int i = 0; i<100; ++i) cout « i « '\1'« square(i)« '\n '; '11ls means "Execute the body with i starting at 0 incrementing i aftcr each exe- CLition of the body until we reach 100_" A for -statcment is always equivalent to some while-statement. In this case for (int i = 0; i<100; ++i) co ul « i « '\1' « square(i)« read more..

  • Page - 142

    112 C H APTER 4 • COM PUTAT ION /I calculate and print a table of squares of even numbers in the 10: 1 00) range int ma inO { fo r (int i = 0; i<100i i+=2) coul « i « '\1'« squa re(i)« '\n'i Please note that the cleaner, morc explicit version is shorter than the messy olle. 11m's lypical. TRY THIS Rewrite the character value exam ple fro m read more..

  • Page - 143

    4 .5 FUN C TI ON S "Ve don 't have to use the result ofa fun ction call (but if we didn' t want the result, why would we call it ?), but we do have to give a function exactly the arguments it requires. Consider: square (2)i int v1 = squareOi int v2 = squarei int \13 = square(1 ,2)i int v4 = sq uare("lwo "); 1/ probably a mistake: unused read more..

  • Page - 144

    114 CHAPTER 4 • (OMPUTATION The language-technical aspects o f functions will be examined more closely III C haple r 8. 4.5. 1 Why bother with fun ctions? We define a function when we want a separate computation with a name because doing so Makes the computation logically separate Makes the program text clearer (by naming the computation) M akes it possible to lISC read more..

  • Page - 145

    4 .S FUNCTIONS prinCsquareO is a rather specialized function that we could not expect to be able to use later, whereas squareO is an obvious candidate for other uses squareO hardly requires documentation, whereas print_squareO obvi- ously needs explanation llle underl ying reason for both is that print_squareO perfonns two logically sep- arate actions: It prints. It calculates a read more..

  • Page - 146

    116 C HAPTER 4 • COM PU TATION bod y o f the standard library sqrtO fu nction? We know it calculates the square fOOL of its argument. '.vhy would we want to sec the body of our squareO fun e- lio n? Of course we might just be curious. But almost all of the ti me, we a f C just interested in knowing how to call a fu nction - seeing the definition read more..

  • Page - 147

    4 .6 VECTOR 11lat is, the first clement has index 0, the second index I, and so on. We refer to an clement by subscripting the name of the vector wit.h the element 's index, so here t.he value of viOJ is 5, the value of v[l] is 7, and so 011. Indices for a vedor al- ways start with 0 and increase by 1. 111is should look familiar: the standard li- brary read more..

  • Page - 148

    118 (HAPTER 4 • COM PU TATION vd[20000] = 4.7; /I run-time error We will discuss nm-timc errors and subscripting in the next chapter. 4.6.1 Growing a vector Often, we start a vector empty and grow it to its desired size as \ ... ·c read or COIll- pute the data we want in it. The key operation here is pus h_backO, which adds a new clement to a veclor. The read more..

  • Page - 149

    4 .6 VECTOR Given the defin ition of v and the push_backOs above, this for-loop will print vIOl ==2.7 v(11==5.6 v{2J==7.9 If yo u have programmed before, you will note that a vector is similar to an array in C and other languages. However, yo u need not specify the size (length) of a vector in advance, and you can add as many elements as you like. As we go read more..

  • Page - 150

    120 CHAPTER 4 • COMPUTATION while (ci n» temp) /I read temps. push_back(temp); /I put into vector rn le cin»lemp reads a doubl e, and that double is pllshed into the veclor (placed at the back). We have seen those individual operations before. What 's new here is that we usc the input operation, cin»lemp, a s the condition for a while·loop. Basically, cin» temp read more..

  • Page - 151

    4 .6 V ECTOR fo r (int i = 0; k lemps.size() ; H i ) sum += tempsl i); coul « "Average te mperature : " «su m/temps.sizeO« e ndl; Note how the += operator comes in handy. ' Ib calculate a median (a value chosen so lhat half of the values are lower and the other half are higher) we need to son the clemeills. Fo r that, we lise the stan- dard read more..

  • Page - 152

    122 C H APTER 4 • CO MP U TATION cout « "Number of words : II « words.sizeO «endl; sort(words. begin O,words .end ()) ; 1/ sort " from begi nni ng to end" fo r (int i = 0; i< words.size() ; ++i ) if (i ==O II w o rd s(i - 1]!= word s[iJ) /I is th is a new wo rd~ coul « wo rds[i} « "\n "; If we feed some words read more..

  • Page - 153

    4 .7 LANGUAGE FEAT U RES m." panama plan We didn't like the repetition, so we eliminated it using that test. What docs the test do? It looks to see if the previolls word we pri nted is different fro m the one we are about to print (words[i- l ]!=words[i]) and if so, we print that word ; other- wise, we do not. Obviously, we can' t talk abo ut a read more..

  • Page - 154

    124 C H APTE R <I • COM PU TATI O N to write Llseful programs. TIlis is a key notion : a computer is nOl a gadget with a rlXed function. Instead it is a madunc that we can program to do an y computatio n we can think of, and given that we can attach computers to gadgets thm intcmct with the world outside the computer, we can in principle gel it read more..

  • Page - 155

    ( H AI' TER 4 REVIEW II. Before writing out the values from the vecto r, sort them (that'll make them come Ollt in increasing order). Review 1. What is a computation? 2. What do we mean by inputs and outputs to a computation? Give examples. 3. What arc the three requirements a programmer should keep in mind when expressing computations? 4. What docs an expression read more..

  • Page - 156

    126 Terms abstraction beginO computauon conditio nal sta tement declaration dcfmitio n divide and conquer e lse endO expresSIOn Exercises fo r-statement function if-statement increment mput Iterauo n loop Ivalue member function o utpUt CHAPTER 4 • COM PU TATION push_bac kO repetition rvaluc selection sizeO sartO statcmcill switch-statement vector while-statement l. If you haven't read more..

  • Page - 157

    ( HAPTER 4 EXERCI SES gram, using the same input loop, convert spelled-alit numbers into their digit form; e.g. , the input seve n gives the output 7. 7. Modify the "mini calculator" from exercise 5 to accept (just) single-digit numbers wriucn as either digits or spelled out. 8. 11lere is an old story that the emperor wanted to thank the inventor of the game read more..

  • Page - 158

    128 CHAPTER 4 • COMP U TATI ON 12. Modify the program dcscribed in the previous exercisc to take an input value max and then find all prime numbers from 1 to max. 13. Create a program to find all the prime numbers bctween 1 and 100. There is a classic method for doing this, called the "Sieve of Eratos· thenes ." If you don 't know that method , read more..

  • Page - 159

    C HAPTER" PO STSCR IPT Postscript From a philosophical point o f view, you can now do everything that can be do ne using a computc r - the rest is details I Among other things, this shows the value of "details" and the importan ce of practical skills, because clearly you have barely started as a programmcr. But we are serious. The tools pl"esented read more..

  • Page - 160

    read more..

  • Page - 161

    Errors "I realized that from now on a large part of my life would be spent fmding and correcting my own mistakes." -Maurice Wilkes, 1949 I n this chapler, we discuss correctness o f program s, errors, and error handling. If you are a genuine novice, you'll find the d is- cussion a bit abstract at times and painfull y detailed at other limes. Can error read more..

  • Page - 162

    132 5. 1 Introduction 5.2 Sources of e rrors 5.3 Compile-time e rro rs 5.3.1 Synt ax e rrors 5.3.2 Type errors S.l.) Non-e rrors 5.4 Link-lime e rrors 5.5 Run -tim e errors 5.5.1 The caller de~ls with e rrors 5.5.2 The c~lIee deals with e rrors 5.S.) Error reporting 5.6 Exceptions 5.6. t Bad arguments 5.6.2 Rilnge errors 5. 6.3 Bad inp ut 5.6.4 N'lfrowing errors read more..

  • Page - 163

    5. 1 I N TROO UC TIO N It is tempting to say that our job as programmers is to eliminate an errors. 111at is of course the ideal, but often that's not feasible. In fact , for real-world programs it can be hard to know exaclly what "all errors" means. If we kicked Ollt the power cord from your computer while it executed yo ur program, would that be read more..

  • Page - 164

    134 CHA PTER 5 • ERRORS 5.2 Sources of errors H ere arc some sources of errors: FfJcr sjxcificatiQn: If we are no t specific about what a pmgram should do, we arc unlikely to adequately examine the "dark corners" and make s ure that all cases arc handled (i.e., that every input gives a correct answer or an adequate error message). InlOmplete progralllJ: During read more..

  • Page - 165

    5 .3 COMP i lE · TIME ERROR S the language specific.1.tion will it allow yo u LO proceed. Many of the errors that the compiler fi nds are simply "silly errors" c.1.used by mistypin g or incomplete edits of the source code. Others result fro m flaws in our understandi ng of the way parts of our progra m interact. To a beginner, the compiler often seems pett}', read more..

  • Page - 166

    136 ( H APTER 5 • ERROR S looking error messages for the same code. Fortunately, you SOO I1 gel used to read- ing such stuff. After all, a quick look at those cryptic lines can be read as "There was a syntax error befo re 53, and it had something to do with the type of Int or 53." G ive n thal, it's not rocket science to find the problem. TRY read more..

  • Page - 167

    5 .4 LINK - TIME ERRORS 111ese arc just a rew examples. There arc many more errors that the compiler will find ror you. TRY TH IS Try to compile those examples and sec how the compiler responds. Try thinking or a rew more errors you rself, and try those. 5.3.3 Non-errors As yOLi work with the compiler, you'll wish that it was smart enough to fi gure OLit what read more..

  • Page - 168

    138 CHAPTER 5 • ERROR S every translation unit in which it is used. We usc header files to ensure lhat ; sec §B.3. Every function must also be defined exactl y once in a program. If e ither of lhese rules is violated, the linker will give an error. We discuss how to avoid link- lime errors in §B .3. For now, here is an example of a program that might read more..

  • Page - 169

    5.5 RU N . T IME ERRORS detect errors, but it is not always easy to know what LO do with an error once you catch it at run time. Consider: int area(int length , int width) { /I calculate area of a rectangle return length*width ; } int framed_area(int x, int y) { II calculate area within frame return area(x-2,y-2); } inl mainO { intx= - l ; inty =2; read more..

  • Page - 170

    140 ( HAPTER 5 • ERR O RS $0, let's tackle the problem of argument errors Wilh areaO. We have tWO ob- vious ah'cmauves: a. Let lhe caBer of areaO deal with bad arguments. b. Let areaO (the called fun ctio n) deal with bad argu ments. 5.5.1 The call er deal s with errors Let 's try lhe first alternative (" Let the lIser beware! ") first. That's the read more..

  • Page - 171

    5.5 RUN-T IM E ERRORS Someone doing that would have to look at every call of framed_areaO and modify the error-checking code correspondingly. Such code is called "briule" bec. ... use it breaks eas ily. This is also an example of a " magic constam " (§4.3 .1 ). We could make the code less brittle by giving the vaJue subtracted by fram ed _areaO read more..

  • Page - 172

    142 CHAPTER 5 • ERRORS Tbis is rather nice, and we no longer have to write a test for each caU of framc_areaO . For a useful functio n that we call 500 times in a large program, that can be a huge advantage. Furthermore, if anything to do with the error handling changes, we only have lO modify the code in one place. Note something interesting: we almost read more..

  • Page - 173

    5.5 RUN - TIME ERR O RS the number of machine ins tr uctions that need lO be executed , nOt just the length of the source code). For some programs , that can be critical, especially if the same information is checked repeatedl y as functions call each other, passing informatio n along more or less und langed . So what should you do? Check your arguments in a read more..

  • Page - 174

    '44 ( CHAPTER 5 • ERRORS A caller can forget to tes t. That can lead to unpredictable behavior fur- ther along in the progra m. Many functions do Il O t have an "'extra" return value thai they Gill usc to indicate an error. For example, a function that reads an integer fro m inpu t (such as, dll's operator » ) can obviously return any int value, so read more..

  • Page - 175

    S.6 EXC EPTIONS llle basic idea is that if a function finds an error that it cannm handle, it does 110t return normally; instead, it throws an exception indic.'lting what weill wrong. Any elil'ect or indirect « Iller can catch the exception, that is, specify what to do if the called code lIsed th row. A function expresses interest in exceptions by using a tr read more..

  • Page - 176

    146 C HAPTER 5 • ERRORS catch (Bad_area) { cout « "Oops! bad arguments to area()\n "; ) First note that this handles all caHs to areaO , both the one in mainO and the two through framed_areaO. Second, note how the handling of the error is cleanly sep- arated from the detection of the co "or: mai nO knows nothing about which func- tion did a read more..

  • Page - 177

    5. 6 EXCEPTION S we were tired. Errors are always more common when you are tired or rushed. We use 0 and sizeO to try to make sure that i is always in ra nge when we do v{i]. Unfortunately, we made a mistake. Look at the for· l oop: t.he termination condition is i<=v.sizeO r a ther than the correCl i<v.sizeO . This has the unfortu nate consequence that if read more..

  • Page - 178

    148 (HAPTER 5 • ERROR S QUtiill C, vector's subscript function (called vector : :operator[J) rcpons finding an error by throwing an exception. \'\!hat clse could it do? lL has no idea what we would like to happen in case of a range error. The author of vector CQuldn't even know what programs his or her code would be part of. 5.6.3 Bad input We'll postpone the read more..

  • Page - 179

    5. 6 EX CEI' Tl ON $ grams? It can't re turn a value because we wouldn't know what to do with that value; instead errorO is supposed to tenninate the program after getting iLS mes- sage written. In addition, we might want to take so me minor action before exit- ing, such as keeping a window alive long enough for us to read the mcssage. "lnat's '1Il obvious read more..

  • Page - 180

    150 C H APTER 5 • ERRORS A5 it ha ppens, o u,-oCrange is nm a runlime_error, SO catching runtime_e rror does not deal with the out_oe range errors that we might gel from misuse of vectors and other standard library container types . However, both ouC oC range and runlime_e rro r arc "exceptions," SO we c.'tn catch exception to deal with bOlh: int mainO read more..

  • Page - 181

    5.6 EXCEPTIONS calls wc have done on thc way to thc crror: erro rO will find its way to the nearest catch or runtime_e rro r, typically thc onc in main O. For examples or the use or ex- ceptions and e rro r() , sec §7.3 and §7.7. Ir you don't catch an exccption, yo u'll get a dcrau lt system error (an !;uncaught exception" error ). TRY THI S To sec read more..

  • Page - 182

    152 CHA PTER 5 • ERRORS 5.7 Logic errors Once we have removed the initial compiler and linker erro rs, the program runs. Typically, what ha ppens next is that no Outp u t is produced or th at the output that the program produces is just wrong. TIlis can occur for a number of reasons. Maybe your understa nding o f the underlying prOb'l'am logic is nawcd ; read more..

  • Page - 183

    , 5 .7 lOGIC ERR OR S - 16.5, -23.2, - 24.0, - 25.7, 7.5, 12.6, 23.8, 25.3, 40.3, 42.6, 39.7, 35 .4, ' n le output was High temperature : 42.6 l ow temperature : -26.1 Average tempe rature: 9.3 - 26.1, - 18.6, 28.0, 34.8, 12.6, 6.5, - 9.7, 36.7, -3 .7, -2.4, 41 .5, -14.3 A naive programmer would eonelude that the program works juSt fm c. An irre· read more..

  • Page - 184

    154 C HAPTER 5 • ERR ORS ~Inesc errors are fairly typical ; they will n Ot cause any errors when you com- pile the program or cause wrong results for "reasonable" inputs_ However, we forgot to think about what we should consider "reasonable." Here is an improved program: int ma inO { ) d o uble te mp = 0; d o uble s u m = OJ do uble read more..

  • Page - 185

    , 5 .8 EST IMAT ION 5.8 Estimation Imagine you bave written a program that docs a simple calculation, say, comput· ing lhe area of a hexagon. You run il and it gives the area -34.56. You juSt know that's wrong. Why? Because no shape has a negative area. So, you fix thaI bug (whatever il was) and get 21.65685. Is that righ t? That 's harder to say because read more..

  • Page - 186

    156 ( C HAPTER 5 • ERR ORS Often, making an estimate involves coming up with estimates of data that arc needed for a proper calculation, but that we don't yet have. Imagine you have to test a program that estimates driving times between cities. Is a driving time of 15 hours and 33 minutes plausible for New York City to Denver? From London to Nice? Why or why read more..

  • Page - 187

    5. 9 DEBUGGING Basicall y, we go through tins sequence again and again: hundreds of times, thou- sands of limes, again and again for years for really large programs. Each time something doesn't work we have to find what caused the problem and ft,'\( it. I consider debugging the most tedious and time-wasting aspect of programming and will go to great lengths during design read more..

  • Page - 188

    158 111c name o f the progra m 111c purpose of the program "Vh o wrote this code and whe n Ve rsion numbers (HAP TER 5 • ERRORS What complicated code fragments arc supposed to do What the general design ideas arc How the source code is o rg-<lIlizcd What ass umptions arc made abo ut inputs What parts of the code afC still missing a nd what cases a read more..

  • Page - 189

    5.9 DEBUGGING lhe rules the compiler enforces are stupid and unnecessary (they ra rel y arc) and that lhinb'5 could and ought to be simple., (indeed, but they are not). However, as they say, "a poor craftsman curses his tools." A good craftsman knows the strengths and weaknesses of his tools and adjusts his work accordingly. Here are some conunon compile-time read more..

  • Page - 190

    160 CHAPTE R 5 • ERROR S flCSl you o ften look at a blank screen (or window), wo ndering how your probrram could have failed to produce any output. A common [mit problem with a Windows console mode program is lhat the console window disappears before YOLL have had a chance to see the outp ut (if any). One solution is to call keep_window_open O fro m our read more..

  • Page - 191

    5 . 10 PRE - AND POST-CONDITIONS if (! (ka && a<b && b<c)) /I ! means ~ not · and && means ~ and · error("bad arguments for mcf"); 1/ .. . If that d oes n' t have any cffect, insert invariillns in sections of code nOi suspected o f harboring bugs; if yO Ll can't find a bug, you are almost cer- tainl y looking in the wro read more..

  • Page - 192

    '.2 (HAPTER 5 • ERR ORS Looking at it this way, argument types arc just a way o f having the compiler check the simplest pre-conditions for us and report them at compile lime. For example: int x = my_compl icated _fun ct io n{1, 2, "horsefealh e rs"); Here, the compiler will catch that the requircmcill ("pre-condition") thaI the third argument be read more..

  • Page - 193

    5. 10 PRE- A N D POST-CON D IT IO N S ging; explicitl y stating pre-conditions helps in avoiding design errors as well as catching usage errors early. Writing int my_compli cated_fun ction(int a, int b, int c) /I the arguments are positi ve and a < b < c { if (!(O<a && a<b && b<c» /I! mea ns ~ not " and && means ~ atl d read more..

  • Page - 194

    '64 C HAPTER 5 • ERR O RS II post-condition: returns a posi tive value that is the area ( } if (lenglh<=O II width <=0) e nor("area() pre -condition "); int a = le ngth -width ; if (a<=O) e rro r(nareaO post-condition "); re turn a; We couldn't check the complete post-condition, but we checked the part that said that it should be positive. TRY read more..

  • Page - 195

    C H AP TE R 5 DR i l l Who do you think will find more errors? Of course, the very best is an experi- enced person with a bit of "'attitude 1" who coolly, calmly, patiently. and system- atically works through the possible fail ings of the program . Good teste rs arc worth their weight in gold . We try to be systematic in choosillg our test cases read more..

  • Page - 196

    1'66 1. 2. 3. 4. 5. 6. 7. B. 9. 10. II. 12. 13. 14. 15. 16. 17. l B. 19. 20. 2 1. 22 . 23 . 2;~. 25 . Cout« "Success!\n "; coul « "S uccess!\n; cout « "S uccess" « !\n" cout « success« endl; (HAPTER 5 • ERROR S string res = 7; vector<int> v(10 ); v(51 = res ; coul « "Success!\n"; vector<int> v(10); read more..

  • Page - 197

    ( HAPTER 5 EXERCI SES 14. H ow do you test if an in put operation succeeded? 15. Describe the process of how exceptio ns are thrown and caught. 16. Why, with a vecio r called v, is v[v.s ize()] a range error? What would be the result of callin g tills? 17. Defme prNoluii/ioll and POSI-amdilioll; give a n example (that is not the areaO function from tllis read more..

  • Page - 198

    168 C H A PTER 5 • ERRO RS 3. Absolute zero is the lowest tempera ture that can be reached ; it is - 273.lS oC, or OK. The above program, even when corrected, wi.1l produce erroneous results when given a temperature below this. Pl.ace a check in the main pnr gram that will prod uce an error if a temperature is given below - 273.1S°C. 4. D o exercise 3 read more..

  • Page - 199

    C HAPTER 5 POS TSCRIPT 9. Modify the program fro m exercise 6 to wri te OUl an error if the result cannot be represented as an in!. 10. Modify the program fro m exercise 8 to usc doubl e instead o f int o Also, make a vector of doubles containing the X- I differences between adja- cent values ,md write out that vector of differences_ 11 . Write a program read more..

  • Page - 200

    CHAPTER 5 • ERRORS confounded by the difficulty of writing correct programs. In our experience, good mathematicians are the people most likely to underestimate the problem of bugs, but we all quickly exceed our natural capacity for writing progratns that arc correct the firs t time. You have been warned! Fortunately, after 50 years 01" so, we have a lot of experience read more..

  • Page - 201

    ~!.. r 6 Writi ng a Program "Progranuning is understanding." -Kristen Nygaard W riting a program involves gradually refinin g your ideas of what you want to do and how you wam to express it. In this chapter and the next, we will develop a program from a fU'st vague idea through stages o f a nalysis, design, implementa- tion, testing, redesign an d read more..

  • Page - 202

    172 6.1 A problem 6.2 Thinking abo ut th e problem 6.2.1 Stages of development 6.2.2 Strategy 6.3 Back to the calculator! 6.3.1 First atte mpt 6.3.2 Toke ns 6.3.3 Impl e menting tokens 6.3.4 Using tokens 6.3.5 Back to the drawin g board 6.4 Grammars '04 . 1 A detour : Engli sh grammar 6.4.2 Writing ill gramma r 6.1 A problem ( H A PTE R 6 • W RITIN G read more..

  • Page - 203

    6.2 THINK I NG ABOUT THE PROBLEM For example, if you ente r 2+3. 1· 4 lhe program should respond 14.4 Unfonumucly, such a calcula tor program does n't give us anything we do n't al- ready have available o n o ur compu te r, but that would be tOO much to as k from a fi rst program. 6.2 Thinking about the problem So how do we start? Basically, think a read more..

  • Page - 204

    174 CHAPTER 6 • W RITING A PR O GR AM 6.2.1 Stages of development He re is a bit of terminology for program development. As YOli wo rk all a prob- lem you repea tedl y go through lhese stages: Andysis: Figure out what should be done and write a description of your (current) understanding of thal. Such a description is called a sd 0/ re- quirements or a read more..

  • Page - 205

    6.2 TH I NKING ABOUT THE PROBLEM Docs the problem seem manageable, given the lime, skills, and tools available? There is IitLle point ill starting a project L1lat you couldn 't possibly complete. If there isn't su fficient lime to implement (includ· ing testing) a program that docs all that is required, it is usually wise not to start. Instead, acquire more resources read more..

  • Page - 206

    176 (HAPTE R 6 • W RI TING A PROG RAM and implementing such parts is a major theme of this book and of soft\'vare development in general ; see user-defin ed types (Chapler 9), class hierarchies (Chapler 14), and generic types (Chapler 20). Build a s mall, limited ve rsion o f the program lhat solves a key part of the problem. When we start, we rarel y know read more..

  • Page - 207

    6 .3 BACK TO TH E CALCU LATOR! ·nIe expressions, c.g., 2+2 and 2+r3, should be entered by the user; the res t is pm- duced by the program. We dIose to OUiput "Expression: " to prompt lhc user. \¥e could have chosen "Please enter an expression followed by a newline" but that seemed verbose and poinDess. On D1e other hand a pleasanDy shon prompt, sud1 read more..

  • Page - 208

    178 CHAPTER 6 • W RITI NG A PROGRAM return 0 ; ) 11lat is, read a pair of values separated by an operator, such as 2+2, compute the result (in this case 4), and pr int the resulting value. We chose the varia ble names Ivai for left-hand value and rva l for ri ght.lland value. 'Illis (sort of) works! So wha t if this program isn't quite comple te? It read more..

  • Page - 209

    6.3 BA CK TO THE CALCULATOR ! } case ' . ' : Ivai "= rval; 1/ multiply: Ivai = Ivai ' rval break ; case 'f: Ivai 1= rval; /1 divide: Ivai = Ivai I rval break ; default : 1/ not another operator: print result } cout « " Result : "« Ival « '\n '; keep_window_open O; return 0; error{" bad expression "); lllis isn't bad, but then read more..

  • Page - 210

    180 CHAPTER 6 • WRITI N G A I'ROGRAM Also, we' ll ask around for help. Surely someone will know a convenlional way of rcading "stuff," such as numbers and operators, from input and storing it in a way th at lets us look at it in convenient ways. The conventional and very usefu l allswcr is "tokcnize" : first input characters arc read and assem read more..

  • Page - 211

    6.] BACK TO THE CA LCULATOR ! der, whereas strings hold sequences o r characters and give us concatcnation and subscripting. The C++ language and its standard library givc us many types such as char. inl, doubl e, siring, vector, and oslream, but not a Token type. In ract, there is a huge number or types - thOllsands or tens or thousands - that we would like to read more..

  • Page - 212

    182 CHAPTER 6 • WRITING A PRO G RA M 12. kind = '8' ; /I we use the digit 8 as (he ~ k i nd " for n umbe rs 12. value = 3.14: We lise the member access notation, obftd_lUllfle . memlxr_'lIllJle, (0 access a mem- ber. YOll can read I.kind as "I's kind " and 12.valu e as "t2's valu e ." We can copy Tokens just as we can copy read more..

  • Page - 213

    6 .3 BACK TO THE CALCULATOR! In the first constructor, :kind (ch), value(O) means "Initialize kind 10 ch and set value to 0." In the second constructor, : kind(ch), value(val) means "Initialize kind to ch and set value to vat." In both cases, nothing more needs to be done to con· struct th e Token , so the body of the function is empty: { }. read more..

  • Page - 214

    184 C HAPTER 6 • WRITING A PROGRAM Now we could fmd the multiply operation by a simple loop : for (i nt i = 0; i<tok .sizeO; ++i) { if (lok[i].kind==' ·') ( /I we found a multiply! double d = lokli-l1.value· tok[i+l1.valuc; II now what? ) Yes, but now what? What do we do with that product d? How do we decide in w hich order to evaluate the read more..

  • Page - 215

    6.3 BACK TO THE CALC U LATOR! 6.3.5 Back to the drawing board Now, we will look at the problcm again and try not to dash ahead with another h,llr·baked solution. One thing that we did discover was that having the program (calculator) evaluate only a singlc expression was tedious. We would like to be able to compute several expressions in a single invocation o f our read more..

  • Page - 216

    .86 ( HAPTER 6 • WRITING A " ROGRAM initial projecl. That would have m OTC than doubled the time needed LO ge l the ini- lial version running. OUT guess is that if yOlI really arc a novice, it would have at least quad ru pled the effon needed and most likely pushed the project beyond you r patience. It is most important to avoid "(eatu re creep" read more..

  • Page - 217

    6.4 G RAMM A RS After tokens have been produced, the program must ensure that complete expressions are understood correctly. For example, we know that 45+11 .517 means 45+(1 1.517) and not (45+11.5 )17, but how do we teach the program that useful mle (division "binds tighter" than addition)? TIle standard answer is that we write a grall/lllar defining the syntax read more..

  • Page - 218

    '88 CHAPTER 6 • W RIT ING A PROGRAM 1+2-3 and 3"2+412. Il seems hardwired in you r brain. However, could you ex· plain how you do it? Could you explain it well enough for someone who had never seen conventional arithmetic to grasp? Could you do so for every combi- nalion of operators and operands? To articu late an ex planation in sufficient d etail and read more..

  • Page - 219

    6.4 GRAMMARS l11is represents the path we rollowed through the definitions. Retracing ollr path, we can say that 2 is an Expression because 2 is a floating-poi nt-literal , which is a Numbe r, which is a Primary, which is a Term, which is an Expression . Let's uy something a bit more complicated: Is 2+3 an Expression ? Nam rally, much or the reasoning is the same read more..

  • Page - 220

    190 C HAPTER (, • W RITI NG A PROGRAM "111C real rcason we are interested in granunars is that they can solve our problem of how to correctly parse expressions with bOlh + and . , so let 's try 45+11.5*7. However, ';playing computer" following the rules in detail as we did above is tediolls, so let's skip some of tJ1C intermediate steps lhal we have read more..

  • Page - 221

    b.4 G RAMMAR S You may find this logic hard to follow at first, but many humans do read grammars, and simple gr<ulullars arc not hard to understand . However, we were not really trying to teach YOIl to understand 2+2 or 45+11 .5+7. Obviously, you knew that already. We were tryi ng to find a way for the computer to "under- stand n 45+11 .5*7 and all the read more..

  • Page - 222

    192 CHAPTER 6 • WRITING A P ROG RAM Now look at a parsing tree as we used above for expressions, but lIsed here for simple English : Parsing a simple English sentence Sentence : Noun Verb Sentence Sentence Conjunction Semence I I I Conjunction : .""'- "or" Sentence Conjunction Sentence "but" Il Il Noun: '"birds" Noull V,,,, Noun Verb read more..

  • Page - 223

    6.5 TU RN ING A GRAMMAR INTO CODE Different textbooks and different parser systems usc different notational conven- tions and different terminology. For example, some call LOkens lennill,llJ and rules T!Q1l-tennvUlLs or pnxJuchoTlS. We simply put tokens in (double) quotes and Slart with the first rule. Alternatives arc put on separate lines. For example: list: "{" Seque read more..

  • Page - 224

    194 C HAPTER 6 • WRITING A PROGRAM 6.5.1 Implementing grammar rul es To implement OUT calculator, we need four functions: o ne to read tokens plus one for eadl rule in OUT gnunmar: geUokenO expression() ferm O primaryO II read characters and compose tokens /I uses ci n /I deal with + and - /I calls leTmO and get_IokenO II deal with' , I, and % /I ca lls read more..

  • Page - 225

    6 .5 TURNING A GRAMMAR I NTO CO DE double expression O /I deal with + and - do uble le rmO 1/ deal with' , /, and % double primaryO 1/ deal with numbers and paren theses 6.5.2 Express ion s Let 's first write expression (). '11e grammar looks like this: Expression : Term Exp ression '+' Term Expression ,_ , Term Since this is our first attempt to turn a read more..

  • Page - 226

    196 CHA PTER (, • W RI TING A PROGRAM Unfortunately, lhat doesn't really make sense. H ow do we know where the ex- pression ends so umt we can look for a + o r a - ? Remember, our program reads left to right and can 't peck ahead to sec if a + is com ing. In fact, this expressionO will never get beyond its first line: expressionO starts by calling read more..

  • Page - 227

    6.5 TURNING A GRAMMAR I N TO CODE So we got a very nice program that just didn't do the right thing. '11at's dan- gerous. It is especially dangerous because it gives the right answer in many cases. "or examp le, 1+2+3 gives lhe right answer (6) bec.lUse 1+(2+3) equals (1+2)+3 . \<\That fundam entally, from a programming point of view, did we do wrong? We read more..

  • Page - 228

    198 ) (HAPTE R 6 • W RITING A PROGRAM while ( I.kind=='+' IIl.kind=='-') ( I/look for a + or a - if (I.kind == ' + ') ) left += termO; /I evaluate Te rm and add else left -= termO: t = geUoken Oj II eva[uale Term and su btract return leH; 1/ finally: no more + or - ; return the answer TIlis is a bit messier: we had to introduce a loop to keep read more..

  • Page - 229

    6.5 TURN I NG A GRAMMAR INTO CODE Term : Primary Term ,. , Primary Term '/' Primary Term '%' Primary Consequcnt.ly, thc code should bc very similar also. Here is a first try: double lerm O { double lefl = primary() ; Token t = geUoken O; while(lru e) { switch (t.kind) { case '.' : left .= primaryO; 1 = gel_tokenO; break ; case 'I' : left 1= primary() ; read more..

  • Page - 230

    200 ( HAPTER 6 • WRITING A PROGRAM yo ur program with a somewhat unhelpful error message. An inexperienced pro- gram mer will discover this the hard way. So, we'd better check and give a decem error message: do uble term O { ) double left = primaryO; To ken t = get_t o ke n (); while(tru e ) { ) switch (t.kind) { case I. ' : left -= prima ryO; t = read more..

  • Page - 231

    6.6 TRYING THE FIRS T VERSION double primaryO ( ) Toke n I = geCloke nO; swilch (I.kind) ( case '(' : 1/ handle '(' expression 'I' { do uble d = expressio nO; 1= gel_Ioke nO: ) if (I .kind != ')') erro r("')' expected "): relurn d; case '8'; /1 we use '8' to represent a number /1 return the number's va lue relurn I.value: defaull : error{" read more..

  • Page - 232

    2')2 CHAPTER 6 • WRITING A PROGRAM TIle error handling is the usual ';boilcrplate" (§5.6.3). Let us postpone the de- scription of the implementation of geClokenO to §6.8 and test t his firs t version of the calculator. TRY THIS This first version of the calculator program (including gel_fokenO) is avail- able as file calculatorOO.cpp. Get it to ru n a nd try it OUL read more..

  • Page - 233

    6 . 6 TRY I NG THE FIR ST VERS ION while (cin) caul «"= " « expressionO « '\n' ; 1/ version I Now, entering the exact sequence of characters as before, we get 2 3 • =2 5+6+7 = 5 , Bad loken Strange! Try to figure out what the program did . We tried another few examples, but let's just look at t.his.'11is is a puzzle: Why didn 't the program read more..

  • Page - 234

    } } case ' +' : leU += lermO; 1= geUokenO; break ; case '-' : left -= lermO; 1= gel_IokenO; break ; d eraull : relurn lefl; } C H APTER 6 • wRITING A PROGRAM II evaluate Term and add /I evaluate Term and sublract /I finally: no more + Of -; return the answer When the Token relumed by geClokenO is not a '+ ' or a '- ' we just return. We don't read more..

  • Page - 235

    6.6 TRYIN G HIE FIR ST VE RSION } case ' +' : le ft += term O; /I evaluate Term and add t = Is.geIO; bre ak ; case '- ' : left -= le rmO; 1= Is.gelC); break ; de fault : /I evaluate Term and subtract Is.pulback(l); II put I back into the token stream re lurn le ft ; /I finally: no more + or -; return the answer } In additio n, we must make read more..

  • Page - 236

    206 C H AP TE R 6 • W RITI NG A PROGRAM For O ll f las t parser fun ction, primaryO, we need just to change geCloken() to ts.get() ; primaryO lIses every token it reads. 6.7 Trying the second version So, we arc ready to test our second version. Type 2 foll owed by a newline. No re- sponse. T ry another newline to see if it's asleep. Still no read more..

  • Page - 237

    6 .8 TOKEN STREAM S \oVc can cha nge that to the messier but more useful double val = 0; while (cin) ( Token I = Is.gel() ; if (I. kind == 'q' ) break; if (I. kind == ';') lI 'q' for Nquil"" II '; ' for Nprint nO\.vN cout« "="« val « '\n ' ; } else Is.putbac k(l ); val = expressionO; Now the calculator is actuall y usable. For read more..

  • Page - 238

    C HAPTER b • W RITI NG A PROG RAM could yo u know that lhe number 1.5 had been completely read without reading the +? Until we sec the + we might be on o ur way to reading 1.55555. So , we need a "strea m" that produces a token when we ask for one llsing getO and where we can put a token back into the stream using putbackO. Everything we read more..

  • Page - 239

    6 .8 TOKEN STREAM S TIlat's all a user needs to use a Token_stream. Experienced programmers w ill wonder why cin is the only possible source o f characters, but we decided to take our input from the keyboard. We'll revisit that decision in a Chapter 7 exercise. Why do we usc the "verbose" name putbackO ra ther than th e logically suffi· cient put()? We wanted read more..

  • Page - 240

    210 { } CHAPTER 6 • WRITING A PROGRAM VVhen we define a member of a class outside the class definition itself, we have to mention which class we mean the member to be a member of. We use the notation for thal. In this case, we define Token_stream 's constructor. A constructor is a member with the same name as its class . Why would we define a member read more..

  • Page - 241

    6 .8 TO KEN STREAMS 6.8.2 Reading tokens All the real work is done by getO. If there isn't already a To ke n in Toke n_stream : : b uffe r, get() must read dmfactcrs from ci n and compose them imo Toke ns: Toke n Toke n_stream : :getO } { if (full) { II do we already have a Token ready? /I remove Toke n from buffer full =false; re turn buffe r; read more..

  • Page - 242

    212 CHAPTER 6 • WR ITIN G A PROCRAM Only if full is false (tha t is, there is no token in the buffer) do we need to Illess with characte rs. In that case, we read a character and deal with it approp riatel y. We look for pare ntheses, operators, and numbers. Any other cha racter gelS us the call of c n orO lhat tcnninatcs the program: default : e read more..

  • Page - 243

    6.9 PRO G RA M STR U CTURE to let dn read the n umber. but we have already read the fi rst character (a digit o r dOl), so j ust letLi ng d n loose on the rest will give a wrong result. We could try to combi ne the value of the first characte r wi th the value of "the res t" as read by d n ; for example, if someone typed 123, we read more..

  • Page - 244

    214 CHAPTE R 6 • WRITING A PROGRAM declared befo re the parser functions because they al1 use il. 111(rc is an interest- ing loop in the ca ll gra ph: e xpression O calls te rm() which calls prima ryO which calls ex pression O. We can represent !.hat graphica11y Oeaving Ollt calls to errorO - Cvc l)'onc calls e rro rO) : lllis means that we can't JUSt read more..

  • Page - 245

    ( HAPTER 6 REV I EW ~ Drill ~nlis drill involves a series of modifications of a buggy program to tum it from something useless into something reasonably useful. I . Take the ca.iculaLQr from the file calculalor02buggy. epp. Get it to com- pile. You need to find and fix a few bugs. TIlOse bugs are not in the text in the book. 2. Change the clmracter used as the read more..

  • Page - 246

    I 216 (HAPTER 6 • WRITING A PROGRAM 17. Wha t is "look-ahead"? 18. Wha t docs putbac kO do and why is it useful? 19. Why is the remainder (modulus) operation , %, difficult to implement in the te rm O? 20. What do we lI SC the two data members of the Token class for? 2 1. \-Vhy do we (sometimes) split a class's members into private a nd publi read more..

  • Page - 247

    C HAPTER 6 EXERC I SES 6. Write a program that checks if a sentence is correct according to !.he "English" grammar in §6.4. 1. Assume that every sentence is tenninated by a rull SLOp (.) surrounded by whitespace. For example, birds fl y but the fish swim . is a sentence, but birds fl y but the fi sh swim (tenninating dot missing) and birds fl y bur read more..

  • Page - 248

    218 C HAPTER 6 • WRITING A PROGRAM Design a program that asks users for two numbers, asks them whether they want to calculate permutations or combinations, and prints out the result. This will have several parts. Do an analysis of the above require- ments. Write exacLly what the program will have to do. - n1 CI1 , go into the design phase. Write pseudo code for read more..

  • Page - 249

    ',L ,.-- 7 Completi ng a Program "It ain 't over till the fat lady sings." -Opera proverb W riting a program involves gradually refmi ng your ideas of what you want to do an d how you want to express il. In Chapter 6, we produced the initial working version of a calcu- lator program. Here, we'll ferm e it. Completing the program - that is, making it fit read more..

  • Page - 250

    22. 7. 1 Intro ductio n 7.2 Input and o utput 7.3 Error handling 7." Negati ve numbers 7.S Remainder : % 7.6 Cleaning up the cod e 7.6.1 Symbolic constants 7.6.2 Use of fun cti ons 7.6.3 Code layout 7.6.4 Co mme nting 7.1 Introduction C HAPTER 7 • COMPL ETI NG A PR O GRAM 7.7 Recovering fro m errors 7.8 Va riables 7.8.1 Variables and definili ons read more..

  • Page - 251

    7, 2 INPUT AND O UTPUT what we would do, ass uming that we can change tile specification of what exactl y the progr.un should do. 00 we really want the program to write Expression : and Result :? How would we know? Just "thinking" rarely hel ps. We have 10 try and sce what works bcsl. 2+3; S·7; 2+9; currellll), givcs =5 = 35 = 11 If we added read more..

  • Page - 252

    222 Token t = ts.get(); if (t.kind == 'q 'l break ; if (t.kind == '; ') ( HAPTE R 7 • COMPLE TI NG A PR OG RAM coul « "= " «va l « '\n ' ; /I print result } else Is.putback(l) ; val = expression(); Unfortunately, the result of putting severaJ expressions on a line is still messy: > 2+3; 5°7; 2+9: =s > =35 >= 11 > ' 11C basic read more..

  • Page - 253

    7.3 ERROR HAND LIN G that you can fix them befo re anybody else finds them. If you go into this exercise with the attitude that '" my program works and I don't make errors!" yo u won't find many bugs and you'll feci bad when you do find one. You'd be playing head games with yourseln The right auitude when tesling is "I'll break it ! I'm smarter read more..

  • Page - 254

    224 CHAPTER 7 • COMPLET ING A PROGRAM question is: "Can we lest the program system atically, so thm we find all of the eT- rors?" "Illerc is no ge neral answer to this qucstion; that is, there is no a nswer tha t holds for all programs. H owever, you can d o rather well for lUany prOb'Tams when yo u a pproach testing seriously. Yo u try to read more..

  • Page - 255

    7. 3 ERR OR HANDLING Basically, we replaced keep_window_openO with our own code. Note that we still have our problem ir a - happens to be the next character to be read after an error. bUl that's rather unlikely. When we encountered this problem we wrote a version or keep_win - d ow_ope nO that takes a string as its argument and closes the window onl y when you read more..

  • Page - 256

    226 C HAPTER 7 • CO MPLETIN G A PROGRAM docs tha t, but the ap paren tl y cleaner 1+2; q cl iciLS a Primary expcCled error. Whe re would we look fo r this e rror? Ll main{) where ; and q are handled , of course. We added those "print" and "quit" CO Ill - mands ra ther q uickly to get the calculator to work (§6.G). Now we a rc payi read more..

  • Page - 257

    7.4 NEGATIVE N U MBERS catch (exception& e) { cerr « e. whatO« endl ; keep_window_o pe n("-"); return 1; catch ( ..• ) { cerr « "exceptio n \n"; keep_window_o pe n("-") i re turn 2; 111is ma kes for reaso nably robus t elTor handling. So we can start considering what else we can do to improve the calculator. 7.4 Negative numbers If read more..

  • Page - 258

    228 a nd we need something like Primary: Number "( " Expression tI)" "- " Primary "+" Primary CHAPTER 7 • COMP LETI NG A PROGRAM We added unary plus because tha t's wha t C++ docs. Whe n we have lInary minus, someone always tries unary plus and it 's easier juSt to implement that than to explain why it is useless . TIle code that read more..

  • Page - 259

    7 .5 REM A INDER : % I. We add % as a Token. 2. We convert the doubles to ints so that we can usc "I" all those ints. Here is the added code in term() : case '''I,,': double d = term(); int il = int(left ); int i2 = int(d); return il %i2; "n 1e int(d) is an explicit nota.lion for turning the do uble into an int by truncating (that read more..

  • Page - 260

    230 } } CHAPTER 7 • COMPLETING A PROGRAM case I ",,: r.'...., ..... ', le U .= lefmO; 1 = Is.get()i break ; case 't : ....... ( double d = term(); if (d == 0) e rror{"divide by zero ") ; left 1= d ; } t = Is.get() ; break; case '0)/0': ( double d =,!erm(); int i1 = int(left); if (it != le ft) error ("Iefl-hand operand of % not int read more..

  • Page - 261

    7. 6 ClEANING U P THE CO DE That's certainly shorter, and argua bly dearer, but it doesn't give quite as good elTor messages. 7.6 Cleaning up the code ""e have made several changes to the code. ~nley are, we think, all improve- ments. but the code is beginning to look a bit messy. Now is a good time to re- view the code to sec if we can make it read more..

  • Page - 262

    C HAPTER 7 • CO MPLETIN G A PROGRAM This req ui res no commem. We should not say in comments what can be clearly and directl y said in code. Repeated commeills explaining something are often an indication that tile code should be improved . Similarly, the code in Token_stream : :getO that recognizes numbers becomes case ' .': case '0': case '1 ': case '2' : read more..

  • Page - 263

    7 .6 CLEANIN G U P THE CO DE Now the strings "> " and "= " s tand out. Why do we have these "magical" lit- erals in the code? How would a new programmer reading main O guess their pur- pose? Maybe we should add a comment ? Adding a comm ent might be a good idea, but introducing a symbolic name is more effecti ve: canst string pro read more..

  • Page - 264

    234 C HAPTER 7 • C OMP LETI NG A P RO GRAM while (eio ) ( cout « prompt; Token t = ts.get(); while (t.kind == prinO I=ts.get() ; if (I.kind == quit) re turn ; Is .putback(l); II first discard all "prints" II qu it cout « result «cx pressionO« e ndl ; } int main() tr y ( } calculale() ; keep_window_openO; return 0 ; ca tch read more..

  • Page - 265

    7.6 C LEANIN G U P THE CODE Token Toke n_stream : :getO { } /I read characters from cin and compose a Token if (fu ll) { /I check if we already have a Token ready full=false; return buffe r; } char Ch i cin » Chi /I notc that » skips whitespace (space, newline, tab, etc.) switch (ch) { case quit : case print : case '(' : case ')' : case '+' : read more..

  • Page - 266

    236 (HAPTER 7 • COMPLETING A PROGRAM When we dean up code. we might accidentally imrodtiCC errors. Always retest the program after cleanup. Belter still, do a bit of tes ting after each set of minor improvements so that if something weill wrong yo u ca.n still remember ex- actly what you d id. Remember: Tcst early and often. 7.6.4 Commenting \ oVc added a few read more..

  • Page - 267

    7 .6 ClEANING U P THE CO DE ' / The grammar (or input is: Statement: Print: Quit: Expression Print Quit q Expression: Term : Term Expression + Term Expression - Term Primary Term' Primary Term I Primary Term "/" Primary Primary: Number ( Expression ) - Primary + Prima ry Number: floating-poi nt-literal Input comes from cin through the Token_stream ca l led read more..

  • Page - 268

    C HAPTE R 7 • C OMPLETING A PRO G RAM 7.7 Recovering from errors Why do we exit when we find an error? T hat seemed simple and obvious at the time, bm why? Couldn 't wej ust write an error message and carry on? After all, we often make little typing errors and such an error doesn't mean that we ha ve decided not to do a calcula tion. So lct's try read more..

  • Page - 269

    7. 7 RECOV ERING FROM ERR ORS I. Purge all tokens from the Toke n_stream. 2. Purge all tokens from the current calculation fro m thc Toke n_stream. lllC first choice discards all (including 4+5: ), whereas the second ch oice just dis· cards 2*3: , leaving 4+5 to be evaluated. Either could be a reasonable choice and either could surprise a user. As it happens, both read more..

  • Page - 270

    C H A PTER 7 • COMPLETING A PROGRAM private: booS full ; II is there a Token in the buffer? Token buffer; /I here is where we keep a Token put back using putbackO ); ~l11is ignoreO function needs to be a member of Token_stream because it needs to look at Token_stream's buffer. We chose to make "the thing to look for" an ar- gument to ignoreO - after read more..

  • Page - 271

    7.8 VARIABLES 7.8 Variables Having worked on style and error handling, we can return to looking for im- provemcnts in thc calculator fun ctionality. We now have a program that works quite well ; how can we improve it? '11e first wish list for the calculator included variables. Having va riables gives us better ways of expressing longer calcula- tions. Simila rl y, for read more..

  • Page - 272

    242 C H APTER 7 • COMPL ETI NG A PRO G RAM double get_value(shing 5) { II return the value of the Variable named s for (int i = 0; kvaUable .size(); Hi) if (va,_lable[iJ. name == 5) return var_table[il .valuei error("gel : undefined variable ". 5); TIle code really is quite simple: go through every Varia ble in var_tabl e (sta rting with lhe first read more..

  • Page - 273

    7.8 VARIAULES Oops! C learly, we meant var2 = 3.2; but we didn't say so (except in the com- ment). We could live with this, but we'll follow the tradition in languages, such as C++, that distinguish declarations (with initializations) from assignments. We cou ld usc doubl e, but for a calculator we'd like something short, so - drawing on another old tradition - we read more..

  • Page - 274

    244 ( HAPTER 7 • CO MP LETI NG A PROGRAM void calculateO { while (dn) try ( cout« prompt; Toke n I = ts.gel(); while (I.kind == print) 1=ls.get() ; if (I. kind == quit ) return ; ts .pulback(t); II first discard all h prjnts ~ II quit cout« result « statementO« endl; } catch (c)(ceplion& e) { } cerr « e.whatO« endl; clean_up_messO: 1/ write error read more..

  • Page - 275

    7.6 VA RI A B LES bool is_declared(string va r) { ) /I is var already in vau.1ble? fo r (int i = 0; i<vauable.sizeO; ++i) if (va r_ta ble[i). name == var) re lurn I.rue; re turn false; do uble d efine_na me(slring var, double val) /I add (va r,va l) 10 vt1 uable ) if (is_d ecla red(va r» eHo r(var," decla red twice"); va r _ta ble. push read more..

  • Page - 276

    , .. C H APTE R 7 • COM P LETING A PROGRAM Note that we returned the value stored in lhe new variable. "1l1at's useful when the initializing expression is nontri vial. For example: let v = d!(t2-tl); 111is declaration will defin e v and also prim its value. Additio nally, priming the value of a declared variable simplifi es the code in calculateO because read more..

  • Page - 277

    7. 8 VAl(lABlES Note first or all Ule call isalpha(ch). lllis call answers ule question "Is ch a letter?" ; isalphaO is pari or the standard library that we get rrom stdJ ib_faci lities. h. For more character classification rUllclions, see §1 1.6. 111e 10glc ror recognizing names is the same as that ror recognizing numbers: find a first character or the right read more..

  • Page - 278

    248 CHAPTER 7 • C OM P LETING A P ROGRAM What must we do instead ? First we must specify precisely what we want a name to be and then we must modify getO to do that. H ere is a workable specifi- cation of a name: a sequence of Icu ers and digits starting with a \ctter. Given this definition, a ab a1 Z12 asdsddsfdfdasfdsa434RTHTDl2345dfdsa8fsd888fadsf arc names read more..

  • Page - 279

    7.8 VARIAB L ES 7.8.3 Predefined names Now that we have names, we can easily predefine a few common o nes. For ex- ample, if we imagine that our calculator will be used fo r scientific calculations, we'd want pi and e. Where in the code would we define t.hose? In mainO before the call o f calculateO or in calculatcO before the loop. We'll put them in mainO read more..

  • Page - 280

    254) (HAPTER 7 • C OMPLETING A PR OG RAM 2. Implementing variables was a major extension . It touched just abou t every fu nction and added a completely new concept to the calculator. It increased the size of the calculator by 451)/0 and we haven't even imple- mented assignm ent! In the context of a first program of significant complexity, the second reaction is read more..

  • Page - 281

    CHAPTER 7 EXERCISES 2. Why docs " 1+2; q" typed into the calculator not quit after it receives an cr!"Or? 3. Why did we choose to makc a constant character ca.lled number? 4. We split mai nO into two separate functions. What docs the new function do and why did we split main() ? 5. Why do wc split code into multiple functions? State principles. 6. read more..

  • Page - 282

    CHAPTER 7 • COM PL ETING A PROGRAM 4. The geCvalueO, seCvalueO, is_d eciaredO, and declare_nameO func- tions all operate on the global variable var_table. Define a elass called SymboUable with a member va' _lable of type veclor<Variable> and member functions gelO, sel O, is_deciared O, and d eciareO. Rewrite the c.:-uculator to usc a variable of type SymboUable. 5. M read more..

  • Page - 283

    '. c.J- . r- 8 Techn ical ities: Functions, etc. "No amount of genius can overcome obsession with detail." - Traditional I n this chapter and the next, we change our focu s from pro- gramming to O Uf main tool for programming: the C++ pro- gmJ1uning language. \OVe prescllllanguagc-technic.1.I demils to give a slightly broader view of C++'s bas ic facilities and to read more..

  • Page - 284

    254 CHAPTER 8 • TECHNI CA LI TIES: FUN CTIONS, ET C. 8.1 Technicalities 8.2 Declarations and definitions 8 .2. 1 Kinds of declarations 8.2.2 Variable iIInd conslant declarillion s 8 .2.1 Def.ull! initialiution 8.5.4 Pass- by-( on sl' r('feren ce 8.5.5 Pass· by-re fe rence B.S.6 Pass· b y-value vs . pass· by-re ' ere"ce B.s.7 Arg ume nt c he c king a nd read more..

  • Page - 285

    8 .2 D EClARATI O N S AND D EFINITIONS l:,tTCCS o f ease - in all ian guagcs. The language technicalities, however, are specific to a given language. Fortunately, program ming langu ages do not develop in a vacuum, so much of what you learn here will have reasonably obvious coumer- parts in other languages. In particular, C++ belongs to a group of languages that read more..

  • Page - 286

    C HAPTER 8 • TE C HNICALITIES; FUNCTIONS , ETC. The compiler will give at least three "undeclared identifier" errors for this: cout, f, and i arc not declared anywhere in this program fragmem. We can get coul de- clared by including the header std_lib_facililies.h,which contains iLS declaration : #include "std_lib_facililies.h " int mainO { coul « f(i )« read more..

  • Page - 287

    8 . 2 DECLARATI O NS AND DEF I NITIONS Every definition is (by definition ©) also a declaration, but only some declara- (ions arc also definitions. Here are some examples of declarations that are not definitions; each must bc matched by a definition elsewhere in the code: double sqrl(do uble); extern inl a; // no fu nction body here /, "extern plus no read more..

  • Page - 288

    258 C HAPTER 8 • TECHNICALITIES: FUN C TION S, ETC. Declarations: Definitions: ,=-=:.::c,.:""---:-:--:-:--:c--, I d o uble sqrl(double d ) ~ ~ouble sqrt(double d) ~ ~ II calculate the I d o uble sqrt<do uble d ) II squa re root of d ) extern int Xi ~ ~==. ==~L _ r- ;"'-x= -7; ----, exte rn ml Xi r-- . Why docs C++ orrer both declarations and read more..

  • Page - 289

    8.2 DECLARATION S AND DEFIN ITI ONS pr imaryO ; 1/ .. do uble expression() ( 1/ ... lerm(); 1/ . \,Ve can order those four fu nctions any way we like; there will always be one call (0 a function defined below it. Somewhere, we need a '; fo rward" declaration. 111ercfore, we declared expressionO before the definition o f primaryO and all is well. Such cyclic read more..

  • Page - 290

    260 C HAPTER 8 • TE C H NICALITIE S: FU NC TI O N S, ET C. 8.2.2 Varia ble and constant declarations ' n lC declaration o f a varia ble or a constant specifics a name, a type, and option· ally an initializcr. For example: int aj double d = 7; veclor< in t> vi(10) ; II no initializcr II initializer using the = syntax /I initializer using the 0 read more..

  • Page - 291

    8 .3 HEADER FILES Because x is uninitialized, executing z>x would be undefined behavior. TIle eom- p<1I;son z>x cou ld brive different results on different machines and different res ults in different nlllS of the program on the sam e machine. In principle, z>x might cause the program to terminate with a hardware error, but most orten that doesn't happen. Instead we read more..

  • Page - 292

    2'2 CHAPTER 8 • TECHNICALITIE S; FUNCTIONS, ET C. us. For example, the implementations of coul and sqrt() were '\!Tiucn by someone else many years ago. We juSt usc them. "nlC key to managing declarations of facilities defined "'elsewhere" in C++ is the header. Basically, a header is a collection of declara tions, I ypically defined in a file, so a header is read more..

  • Page - 293

    8.3 HEADER FI LES /I f.cpp #include "f_ h" int g(int i) { return W ); ) When compiling I.cpp the compiler would do the #include and compile int f(i n!); int g(int i) { return Hil ; Since #includes logically happen before anything else a compiler docs , handling #i ncludes is pan of what is called preprowsillg (§A.17). 10 ease consistency checking, we read more..

  • Page - 294

    264 ( HAPTER 8 • TECHNICALITIE S: FUN CT IONS , ETC. Our std_lib_facililies .h header contains declarations for me standard library facilities we lISC , slich as caut, vector, and sqrt() , togethe r with a couple of simple u tility fUllct io ns, slIch as errorO, that are not part ofth e standard library. In § 12.8 we show how to lISC the standard library read more..

  • Page - 295

    8. 4 SCO P E A local scope: betwecn { . .. } braces of a block or in a function argument lisl A J/a/t11lt!11 / Jloj)(: e.g. , in a for-statement rn l C main pUll)Ose of a scope is to keep names local , so that they won't interfere with namcs declarcd elsewhere. For example : void f( inl xl /I f is global; x is local to f { int z = x+7i liz is read more..

  • Page - 296

    266 C H AP TER 8 • TE C HN ICALITIES: FUNC TIONS , ETC. Yo u find maxO and absO in the standard library, so you don't have to write them yourself. TIle ?: construct is called an ant/llne/ic if or a cQnditiolla! exprt!S1ioll. '11C va lue of (a>=b)la :b is a if a>=b and b Olhcrwisc. A conditional expression saves us from wriLing long-winded code like this: read more..

  • Page - 297

    8.4 SCOPE int fO { int Xi X = 7; { } II local variable lIthe local x intx =y; ++x ; II local X initialized by global y lIthe X from the previous line ++X; II the x from the first I ine of f() relurn I; Whenever you can, avoid such complicated nesting and hiding_ Remember: "Keep it simple!" 111e larger the scope or a name is, the longer and read more..

  • Page - 298

    268 CHAPTER 8 • TECHNICALITIES : FUNCTIONS, ETC. C lasses wiLhin classes: member classes (also called nested classes) class C { public: }; struct M { II . } ; 1/ • •• This tends LO be useful only in complicated classes; remember that the ideal is to keep classes small and sim ple. Classes within functions: local classes void fO { } class L ( II . ); read more..

  • Page - 299

    8. 5 FUN CTION CAll AND RET U RN II . } 1/ ..• Nested blocks are unavoidable, but be suspicious of complicated nesting: it can easily hide errors. C++ also provides a language feature , namespaee, exclusively for expressing scoping; see §8.7. Note OUT consistent indentation to indic."1te nesting. Witho ut consistent in- dentation, nested constructs become unreadable. For read more..

  • Page - 300

    270 ( H APTE R 8 • TECHNICALITIES ; FUN CTI ONS , ETC. which we can control Lhc order of execution. To organize code made Ollt of these primitives, we have fun ctio ns . To do its job, a function usuall y needs arguments, and many functions rctum a resull. ~ntis section focllses on how arguments are specified and passed. 8.5.1 Declaring arguments and return read more..

  • Page - 301

    8 .5 FU NCT ION CAll A ND RET U RN int my_find (vector<slring> vs, string s, int hint) /I search fo r s in vs starting at hint { if (hint<O II vs .sizeO<=hint) hint = 0 ; for (int i = hint; kvs .size O; ++i) II search starting from hint if (vs[il==s) return i; if (o<hint) { II if we didn' t find s search before hi nt for (int i = 0; khint read more..

  • Page - 302

    CHAPTER 8 • TE C HNICALITIES : FUNCTIONS , ETC. Here, the value returned is exactly the value we would have gotten by initializing a variable of type T by a value of type V : VVi II ... T t(V)i /I initial ize t with v 11mt is, value return is a form of initialization. A fu nction declared to return a value must return a value. In particular, it is an read more..

  • Page - 303

    8.5 FUNC TIO N CALL A N D RET U RN 8.5.3 Pass·by·valu. ~n1e simplest way of passing an argument to a function is to give li1e function a copy of the value you lise as the argument. An argument of a function fO is a local variable in fO li1at's initialized each time fO is called. For example: /I pass-by-valuc {give the function J copy of the value passed) read more..

  • Page - 304

    274 CHAPTER 8 • TEC HNI CALI TIE S: FUN C TI ONS , ETC. costly. We should not be obsessed by cost, blll doing unnecessary work can be embarrassing because it is an indication that we didn't directly express o ur idea of what we wamed. Fo r example, we could write a function to print out a vector of floating-point numbers like this: void prinl(veclor<double> read more..

  • Page - 305

    8 .5 FUNC TION CAL L AND RET U RN void prin1(eonsl veclor<double>& v) ( eoul « "{ "; or (inl i = 0: i<v.size(): ++i) ( coul « vO]: /I pass- by-co nst-reference if (i!=v.sizeO-l) coul « ", "; coul « " }\n " ; ) '11e & mean s " reference n and the consl is there to stop printO modifying its ar- gument by accident. read more..

  • Page - 306

    27. C HAPTER 8 • TECHNI CA LITIE S: FUNCT IONS , ETC. void prinl (consl vector<double> & v) { II pass-by-const-referen ce II . .. vii] =7; II . .. II error: v is a const (is nOl mutable) ) Pass-by-const-rcfcrcncc is a useful and popular mechanism. Consider again the my_find O function (§B.S.l ) tbat searches for a string in a vector of strings. Pass- read more..

  • Page - 307

    6 . 5 FUNCTION CAll ANO RETUR N H ere, we wanted init() to modify the argument vector, so we did not copy (did not use pass-by-value) nor declare thc reference const (did not usc pass-by-con st- value), but simply passcd a "plain refer ence" to the vector. Let us cons ider references from a more technical point of view. A refercnce is a construct that allows read more..

  • Page - 308

    278 ( H AP TER 8 • TE CH N ICA LITI ES : FU NC TIO NS , ET C. int main() ( intxx=O; /I write: I coul« f(xx )« endl; coul« xx « e ndl ; /I write: I; fO changed the value of xx int yy = 7; /I write: 8 cout« f(yy)« end!; cout « yy« end l; /I write: 8; fO changed the value of yy ) We can illustra te a pass·by-rcfcrence argu ment read more..

  • Page - 309

    6 .5 FUNCTION CAll AND RETURN 111e standard library provides a swapO for every type that you can copy, so you don't have to write swapO yourself for each type. 8.5.6 Pass·by.value vs. pass·by-referenee \"'hen sho uld you usc pass-by-value, pass-by-rcfercnce, ,md pass-by-const-reference? Consider [lrSt a teclUlical example: void f(i nt a, int& r, eonst int& erl I ++a; read more..

  • Page - 310

    280 CHAPTER 8 • TECHNICALITIES: FUNC T IONS, ETC. g(1, ),,3); /I means: inl _compiler....generated = 3; g( 1 ,y,_compi ler-&eneraled) SUdl a compiler-generated object is called a temporary object or just a IClII/Xffat)'. Our rule of thumb is: I . Use pass·by-value to pass very small objects. 2. Use pass-by-consi-referellcc to pass large objects that you don' t need to read more..

  • Page - 311

    8 .5 FUNCTION CALL AND RETURN void fO { vector<int> VJI:; vector<int> vy ; 1/ read vx and vy from input larger(vx,vy); /I ... U sing pass-by-rcferenee arguments is the o nl y reasonable choice for a function like largerO. It is usuall y best to avoid functions that modify several objects. In theory, there arc always altematives, sLich as returning a class object read more..

  • Page - 312

    282 CHAPTER 8 • TECHNICALITIES: f U NCTI O N S, ET C. Note that to initialize J{ with y, we have to convert an int to a do uble. ~nlC same happens in the call of fO . TIle double value received by fO is the same as the one stored in x. Conversions arc often useful, but occasionally they give surprising results (see §3.9.2). Consequently, we have to be read more..

  • Page - 313

    8 .5 FU NCTION CAll AND RET U RN First, ex pressio nO is completely straightfonvard; it has one argument (Is) and twO local variables (left and I): double e xpressio n(loke n_slream& Is) ( ) do uble left = le rm (ls)j Toke n I = IS. gel OJ 1/ . .. Second . le rmO is much like express ion O, except tha t it has an additional local variable (d ) read more..

  • Page - 314

    284 CHAPTE R 8 • TEC H NICA LI TIES; FUNC TI ONS, ETC. other. You may w a nllO ta ke the opportunity LO rdresh your memory of what the complete expression() , telm O, and primary() looks like, but the salient features as ra r as fu nction call is conccm ed are presented here. When a function is caJlcd , the language implementation sets aside a data read more..

  • Page - 315

    8 .5 FUNCTION CAll AND RET U RN Call o r expression() : Is left I Implementation stufT Call or termO: Is left I d Implementation stuff G ill or primaryO : I. I d Implementation stufT Oireoion or Slack growth 111is is staning to get a bit repetitive, but now prima ryO Gllls expression() : Can or expressionO: G.,11 or lermO: Call or prima ry() : Call or read more..

  • Page - 316

    2. 6 C HAPTER 8 • TECHNICALITIE S: f U N C TI O N S, ET C. So this call of expressionO geLS its own activation record, different from the fi rst c.-til of expressio n(). llmt's good o r else we'd be in a terrible mess, since left and t will be different in the twO calls. A function that directly or (as here) indirectly calls itself is called rmmiue. read more..

  • Page - 317

    8.6 OROE R OF EVALUATION And so on. The stack, also called the call Jtadi., is a data structure that grows and shrinks at one end according to the nile: first in, first out. Please remember that the details of how a call stack is implemented and used vary from C++ implementation to C++ implementation, but the basics arc as outlined here. Do you need to know how read more..

  • Page - 318

    288 ( HAPTER 8 • TECHNICALITIES: FUN CTIONS , ETC . (that is, program_name before v) and destroyed in the reverse order (that is, 'tI be- fore program_na me). \\'hen someone calls fO , first s is constructed ; tha t is, s is initialized to the empty string. It will Jive until we return from roo Each time we enler the block that is the body of the while-loop, read more..

  • Page - 319

    8 .6 O RDER OF EVALUATION /I file fl.epp inlx1=1 ; int y1 = x1+2; /I Y 1 becomes 3 111is initialization logically takes plaee "before the code in main O is exeeuled." Using a global variable in anything but the most limited circumstances is usu- ally not a good idea. We have mentioned the problem of the progranuner having no really elTective way of knowing read more..

  • Page - 320

    290 C HAPTER 8 • TECHNICALITIES: FUNCTIONS, ETC. const Oate& defa ult_dateO { ) slatic consl Dale dd (1970,1,1); return dd ; /I initialize dd first time we gel here A sialic local variable is initialized (constructed) only the first time its fUllction is called. Note that we returned a reference to eliminale unnecessary copying and, in particular, we returned a const read more..

  • Page - 321

    8 .7 NAMESPACE S member. Graph_lib is a sliglllly ugly name; we chose it because the "pretty and obvious " name Graphics had a greater chance of already being used somewhere. Let 's say thm your Text was part of a text manipulatio n library. '11e same logic that made us put our graphics facilities into namespace Graph_lib should make you put your text read more..

  • Page - 322

    292 using std : :slring; using sid : :co ul ; 1/ .. . CH APTER 8 • TE CH N ICA LITIES: FUN CTI ONS, ETC. 1/ string means std::slring II cout means std::cout That construct is called a using declaration; it is the progranuning equivalent to lIsing plain "Greg" to refer to Greg Ha nsen, when there are no other Cregs in the room. Sometimes, we prefer an read more..

  • Page - 323

    C H APTE R 8 DR i l l string name; co ut « "Please enter your first name\n"; d n » nam e; cout « "He llo, " « name« '\n'; \Ve promise never LO do that for any namespaec except std . ...; Drill I. Create three flies: my.h, my.c pp, and use .cpp . The header me my.h contains extern int foo ; void prinUooO; void prinl(inl) ; TIle read more..

  • Page - 324

    C H APTER 8 • TECHNICALITIES : FUNCTIONS, ETC. doubl e dll = 7.7; doubl e dy = 9.9; swap_l(dll,dY)j swap_l{dll,dY)j Which calls compiled, and why? After each swap that compiled, print the value of the arguments after the caU to see if they were actually swapped. If you arc surprised by a result, consult §a.6. 3. Write a program using a single me containing three read more..

  • Page - 325

    C HAPTER 8 TERMS 8. What good docs in den tation do? 9. \"'hat arc h eader fil es used for? 10. \"'hat is the scope of a declaration? II . What kinds of scope arc there? Give an example of each. 12. What is the difference ben"een a class sco pe and local scope? 13. \Vhy should a programmer minimize the number of global varia bles? 14. What is the read more..

  • Page - 326

    CHAP TER 8 • TEC H NICA LITI ES: FUNC TI ONS , ETC. Exercises I. Modify the calculator program from Chapter 7 to make the input stream an explicit parameter (as shown in §8.5.8). Also give the Token_stream constructor and isfream& parameter so that when we fi gure out how to make our own istreams (e.g. , attached to fil es), we can usc the calculator for read more..

  • Page - 327

    C HAPTER 8 PO ST SC RIPT 11. Write a function man'O that relUrns the largest element of a vecto r argument. 12. Write a function that finds the smallest and the largest elemelll of a vecto r argument and also computes the mean and the median. Do not use global variables. Either return a slruct containing the results or pass them back through reference arguments. read more..

  • Page - 328

    read more..

  • Page - 329

    Technicalities: Classes, etc. "Remember, things take time." -Piet Hein I n this chapler, we keep our focus on OUT main tool for pro- gramming: the C++ programmin g language. We present lan- guage technicalities, mostly related to user-d efin ed types, that is, to classes and enumerations. Much o f the presentation o f lan - guage featu res takes the fo rm o f read more..

  • Page - 330

    300 CHAPTER 9 • TECHNI CA LITIE S: ClASSES, ETC. 9.1 User·defined types 9.2 Classes and members 9.3 Inle rface and implementation 9.4 Evolving a class 9.4.1 shuct and functions 9.4.2 Member functions ilnd constructors 9.4.3 Keep d("lails private 9.4.4 Defining member functions 9.4.5 Referrin g 10 the current object 9.4.6 Reporting errors 9.1 User-defined types 9.5 read more..

  • Page - 331

    9. 2 ( LASSES AND MEMBE RS Repre~71latioTl: A type "knows" how to represent the data needed in an object. Ojx mli01u: A type "knows" what operations can be applied to objects. Many ideas follow this patlern: "something" has data to represent its curre nt value - sometimes called the cun"Cnt Jlale - and a set of operations that can be read more..

  • Page - 332

    302 CHAPTER 9 • TECHNICALITIES: CLA SSE S, ETC. operations on such objects. We access members using the objcd.membt'r notation. For example: X va,; var.m = 7; int x = var.mr(9)i /I var is a variable of type X /I assign to var's data member m 1/ call var's member function mf() You call read var.m as var's m. Most people pronoullce it "vaf dOl m" or read more..

  • Page - 333

    9 .3 I N TERFA CE AND IM PLEMENTATIO N class X { private : ); so thai X x; int mf(int) ; 1/ . .. int y = x.mfO; II variable )[ of Iype X 1/ error: mf is private (i.e., inaccessible) A user cannot d irectly refer to a private member. Ins tead, we have to go through a public function that can usc it. For example: class X ( int m; int mf(int); read more..

  • Page - 334

    304 CHAPTE R 9 • TE CH NICA LITI ES ; CLASS ES, ETC. stru cts arc primarily used for data structu res where the members can take any value ; that is, we can 't define a ny meaningful invariam (§9.4 .3) . 9.4 Evolving a class Let 's illustra te the language facilities supporting classes and the basic techniques for using them by showing how - and why - read more..

  • Page - 335

    9.4 EVOLV I NG A CLASS /I set today to December 24, 2005 loday.y = 2005; loday. m = 24 ; loday. d = 12; 111is is tedious and eITOr·pronc. Did you spOt the crror? Everyt hing tha t's te· dious is error·pronc! For examplc, does this make sense? Date Xi x.y =-3; x.rn = 13; x.d = 32i Proba bly not, and nobody would write that - or would they? How about read more..

  • Page - 336

    ( I-lAPTER 9 • TE CH NICA LITIE S: CLA SS ES, ETC. void fO ( } Dale loday, iniCday(today, 12, 24, 2005), add _day(loday,1) , II oops! (no day 2005 in year 12 ) Hrst we note the usefulness of such "operations" - here implemented as helper fu nctions. Checking that a da te is valid is sufficiently difficult and tedious that if we didn't write a checking read more..

  • Page - 337

    9.4 EVOLV t NG A C LASS a day by simply adding 1 to its member d is a time bomb : when today is the last day of the mamh the increment yields an invalid date. The worst aspect of this '·very bad code" is thaI it doesn't look bad . 111is kind of thinking leads 10 a demand for an initialization function thaI can 't be forgotten and for operations that read more..

  • Page - 338

    308 CHAPTER 9 • TEC HNI CALI TI ES: CLASSES, ETC. Notc that the member funClion add_dayO is called for a particular Da te using the dot member-access notation. We'll show how to define member functions in §9.4.4. 9.4.3 Keep details private We still have a problem: What if someone forgets to usc the member functio n a dd_dayO ? What if someone decides to change read more..

  • Page - 339

    9.4 EVOLV I NG A CLASS ~nle notion of a "valid Date" is an important special case of the idea of a valid value. We try to design our types so that values are guaranteed to be valid : that is, we hide the representation , provide a constructor that creates only valid ob- jects, and design all member functions to expect valid values and leave only valid read more..

  • Page - 340

    310 ( H APTER 9 • TECHNICALIT IES: C LASSES , ETC. looks reasonable and if the implementer used sollle technique that we could learn from. However, unless we arc the impicmcntcrs, we do lend to spend much more time with lhe public interface. The compiler doesn't care about the order of class members; it takes the declarations in any order you care to prcscl1llhcm. read more..

  • Page - 341

    9.4 EVOLV I NG A C LASS and int x=2; II define and immediately inilial ize with 2 For consistency, it is even possible to express that last initialization using the "arb"LIt11ent"!parcnthesis notation: int x(2); /I initialize x with 2 Date sunday(2004,8,29); /I initialize sunday with (2004,8,29) vVe can also derine member functions righ t in the class defmirion: read more..

  • Page - 342

    312 CHAPTER 9 • TECHNICALITIES: CLASSES , ETC. Note that monthO can refer to m even though m is defined after (below) month() . A member can refer to another member of its class independently of where in the class that Olhcr member is declared. The mle that a name must be declared before it is lIsed is relaxed within the limited scope of a class. Writing the read more..

  • Page - 343

    9.4 EVOLV I NG A C LA SS to identify the object for wruch it is called. So in the first cail , m correctly refers to dl .m and in the second call it refers to d2. m. See § 17.10 for more uses of this im· plicit argument. 9.4.6 Reporting errors ' '''hat do we do when we find an invalid date? \"'here in the code do we look for invalid dates? read more..

  • Page - 344

    314 C HAPTER 9 • TECHNICALITIES: ClASSES , ETC. vo id fCi n t x, int y) try ( ) Date d xy(2004,x,y); coul « dxy« '\n ' ; d xy.add_day(2); ca lc h(Date :: Invalid) ( error(" invalid da te n); ) 1/ see §9.8 (or J declaration of « II e rrorO defined in §5 .6.3 We now know that « and add_da teO will have a valid Date on which to operate. read more..

  • Page - 345

    9 .5 ENUMERATIONS enum Day { monday, tuesday, wednesday, thursday, friday, saturday, s unday ); Here monday==O and s unday==6. In practice, staning with 0 is often a good choice. Vile c..,n lise our Month like lills: Month m = feb; m =7; int n = m j Month mm = Month (7)j /I error: can't assign an int to a Month /I OK: we can get (he numeric value of a read more..

  • Page - 346

    31. C H APTER 9 • TECHNICA LITI ES: ClA SS ES , ETC. we try to represent sets of alternati ves (up, down ; yes, no, maybe ; on , off ; n, ne, e, se, 5, SW, w , nw) o r distincti ve values (red, blue, green , yellow, maroon, crim- son, blac k). Note that an e numerator is /lot in the scope of its enumeration type; it is in the sallle scope as read more..

  • Page - 347

    9 .6 OPERATOR OVERLOADING ~nle ? : constmct is an "arithmetic if": m becomes Jan if (m==Oec) and Month (m+l ) otherwise. It is a reaso nably elegant way of expressing lhe fact that months "wrap around" after December. TIle Month type can now be used like this: Month m = sepi ++m; /I m becomes Dcl ++m; ++m; ++m; /I m becomes Nov /I m becomes Dec read more..

  • Page - 348

    318 CHA PTER 9 • TECHNI CALITIE S: ClA SS ES, ET C. only with their conventional meaning: + should be addition, binary · multiplica- tion, [J access, () call, etc. This is just advice, not a language rule, but it is good advice: conventional lise of operators, slich as + for addition. can significantly help us understand a program. After all, such lI SC is the read more..

  • Page - 349

    9.7 CLASS INTERF AC ES 9.7.1 Argument types ''''hcn we defincd the conStlUCLOr for Date in §9.4.3, wc uscd threc ints as thc ar· b'umcnlS. 1nat caused somc problcms : Date dl(4,5,2005); Dale d2(2005,4,5); /I oops: year 4, day 2005 /I April 5 or May 4? 111C first problem (an illegal day of !.he month) is easily dealt with by a test in the constnlctor. However, read more..

  • Page - 350

    320 C H APTE R 9 • TE C H NICALITIES: ( LASSES. ET C. This takes care of most "accidents." Note the usc of the q ualifi cation of the cnLl- mc ralor ma r with the class na me Date : Date:: mar. This is the way we say thaI it's Date's mar. \<\'c don't say Date.mar because Da le isn't an o bject (it's a type) and ma r isn' t a data read more..

  • Page - 351

    9 . 7 ClASS INTERFA C ES Now we get Date dx1(Year(1998), 4, 3); Date dx2(Year(1998), 4 , Date: :mar); Dale dx2(4, Date: : mar, Year(l998)); Dale dx2(Dale: :mar, 4 , Year(1998)); Dale dx3(Year(1998), Dale: :mar, 30); II error: 2nd argument not a M onth /I error: 2nd argument not a Month /I error: 1 st argument nOI a Year II error: 2nd argument not a Month II OK read more..

  • Page - 352

    322 CHAPTER 9 • TECHNICALITIES: CLA SSES, ET C. holiday = Oate(1978, Date: :dec, 24); d3 = holiday; II assignment This will all work as expected. TIle Oa le(1978, Datc : :dec, 24) notation makes the appropriate unnamed Date object, which you can then use appropriately. For example: cout« Dale(1978, Da te: :d ec, 24); 111is is a usc of a constructor that acts much read more..

  • Page - 353

    9 . 7 CL A SS INTERFAC ES For a type T, TO is the notation for the defaull value, as defmed by the default constmcLOr, so we could write string sl = string() ; veclor<string> v1 = veclor<string>O; /I default value: Ihe empty string ·" II default value: veclor<siring> v2(10,string()) ; II the empty vector; no elements II vector of 10 default strings read more..

  • Page - 354

    32. CHAPTER 9 • TECHNI CA LI TI ES ; CLASSES, ET C But we don't think that's particularl y pretty. For siring, '''' is rather obvious for "em pty string." For vector, 0 isn't t OO obscure fo r "empty vectO r." H owever, for many Iypes, it is not easy to find a reasonable notation for a default value. For ma ny types, it is ben eT to read more..

  • Page - 355

    9 .7 C LA SS INTER FAC ES Dale:: DaleO : y(default_dateO. yea rO), m(defauIL dateO.mo nlh O), d(d efaull_daleO . day(» Note that the default constructor does not need to check its value; the construc- tor for default_date already did that. Given this default Dale constructor, we can now have vectors of Oates: vector<Dale> birlhd ays(10); Without the default cons tnlctor, read more..

  • Page - 356

    326 CHAPTER 9 • TECHNICALITIES: CLASSES , ETC. class Dale ( public: 1/ . .. jnt dayO const; Month m onth() co nst ; jnt yea r() const; void add _day(int n); void add_m o nth(int n); void add_yea r(int n )i private : jnt Yi /I year II const member: can', modify the object II const member: can', modi fy the object II const member: can', modify the object /I read more..

  • Page - 357

    9 ,7 CLASS INTERFAC ES nonmcmber function) should be implemcnted outside th e class. That way, a bug in that function cannot directly corrupt tllC data in a class object. Not accessing the rcprcsemation is impo rtant because the usuaJ debug technique is "round up thc usual SUSPCCIS n ; that is, when sometlljng goes wrong with a class, we first look at the functions read more..

  • Page - 358

    32. CHAPTER 9 • TECHNICALITIES: CLASSES, ETC. Helper functions arc aJsa called amveniena jimetians, auxiliary fiwetiolls, and many other things. TIle distinction between these functions and other nonmember functions is logical; that is, "helper function" is a design concept, not a program- ming language concept 'The helper functions often take arguments of the classes that read more..

  • Page - 359

    9.8 THE DATE CLASS public: enum Month ( jan=l , feb, mar, a pr, may, jun, ju l, a ug, se p, oct, nov, dec ); class Invalid {}; /I to throw as exception Date(int y, Month m, int d); II c heck for valid date and initialize DateO ; II default constructor /I the deiault copy operations are fine I/nonmodifying operations: int dayO ca nst { return d; ) Month read more..

  • Page - 360

    330 CHAPTER 9 • TE CH NICA LITIE S: CLA SS ES, ETC. /I Chrono.cpp nam espace Chro no { 1/ member function definitions: Oate:: Da te (inl yy, Mo nth mm, int dd ) : y(yy), m (mm), d (dd ) { if (! is_date(yy,mm,dd» throw Invalid ()i } Date& defa ult _dateO ( } static Date dd(2001 ,Date : :ja n,1); II start of 21 51 century return dd ; Date:: read more..

  • Page - 361

    9.8 THE DATE CLASS /I helper functions: bool is_dalc(inl y, Dale::Month m, int d ) ( II assume that y is valid if (d<=O) r e turn false; II d must be positive int days_in_month = 31; II most months have 3 1 days switch (m) { case Date: :feb : li the length of February varies daysj n_month = (leapyear(y» 129:28; break; case Date : :ap r: case Date: :jun : read more..

  • Page - 362

    JJ2 CHAPTER 9 • TECHNICALITIES : CLA SS ES , ETC. ) return os« '(' « d .yearO « ',' « d .month () « ' ,' « d .dayO« 'I' ; istream& o pe ra tor» (islream& is , Datc& dd) { int y, m, d ; char c hl, ch2, ch3, c h4; is» chl » y » c h2» m » chJ » d » c h4i if (! is) return is; if (c hl != '(' II ch2 !=', ' read more..

  • Page - 363

    ( H AI' TER 9 TE RMS ~ Drill 1l1is d rill simply involves geuing the sequence of versions of Date to work . Fo r each version defin e a Date called today initialized lo J une 25, 1978. Then, define a Date called tomo rrow and give it a value by copying today into it and increas- ing its day by one using add_dayO . Finally, output to day and to mo rro read more..

  • Page - 364

    CHAPTE R 9 • TECHNICAllTI ES: CLASSES, ETC. Exercises 1. List sets of plausible operations for the cxamplcs of rcal-world objects in §9.1 (such as toaster). 2. Design and implement a Name_pairs class holding (name,age) pairs where name is a string and age is a do ubl e. Represent lhat as a vector<5tring> (called name) and a vector<double> (called age) member. read more..

  • Page - 365

    CHAPTER 9 EX ERC I SES from the chapter. Make a veClor of Transactio ns. Create functions to add books to the library, add patrons to the library, and check Olll books. Whenever a user checks o ut a book, have the library make sure that both the user and the book arc in the library. If they aren' t, report an error. Then check to make sure that the user read more..

  • Page - 366

    CHAPTER 9 • TE CH NIC ALITIE S: CLA SSES , ETC. Postscript There is a lot to user-defined types, much more than we have presented here. User·defined types, especially classes, are the heart of C++ a.nd the key to many of the most effective design techniques. Most of the rest of the book is about the design and use of classcs. A class - or a set of classes read more..

  • Page - 367

    Part II Input and Output read more..

  • Page - 368

    read more..

  • Page - 369

    \ 1. '-'0 Input and Output Streams "Science is what we have learned about how to keep from fooling ourselves." -Richard P. feynman I n this chapter and the next, we presem the C++ standard library facilities for handling input and output from a variety of sources: I/O streams. We show how to read and write files, how to deal with errors, how to deal with read more..

  • Page - 370

    340 C HAPTER 10 • INPUT AND OUTPUT STREAMS 10.1 Input and output 10.2 The 110 stream model 10.3 Files 10.4 Opening a file 10.5 Reading and writing a file 10.6 110 erro r handling 10.7 Reading a single value 10.7.1 Breaking the problem into manageable parts 10.8 User-defined oulpul operators 10.9 User-de fin ed input ope rators 10.10 A sta ndard inpulloop 10.11 read more..

  • Page - 371

    10 . 2 THE I/ O STRE AM MODEl When a model like tlus is used, all input and all output can be seen as streams of bytes (characters) handled by the input/output library. Our job as programmers of an application then becomes 1. 1b set up 110 streams to the appropriate data sources and destinations 2. To read and write fromlto those StreanlS 11le details of how read more..

  • Page - 372

    342 CHAPTER 10 • INPUT AND O UTP UT STREAM S We can represent an ostream graphically like this: Values of various types Character sequences ;';Somewhere" (12,34) osloeam Buffer TIle buffer is a data stnlcturc that the ostream uses intcmally to store the data you give it while conUllUnicaling with the operating system. If you notice a "delay" be- tween your read more..

  • Page - 373

    10 .3 FIl.ES One of the m~or uses of output is to produce data for humans to read . 111ink o f email messages, scholarly articles, web pages, billing records, business reports, contact lists, tables of contents, equipment status readouts, etc. There- fore, oslreams provide many features for fOfll13tting text to suit various tas tes. Similarly, much input is wTitten by humans read more..

  • Page - 374

    344 CHAPTER 10 • INPUT AND OUTPUT STREAMS with tha l assumption, and other representations afC not that hard to deal with. We also talk as if all rues were on disks (that is, on rotating magnetic storage). Again, that's not always so (think of fl ash memory), but at this level of program- ming the actual storage makes no difference. TImt's o ne of the beauties read more..

  • Page - 375

    10.4 OPENING A FilE (rom a C++ string. Such C -style strings arc required by many system interfaces. l11e test o( !isl checks that the me was properly o pened. After that, we can read (rom the file exactly as we would (rom any otller istream. For example, assuming that the input operator, » , was defin ed for a type Point , we could write vecto r<Poi nt> read more..

  • Page - 376

    C HAPTER 10 • INPUT AND OUTPUT ST REAMS You can also perform explicit open () and close() operations (§B.7. I). However. relying on scope minimizes the chances of someone trying to usc a file stream be- fore it has been aU.ached to a stream or after it was closed. For example: ifslream ifs; /I . . . ifs » foo; /I . . ifs.open(name.ios_base:: in); /I . .. read more..

  • Page - 377

    10.5 READING AND WR ITING A FILE o 60.7 1 60.6 2 60.3 3 59.22 "n lis dma fLle contains a sequence of (hour of day,lempermure) pairs. '11e hours are numbered 0 to 2J and the temperatures are in Fahrenheit. No funher fomlatling is ass umed ; that is, the file docs not contain any special header information (such as where the reading was taken), units for the read more..

  • Page - 378

    348 CHAPTER 10 • INP UT AND OUTP UT STREAM S The resulting program would then be reading the original temperature rcading me and producing a new me with the data in (hour,tcmperature) formal. Because the fil e streams automatically close their mes when they go Ollt of scope, the complete program becomes #include "sld_lib_facilities.h " slruel Reading ( 1/ a read more..

  • Page - 379

    10 .6 1/ 0 ERROR H ANDLING standing instructions, mistyping, letting the cat walk on the keyboard , etc.), be· cause fil es fail to meet specifications, because we (as programmers) have the wro ng expectations. etc. The possibilities for input errors are limitless t However, an istream reduces all to four possible cases, called the Jlream slate: Stream states goodO eof() read more..

  • Page - 380

    35() C HAPTER 10 • INP UT AND OUTPUT ST RE AMS Here is an example of how we might use the stream state. Consider how to read a sequence of integers that may be terminated by the character · or an "end of file " (Clrl+Z on Wmdows, Orl+D on Unix) imo a vector. For example: 1 23 4 5* 1l1is could be done using a function like this: void read more..

  • Page - 381

    10.6 110 ERROR HANDLING bad O state is unlikely. Most callers won't bother. TIlis implies that in almost an cases the only thing we want to do if we encounter badO is to throw an excep- tion. 'lb make life easier, we can tell an istream to do that for us: /I make ist throw if it goes bad ist. except ions(ist .except io nsOlios_base : : badbit); '11e notation read more..

  • Page - 382

    352 C HAPTER 10 • INPUT AND OUTP U T STREAMS arc much rarer for outpullhan for input, so we don't do it as o ften. For programs where output devices have a morc significant chance of being unavailable, filled , or broken, we would test after each output operation just as we test after each input opcralion . 10.7 Reading a single value So, we know how to read more..

  • Page - 383

    10 .7 READING A SINGL E VAlUE I. TIle user typing an out·of·range value 2. Getting no value (end of fil e) 3. "Ille user typing something of the wrong type (here, not an integer) ' \That do we want to do in those three cases? l1lat's often the question when writing a program : what do we really want? Here, for each of those three errors, we have three read more..

  • Page - 384

    354 ( HAPTER 10 • INPUT AND OUTPUT ST REAM S whil e (true) { dn » n ; if (cin ) { II we gal an integer; now check it if (1<=n && n<=10) break ; coul « "Sorr y" « n « " is not in the 11:10] range ; please tr y again\n "; ) else if (ein .rail ()) ( cin .dear() ; II we found somethi ng that wasn 't an integer II read more..

  • Page - 385

    10 .7 READ I NG A SINGLE VA LU E while (ci n»ch)( II throwaway non-digits if (isdigit(ch)) { cin .ungetO; II put the digit back, II so that we can re.ld the number relurn ; } } erro r("no input "); /I eof or bad: give up Given the skip_Ioj nlO "utility fun ction," we can write co ut « "Please ent er an integer in the range 1 10 10 read more..

  • Page - 386

    356 } C H APTER 10 • INPU T AND OU T PUT STR EAM S if (cin » n ) return n ; cout « ~ So rr y, tha t was no t a numbe r; please try agai n\n "; skip_loj nl(); Basicall y, geU nlO stubbornly keeps readi ng lIntil it finds some digits lha t it can interpret as an imeger. If we wam to get out of geU nln, we must supply an inte- ger read more..

  • Page - 387

    10.8 USE R- DEFINED OUTPUT OPERATORS int strength = getj nt(l , 10, "ente r strength ", "No t in range, tr y again "); co ut « "strength : "« strength « endl; int altitude = geU nt(O,50000, "Please ent er altitude in fee t", "Not in range, please tr y again "); co ut « "altitude : " « altitude « " f read more..

  • Page - 388

    358 C HAP TER 10 • INP UT AND OUTPUT STR EAMS looks d ifferent from what a « provides, we can simply bypass the « and write OUI the individual parts of the lIser-d efmed type the way we h appe n to like them in ollr a pplicatio n. Here is a simple output operator for Dale from §9.8 that simply prints the year, month, and day comma-separated in read more..

  • Page - 389

    10 . 10 A STANDAR D INPUT lOOP 10.9 User-defined input operators Defining the input operator, » , for a given type and input fonnat is basicaUy an exercise in error handling. It can therefore be quite tlicky. Here is a simple input operator for the Date from §9.8 that will read dates as written by the operator « defined above: istream& operator»(islream& is, read more..

  • Page - 390

    360 (HAPTER 10 • INPUT AND OUTPUT STR EAM S could read a file from its beginning until cnd of file. That can be a reasonable as- sumptio n, because we often apply separate checks to cnsure thal a file is valid. However, we often want to check ollr reads as we go along. Here is a general stra tegy, assuming that ist is a n istream : My_lype var; while read more..

  • Page - 391

    10. 11 READIN G A ST RUC TURED FI LE readings containing daily readings, containing hourly readulgs, etc., so we'll keep considering the possibility of a tenuinating character. U nfortunately, that code is still a bit messy. In particular, it is tedious to re· peat the te rminator test if we read a lot of fil es. We could write a function to deal with that : /I read more..

  • Page - 392

    362 C HAPTER 10 • INP U T AN O OUTPUT STR EAMS A year holds months (of days of readings). A month starts with { month followed by a three-letter month name, such as jan , and ends with }. A reading holds a lime and a temperature. A reading starts with a ( followed by d ay of the month. ho ur of the day, and lcmperaLUre and ends with a ). For read more..

  • Page - 393

    10.11 READI NG A STR UC TURED FIL E match the way we think aboLit temperatures and weather in general: Month holds a month's worth of information and Year holds a year's worth of infonna- tion. But what about Reading? TImt's a low-level notion matching some picce of hardware (a sensor). 111e data of a Reading (day of month, hour of day, tempera- ture) is read more..

  • Page - 394

    CHAPTER 10 • INPUT AND OUTP U T STRE AMS stru ct Month { 1/ a month of temperature readings int mo nth ; 1/ [0 :11[ January is 0 vector<Oay> day; 11 [1 :31[ one vector of readings per day Mo nth O 1/ at most 3 1 days in a month (daylOI wasled) :mo nth (no t_a_monlh ), day(32) {} ) ; stru ct Yea r ( 1/ a year of temperature readings, read more..

  • Page - 395

    10 . 11 READING A STRUC TURED FILE } } is.clear(ios_base : :failbit) ; return is; char ch2; int d ; int h; double I ; is » d » h » t »ch2; if (! is II ch2!=')') error(tlbad reading"); r.day = di r.hour = h; r.temperature = t i return is; /I messed-up reading Basically, we check if the fomml begins plausibly, a nd if it doesn't we set the fil e read more..

  • Page - 396

    366 } int duplicates = 0; int invalids = 0; while (is» r) { if (is_valid (r)) { C H APTE R 10 • INPU T AND OUTPUT STREAMS if (m .day(r.day] .hour(r. hour] ! = nOI_a_reading) ++duplicates ; } } else m.day[r.day]. ho ur[r. ho ur] = "tempera ture; ++invalids; if (invalids) e rror(" invalid readings in m o nth " ,inva lids); if (duplicates) e rror read more..

  • Page - 397

    10 . 11 READIN G A STR U CTURED FILE char chi is» Chi if (ch!='{ ') ( ) is. unget(); is.ciear(ios : : failbit) ; return is; siring year_marker; int yy; is» year_marker » yy; if (!is II yea r_marke r! ="year") error(" bad start of year"); y.year = yy; while (lrue) ( Month m; /I get a clean In each time around if(!(is» m» break; y. mo read more..

  • Page - 398

    368 CHAI)TE R 10 • INPU T AND OUT PUT STREAM S Month m ; w hile (is» m ) ( y. m o nth (m .month] = m ; m = Month (); I/"reinitialize" m } Let 's try to usc it: 1/ open an input file: cout « "Please ent er input fil e name\n"; string name; dn » na me; ifs lream ifs( na me,c_slr(»; if (!irs) e rro r(" can'l o pe n read more..

  • Page - 399

    10. 11 READI NG A ST RUCT U RE D FlU else if (s==" fe b ") m =2; ~n lis is not just tedious; it also builds the names of the months into the code. It would be better to have those in a table somewhere so that the main program could stay unchanged even if we had to change the symbolic representation. We decided to represent the input representation read more..

  • Page - 400

    37. C H A I'TER 10 • INPUT A ND OU TP U T STREAM S void ini C prinUbl{veclor<slring>& fbi ) /I initialize vec tor of output representations { ) tbl . p ush_back( " Jan u a ry"); fbi. p ush_back(" Fe bruary"); Ibl .push_back( " March "); tbl .push_back(It April "); tbl .push_backC" May") ; thl .push_backC"June "); tbl . read more..

  • Page - 401

    C HAPTER 10 REVIEW .../' Drill l. Stall a program to work with points, discusscd in § IO.4 . Begin by defin- ing the data type Point that has two coordinate members x and y. 2. Using the code and discussion in §10.4, prompt the user to input seven (x,}) pairs. As the data is entered, store it in a vector of Poin ls called original_points. 3. Print the data in read more..

  • Page - 402

    Terms bad O buffer clearO closeO device driver eofO failO filc Exercises (HAPTER 10 • INPUT AND OUTPUT STREAMS good O ifslream input device Lllput operator ioslream islream of sire am ope nO o slream output device output operator so"Cam state structured file tenumator ungelO 1. Write a program that produces the sum of all the numbers in a file of whites read more..

  • Page - 403

    CHAI)TER 10 POSTSCRIPT 11. Write a program that produces the sum of all the whitespace-separ;ued integers in a text fil e. For example, "bears: 17 elephants 9 end " should output 26. 12. Write a program that given a me name and a word outputs each line that contains that word together with the line number. I-Unt: getlineO. Postsc ript Much of computing involves read more..

  • Page - 404

    read more..

  • Page - 405

    'el- f" 11 Customizing Input and Output "Keep it simple: as simple as possible, but no simpler." -Albert Einstein I n this chapter, we CQllccmrate on how to adapt the general iOSlrea m framework prescmcd in Chapter 10 to specific needs and tastes. This involves a lot o f messy details dictated by human sensibilities to what they read and also practical co read more..

  • Page - 406

    37' C HAP TER 11 • CUSTOM IZING IN P U T ANO OU TP UT 11 .1 Regularity and irregularity 11.2 Output formatting 11 .2.1 Inl eger o utput 11 .2.2 Inl eger input 11 .2.3 Floalin g-poinloutput 11.2.4 Precis ion 11 .2.5 Fie ld s 11 .3 File o pe ning and positioning 11 .3.1 File open modes 11.3.2 Binary files 11 .3.3 Positioning in files 11 .4 String streams read more..

  • Page - 407

    11 .2 OUTPUT FORMATT ING from ( 1.2467) and totally d ifferent from 1.25 (in financia.l documents, parentheses arc sometimes used to indicate losses, that is, negative vaJues). As programmers, we aim at making our output as clear and as close as possible to the expectations o f th e "consumers" of our p rogram. Output streams (ostreams) provide a variety o f ways read more..

  • Page - 408

    378 C HAPTER 11 • CUSTOMIZING INP U T AND OUTPUT The notations « hex and «oct do not output values. Instead , « hex informs the stream that any further imeger values should be displayed in hexadecimal and « oel informs the stream that any further integer values should be dis- played in octal. For example: coul « 1234« '\1' « hex « 1234 « '\1' « oct read more..

  • Page - 409

    11.2 O U TPUT FO RMATTING coul « 1234 « '\1' « Ox4d2« '\1' « 02322« '\n '; In decimal form, this will prim 1234 1234 1234 As you might have noticed, showbase pcrsislS, just likc oel and hex. l11c manip· ulator noshowbase rcverscs the action of showbase, reverting to thc default, which shows each numbcr without its base. In summary, thc integcr Olltput read more..

  • Page - 410

    CHAP TER II • CUSTOM IZ ING INPU T AND OUTPUT TRY THIS Complete the code fragment above to make it into a program. Try the sug- gested input; then type in 1234 1234 1234 1234 Explain the results. Try other inputs to see what happens. You can get » to acce pt and correctly interpret the 0 and Ox prefixes. To do that, you "unsct" all tlle defaults. read more..

  • Page - 411

    11 . 2 OUT PUT FO RMATTING 1234.57 1234.567890 1.234568e+003 (gene ral ) (fixed) (scientifi c) The manipulators fixed and scie ntific are used to select floating·point formats. Curiously. the standard library doesn't have a general m anipuialOr to give the default format. H owever, we ean define o ne, as we did in s td ~l ib_facilities.h . "111is doe s requi re read more..

  • Page - 412

    382 CHAPTER 11 • CUSTOMIZING INPUT AND OUTPUT 11.2.4 Precision By default, a floating.point value is primed using six lotal digits using the ge ne ra l format. The most ap propriate forma l is chosen and the number is rounded to give the best approximatio n that can be printed using only six digits (the default precisio n for the ge ne ral form). For example : read more..

  • Page - 413

    11 .2 OUTP U T FORMATTING 111is prints (note the rounding) 1234.57 1234.567890 1.234568e+OO3 1234.61234.56789 1.23457e+OO3 1234.5679 1234.56789000 1.23456789e+OO3 ~nl e precision is dcfined as: Floating·point precision general scientific fixed precision is the 10lai number of digils precision is the number of digits after the decimal point precision is the number of digits after the read more..

  • Page - 414

    384 CHAPTER 11 • CUSTOMIZING INP UT AND OUTPUT Fields can also be used for £1oaling-point numbers and strings. For example: co ut « 12345 «'1'« setw(4) « 11345 « 'I' «setw(8) « 12345« 'I' « 12345 « "!\n"; co ul « 1234.5 «'1'« setw(4)« 1234.5« 'I' «setw(8) « 1234.5« '1'« 1234.5« "1\11 "; co ut « "asdfg" « '1'« selw(4) read more..

  • Page - 415

    II .) FILE OPENING AND POSITIONING 11 .3.1 File open modes YOll can open a file in one of several modes. By default, an ifstream opens its file for reading and an of stream opens its file for writing. 111at takes care of most common needs. However, you can choose betwee n several alternatives: Filestream open modes ios_base : :a pp ios_base: :ate ios_base: :binary read more..

  • Page - 416

    386 CHAPTER 11 • CUSTOMIZING INPUT AND OU TP UT Note that typically, an operating system will create a new file if you try to open a nonexistent file for outPUL, but (fortunately) not if you ul ' to open a nOIl- existent file for input: o f stream ofs(" no-s uch. file "); o f sire am ifs(" n o -fil e·of·this· nam e ") i /I create new read more..

  • Page - 417

    11 .3 FI LE OPENING ANO POSITIONING ostream takes an object of a specified type and trans fonns it into a sequence of characters which it writes alit. However, it is possible to reques t istream and oslream to simply copy bytes to and from fi les. 'l113t's called bliltlry /10 and is re- quested by opening a me with the mode ios_base: : binary. H ere is an read more..

  • Page - 418

    388 C HAPTER 11 • C U ST O M I ZING I NP U T AND OU TP U T In both cases, we chose the trickier, but often more compact, binary representa- tion. When we move from character-oriented 110 to binary I/O we give up our usual » and « operators. Those operators specifically turn values into charac- ter sequences using the default conventions (e.g., the string read more..

  • Page - 419

    I 1.3 FIL E OPENING AND POSrT10NING ~Illis binary 110 is messy, somewhat complic. ... ted, and error·prone. However, as progra mmers we don't always have the freedom to choose file formals , so oc- cas ionally we must lise binary I/O simply because that's the format someone chose for the files we need 1"0 read or wrile. Altematively, the re may be a good read more..

  • Page - 420

    390 CHAPTER 11 • CUSTOMIZ ING INPUT AND OUT PUT 11.4 String streams You can usc a string as the source of an istream or lhe target for an oslream . An istream that reads from a string is called an istrings lream and an ostream that stores characters written to it in a string is called an oslringstream. For example, an istringst ream is useful for extracting read more..

  • Page - 421

    11 . 5 LIN E-ORIENTED INPUT composed in my_codeO will eventually end up wriuen to an area of a screen. For example, in § 11. 7, we use a stringstream LO filter undesirable characters out of our input. Thus, stringstreams can be seen as a mechanism for tailoring 110 to special needs and tastes. A simple usc of an ostream is to construct strings by concatenation. read more..

  • Page - 422

    392 C HAPTER 11 • CUSTOMIZ ING INP UT AND OUTPUT string firsCnamej string second_name ; stringstream ss(name)i ss» fir sCname j ss»second_namej /I input Dennis /I input Ritchie Reading directly into firsCname and second_name would have been simpler. One conmlOn reason for wanting to read a whole Jine is that the definition of whitcspacc isn 't always appropriate. Sometimes, read more..

  • Page - 423

    11.f> (f-I ARACTER CLASS IFI CATION actcrs) and z* to be read as one suing (since * isn' t a whitespace character either). Instead. we could write char c h; while (ci n.get(ch» { if (isspace(ch» ( II if ch is whitcspacc II do nothing (i.c., sk ip whitespacel } if (isdigit(ch» { II read a number c lse if (isalpha(ch)) ( II read an identifier } e lse { read more..

  • Page - 424

    394 C H APTER 11 • CU STOMIZIN G IN P UT AND OUTP UT Note the way that classifications can be combined using the "or" operator (I). For example, isalnum(c) means isalpha(c)lisdigit(c) ; that is, "Is c either a letter or a digit?" In addition, the standard library provides two useful functions for getting rid of case differences : Characte r case read more..

  • Page - 425

    11. 7 US I NG NONSTAN D ARD SE PA RATORS As planned, the guests arri ved ; then, TIlis is not what we'd find in a dictionary: "planned," and "anived ;" are not words. TIley arc words plus distracting and irrelevam punctuation charncters. For most purposes we must treat punctuation just like whitespacc. How might we get rid of such punctuation? \o\'e read more..

  • Page - 426

    3% (HAPTE R 11 • CUSTOMIZ IN G I N PUT AN D OUTPUT ps.whilespace( " j :,. ") ; /I treat semicolon, colon. comma, and dot as .... ..,iICSp.1CC string word; while (ps»word) v s. push_back(wordl j H ow wo uld we deflne a stream that wo uld work like ps? The basic idea is to read words fro m an ordinary input stream and then treat the user-specified read more..

  • Page - 427

    11. 7 U S ING NO NS TA N DARD S EPARATORS private: } ; iSlrea m& so urce; istringstream buffe r; siring white; bool sensitive; /I character source /I we let buffer do our formtl ll ing II characters considered "whitespace" /I is the stream case-sensitive? rnle basic idea is - j ust as in the exam ple above - to read a line at a time from the read more..

  • Page - 428

    3 .. ) (HAPTER 1 1 • CUSTOMIZING IN P U T AND OUTPUT while (!(buffer>>s» ( /I try 10 read from buffer ) if <buffer.badO II !source.gaodO> return - this; buffe r.clearO; string line: gelline(source, line): II get a line from source /I do character replacement as needed: for (int i =0; kline .size(); ++i) if (is_whilespace(lin e[ ij)) line[iJ= ' ' ; else if read more..

  • Page - 429

    11 .7 U SING NONS TA NDA R D SEPA RATORS string line ; getline(source, linc ); /I get a line from sou rce /I do character replacement as needed : fo r (int i =0 ; i<line .sizeO; ++il if (is_whitespace(line[iJ)) line[iJ= ' ' ; /I to space else if (!sensitive) line[il = tolowe r(line[iJ); II to lower case buffer.str(line) ; /I put string into stream 'Ne rcad read more..

  • Page - 430

    400 C HAPTER 1 1 • CU STOMIZING INP U T AND OU TP U T TIle conventional lise of an istrcam is to lCSllhc res ult of » . For example: while (ps»s) {'- .. . -' } That means that we need a way of looking a t the result of ps>>s as a Boolean value. TIle result of ps»s is a PuncCstream , so we need a way of implicitly LUm- ing a PuncCstream read more..

  • Page - 431

    11 .8 AND THERE IS SO MUC H MORE don' t la nguages of onl y people that th ere Iwo us. Why did we get don' t and not do nt ? We len the single quote out of the white - spaceO c."1I1. Caution: Pun et_stream behaves like an istream in many important and useful ways, but it isn't really an istream. For example, we can't ask for its state using rd- read more..

  • Page - 432

    40' CHAPTER 11 • CUS TO MIZING IN PUT AN D OU TP UT the complexity implied by na turaJlanguages. What is written as 12.35 in English will be conventiona lly rcprcsclllcd as 12,35 in most Olher European la nguages. Naturall y, the C++ sta ndard library provides facilities fo r dealing with tha t and ma ny Olher na tural-la nguage-specific aspects of 1/0 . H ow read more..

  • Page - 433

    CHAPTER!! TE RM S 1234 1234 12341234 Explain U1C results. 9. Writc somc code to print ule number 1234567.89 three times, fIrst using general , then fixed , then scie ntific forms. Which output form presents the user with ule most accurate representation? Explain why. 10. Make a simple table including last name, fIrst name, telephone number, and email address for yourself read more..

  • Page - 434

    CHA PTER 11 • CUS TOMIZ I NG I NPUT AND OUTPUT Exercises 1. Write a program that reads a text me and converts its input to all lower case, producing a new file. 2. Write a program that removes all vowels from a file ("disellwowcls"). For example, O nce upo n a time ! becomes nc pn tm!. Surprisingly of tell, the result is still readable; try it on read more..

  • Page - 435

    C HAPTER 1 1 POSTSCRIPT 12. Reverse the order of words (defined as whitespace-separated strings) in a file. For example, Norwegian Blue parrot becomes parrot Blue Norwegian. You arc allowed to assume that all the strings fro m the file will fit into memory at once. 13. Write a program that reads a text file and writes out how many charac- ters of each character read more..

  • Page - 436

    read more..

  • Page - 437

    1- . r 12 A Display Model "The world was black and white the n. [It] didn't turn color until sometime in the 193 Os." - Calvin's dad T his dlaptcr presents a display model (the output part of GU I), giving examples of use and fundamental notions such as so'CCn coordinates, lines, and color. line, Li nes, Polygons, Axis, and Text arc examples of Shapes. A Shape is read more..

  • Page - 438

    408 12.1 Why graphicsl 12.2 A. display mo de l 12.3 A. first example 12.4 Usi ng a GUllibra ry 12.5 Coordinates 12.6 Shapes 12.1 Why graphics? (HAPTER 12 • A DISPLAY MODE L 12.7 Using Shape primitives 12.7.1 Graphics heilde rs and main 11.7.2 A.n a lmos t b la nk window 12.7.3 A.xis 12.7.4 Graphin g a fun cti on 12.7.5 Polygo ns 12.7. 6 Recta ngles 12.7.7 read more..

  • Page - 439

    12.2 A D I SPL AY MODel Cm/)/dcs art a ferlile J(jUf(£ rf design eXflmples. It is actually hard to design and implement a good graphics and CU I library. Graphics arc a very rich source of concrete and practical examples o f dcsign decisions and dcsign techniqucs. Some of the most useful techniques for designing classes, de- signing functions, separating so ft ware read more..

  • Page - 440

    410 C HAPTER 12 • A DIS PLAY MODEL the acmal tcxt because it is irrelevam here. lne poim is that you can express lay- out notions in plain text, but the connection between the cha racte rs written and w ha t appears on the screen is indirect, governed by a program that interprets those "markup" commands . Such techniques arc fundamcntaHy s imple and im- read more..

  • Page - 441

    12 .3 A FIR ST EXA MPL E #indude "Simple _window.h" #ind ude "C ra ph .h" int mainO ( /I get access to our window library II get access to our graphics libr.lry faci lities using namespace C ra ph_lib ; /I our graphics facili ties are in GraphJib } Po int 11(100,100); /I to become top left corner of window Simple_window win (II ,600,400, read more..

  • Page - 442

    412 CHAPTER 12 • A DISPLAY MODEl Let's go through the program line by line to sec what was done. First we include the headers for our gra phics interface libraries: #include "Simplc_window.h" II get access to our window library #include "G raph .h " /1 gel access to our graphics library faciJilies Then, in main O, we start by telling the compiler read more..

  • Page - 443

    12.3 A FIR ST EXAMPLE JUSt to show oIT, we then color the lines of our polygon red: poly.scC color(Colo r: :red ); II adjust properties of pol y Finally, we auach poly to our window, win : win .allach(poly); II connect poly to thc window If t.he program wasn't. so fas t, you would notice that so far nothing had happened to the SQ"CCn: nOlhing at all. vVe read more..

  • Page - 444

    .,. C HAPTER 12 • A DISPLAY MODEL Simple_window to " plain" Window, which has no potentially SPUriOLI S facilities built in, and show how we can write our own code to comrol interaction wit.h a window. For the next three chapters, we'll simply usc that "Next" buna n to move from one "display" to the next when we want to display read more..

  • Page - 445

    12 . 5 CO O RDINATE S We can illustrme the partS of our "graphics world" like this: l Our code I ~ l Our interface library I " A l7'phics/GUI library (here FLTK) "- The operating system Our screen I (e.g., Windows or Linux) Our intcrface classes ptovide a simple and user-extensible basic notion of twO- dimensional shapes with limited support for the read more..

  • Page - 446

    " 6 C HAPTER 12 • A DISPLAY MODEl Please note that y coordinates "grow downward." Mathematicians, in particular, fi nd this odd, but screens (and windows) come in many sizes, and the top lert point is about all that they have in common. TIle number of pixels available depends on the screen : I024-by-768, 1280-by- 1024 , 1450-by-l050, and 1600-by- 1200 are read more..

  • Page - 447

    12 . 7 US ING SHAPE PRIMITIVES Later (Chapter 16), we'll add CUI (user interaction) classes : Bullon, In_box, Menu, etc. We could easily add many more classes (for some definition of ';easy"), suc h as Splin e, Grid , Block_chart, Pie_chart, etc. However, defining or describing a complete CU I framework with all it:s facilities is beyond the scope of this book. 12.7 read more..

  • Page - 448

    418 (HAPTER 12 • A DI S PLAY MOD EL As usual, mainO contains the code we want to execute (d irectly or indirectly) and deals with exceptions: inl ma in 0 t.y ( 1/ ... here is our code . ) ca tch(eJeceptio n& e) ( ) 1/ some error reporting return 1; catch( ... ) ( /I some more error reporting return 2; ) 12.7.2 An almost blank window We will not read more..

  • Page - 449

    12.7 US ING SHAP E PRI MITIVES However, we want to lise the point (100,100) several times so it is mo re conven- ient to give it a symbolic name. 111e 600 is the width and 400 is the height o f lhe window, and Canvas is the label we want put on the frame of the window. To actually get the window drawn on the screen, we have to give control to the GUI read more..

  • Page - 450

    420 CHAPTER 1 2 • A DI SPLAY MODEl · nlC actual size of the window (in inches) depends on the resolution of your screen. Some screens have bigger pixels than other screens . 12.7.3 Axis An almost blank window isn't very interesting, so we'd better add some infonn a- lion. What would we like to display? Just to remind you that graphics is nOt all fun and read more..

  • Page - 451

    12. 7 USIN G SHAP E PRIMIT IVES ~nle sequence of aClions is: make the a.xis object, add it to the window, and fi· nally display it : 'yVe can see that an Axis: :x is a borizomalline. We see the required number of "notches" (10) and the label "x axi s." Usually, the label will explain what the axis and the notches re present. Naturally, we chose read more..

  • Page - 452

    422 CHAPTER 12 • A DISPI.AY MODEL ,,'" We don't actually think thal it is a good idea to usc different colors for x and y axes. \<\'c just wanted t o show you how yOll C<'lll set the color of a shape :md of in- dividual clements of a shape. Using lots of color is not necessarily a good idea. In pallicuiar, novices tend to usc color wi th m o rc read more..

  • Page - 453

    12.7 USIN G SHAPE PRIMITIVES . .., Notc how the curvc simply stops when it hits the edge or the window. Points drawn outside our window recta.ngle arc simply ignored by the G U I system and never secil . 12.7.5 Polygons A graphed runction is an example or data presentation. Wc'lI sce much more or that in C hapter 15. However, we can also draw differcnt kinds or read more..

  • Page - 454

    424 poly.set_style(Lin e_style: : dash); win.attac h(po ly); win .seCla be l(" Canvas #5"); win .waiC fo T_butto n(); C HAPTER 12 • A DI SPLAY MODEl 111is time we change the color of the sine curve (sin e) just to show how. ~IltCIl , we add a triangle, just as in our first example from §12.3, as an example o f a polygon. Again, we set a color, read more..

  • Page - 455

    12.7 U S ING S H A P E PR IMITIVES Rectangle r(Poinl(200,200), 100, SO); II top left corner, width, height win .attach(r); win .seUabel("Canvas #6" ); wi n. wail_for_button(); From lhal, we gel ,,.. Please nOle lhat making a polyline with rour points in the right places is nOl enough LO make a Rectangle. It is easy to make a Closed_polyli ne that looks like read more..

  • Page - 456

    426 C HAP TER 12 • A DI S PLAY M OD El .... In fact, the image on the screen of such a poly_reet is a rectangle. H owever. the poly _reet object in memory is nOt a Rectangle and it docs not "'know" anyth ing a bout rectangles. ~nlC simplest way to prove that is to add anoth er point: pol y _recl.add{Poinl(SO, 75»; No rectangle has five points: read more..

  • Page - 457

    12.7 US IN G S HAPE PRIMITIVE S "Iltees of a rectangle (as we know them from geometry). We write code that de- pe nds o n a Rectangle really being a rectangle on the screen and staying that way. 12.7.7 Fill \o\'c have been drawing our shapes as outlines. We can also "fill" a rectangle with color: r.scefill_color(Colot : : ye llow); /I color the inside read more..

  • Page - 458

    428 CHAPTER 12 • A DISPLAY MODEL Text t(Point(150,15O), " He llo, graphical world ! "); win .atlach(l); win .setJabel{"Canvas #8"); win.wail_for_button () ; .... Fro m the primitive gr aphics elements yo u see in this wi ndow, you can build d is- plays of just abOllt any complexity and subtlety. For now, just no tc a peculiarity of the code in this read more..

  • Page - 459

    12 . 7 US ING SH AP E PRIMITIVES 12.7.9 Images \.vc can also load images from files: Image ii(Point(100,50), "image .jpg") ; win .allach (ii); win.seClabel("Canvas #10 ") ; win . wai Uor _bu lIonO; 1/400·2 12 -pixel jpg As it ha ppens, the file called image .jps is a photo or two planes breaking the sound barrier: . "" 429 read more..

  • Page - 460

    ·'" CHAPTER 12 • A D ISPLA Y MO DE L That phoLO is relatively large and we placed it right on tOp of our text and sha pes . So, LO clean up Ollr window a bit, let liS move it a bit out of the way: ii.move(100,200); win .set_labeH "Canvas #11 ") ; win .waiC fof_button()j . "" Note h ow the pans of the photo tha t d idn't fit in read more..

  • Page - 461

    12 .8 GETTING T H IS TO RU N win .attach (c); win.altach (m); win.attach (e); wi n .attach(sizes); win .attach(cal); win .set_label ("Canvas #12 "); win . waiCfor_button (); Can you guess what this code docs? Is it obvious? ...... "'01_"'V .... 111e connection between the code and what appears on the screen is direct. If you don' t yet see how that read more..

  • Page - 462

    432 C HAPTER 12 • A DI SPL AY MODEL One way of looking at the program is that it has four distinct p<lrts: O ur program code (ma inO, etc.) OUf interface library (Window, Sha pe, Polygo n, etc.) l1)c FLTK library TIle C++ standard library Indi rectl y, we also lI SC the opera ti ng system. Leaving out the O S and the stan- dard library, we can read more..

  • Page - 463

    CHAPTER 12 REVI EW Headers: Point .h Window.h Simple_window.h Graph .h GUth Code files: Window.cpp Graph .cpp GUtcpp Until Chapter 16, you can ignore the GU I files . ..;' Drill 111e drill is the graphical equivalent LO the "Hello, World !" program . Its purpose is to get you acquainted with the simplest graphical output tools. l. Get an empty Simple_window with read more..

  • Page - 464

    4" 7. 8. 9. 10. II. 12. 13. 14. 15. 16. 17. 18. Terms C H A P TER 12 • A DI S PL AY MODEL What is the simplest window to use? What is the minimal window? What's a window label? H ow do youlabcl a window? H ow do screen coordinates work? Window coordinates? Mathematical coordinatcs? 'What arc examples of simplc "shapes" that we can display? read more..

  • Page - 465

    C HAPTER 12 POSTSC RIP T 8. Draw the O lympic five rings. If you can't remember the colors, look them up. 9. Display an image on the screen, e.g., a pholO of a friend. Labelt.he image both with a tide on the .. vindow and with a captio n in the window. 10. Draw the fil e diagram from § 12.8. II . Draw a series of regular polygons, o ne ins ide the read more..

  • Page - 466

    read more..

  • Page - 467

    1- '- 13 Graphics Classes "A language that doesn't change the way you think isn't worth learning." -Traditional C harter 12 gave an idea o f what we could do in terms o f graph- ics using a set o f simple interface classes, and how we can do it. This cilapler prcsems llu111Y of the classes o ffered. 111C focus here is on the design, usc, <md read more..

  • Page - 468

    438 13.1 Overview of graphics classes 13.2 Point and Line 13.3 Lines 13.4 Color 13.5 Line_style 13.6 O pe n_polylin e 13.7 Closed_polyline 13.8 Polygo n 13.9 Rectangle C HAPTER 13 • GRAP HI CS C LA SS ES 13.10 Managing unname d o bjects 13.1 1 Text 13.12 Circle 13.13 Ellipse 13.14 Marked_polyline 13.15 Marks 13.1 6 Mark 13.17 Images 13.1 Overview of graphics read more..

  • Page - 469

    13 . 1 OVERVIEW OF GRAPH I CS CLASSES Gra phics inte rface classes (continued ) Line O pe n_polyline Closed_po lyline Polygo n Te .:t li nes Rectangle Circle Ellipse f un ctio n A.:is Mark Marks Mar ked_po lyline Image a line segment as we sec it on Ihe screen, defined by its two end Po ints a sequence of connected line segments defined by a sequence of Po read more..

  • Page - 470

    440 CHAPTER 13 • GRAPHICS ClASSES TIle source code is organized into files like this: Graphics interface source fil es Poinl.h Point Graph .h Window. h Simple_window.h GUI.h all other graphics interface classes Window Simple_window Button and the other CUI classes definitions of functions from Graph.h definitions of functions from Window.h definitions of functions from GUl.h read more..

  • Page - 471

    13.2 POIN T A N D LI N E oricntcd layo ut of two·dimensional points defined b y (x,y) integer coordinates. As described in § 12.5, x coordinates go from 0 (representing the left·hand side of the screen) to max_xO (representing the right·hand s ide of the screen); y coordinates go from 0 (representing the tOp of the screen) to max_yO (representing the botmm of the screen). As read more..

  • Page - 472

    442 ( HAPTER J3 • GRAPHIC S ClA SS ES Executing that, we gel As a user imcrfacc designed for simplicity, line works quite well. YOli don't need LO be Einstein to guess that lin e verlical(PoinI(150,SO), Point(150,15O» ; creales a (ve rtica l) line from (150,50) to (150,150). "nlcrc arc, of cou rse. imple- menta tion details, but yO ll don't have to know those read more..

  • Page - 473

    13 .3 LIN ES From now o n we'll leave Out the definition of the Simple_window and the calls o f allachO . l 110se arc just more "scaffolding" that we need for a complete program but that adds little to lhe discussion of specific Shapes. 13.3 Lines As it tums OUl , we rarely draw just o ne line. We tend to th ink in terms of objects cons isting read more..

  • Page - 474

    444 CHAPTER 13 • GRA PH ICS CLASSES 111C only way we can tell that this is a different window is that we labeled them differently. TIle difference between a set of Lin e objects and a set of lines in a lines o b· ject is completely one of our view of what's going on. By using Lines, we have ex· pressed our opinion that the two lines belong lOgemC!' read more..

  • Page - 475

    13.4 COLOR Let'S reLUrn (0 the design o f lin es. How are the mcmber functions of class lines implemcnted ? lines provides juSt twO operations. The addO function sim- ply adds a Iinc defined by a pair o f points to thc set of lines to bc displayed: void lines : :add(Po int pl , Point p2) ( Shape:: add(pl ); Shape: :add(p2); Yes, the Shape:: qualification is read more..

  • Page - 476

    446 C HAPTER 1 3 • GRAPHI CS C LA SSES 111is colors the lines dcrmcd in grid red so that we get Color defines the notion of a color and gives symbolic names to a few of the morc conunon colors: slrucl Color { enum Colof_type ( ); red=FL_REO, blue=Fl_BLUE. green=FL_GREEN, yellow=Fl_YEllOW, white=FL_WHITE, black=FL_BLACK, mage nta= FL_MAGENTA, cyan=Fl_CYAN, dark_red=FL_DARK_RED, read more..

  • Page - 477

    13.4 COL OR Color(ColoUype cc, Transparency vv) : c(FI_Color(cc» , v(vv) {} Color(inl cc) :c(FI_Color(cc», v(visible) () ColorCTransparenc y vv) : c(FI_ Color()), v(vv) { } /I default color int as_intO co nsl { return Ci ) char visibililyO canst { return Vi } void set_visibilityCTransparency vv) {v=vv ;} private : char Vi /I invisible and visible for now FI_Color Cj ) ; read more..

  • Page - 478

    C H APTER 13 • GRAP H ICS Cl ASS ES 13.5 Line_style When we draw several lines in a window, we can distingu ish them by co lor, by style, or by bOlh. A line style is me pattern used to outline the line. \Ve can use line_style like mis: grid .set_style(line_style : :dot); lllis d isplays the lines in grid as a sequence of dots ra ther than a solid read more..

  • Page - 479

    13 .5 UNCSTYLE int widthO const { return Wi } int styleO const ( return S j } private : int s; int W j } ; "nle programming tedmiqucs fo r defming li ne_style are exactl y the same as the oncs we used for Color. Here, we hide the fact that FI.;T'K uscs plain ints to repre- sent line styles. Why is somcthing like that worth hiding? Because it is exactly read more..

  • Page - 480

    450 C HAPTER 13 • G RAPHICS CL ASS ES Note that color and style apply to alIlincs of a shape. That is one of the advan- tages of grouping many lines into a single graphics object, such as a lines, Open_polyline, or Polygon . If we wam to comrolthc color or style for lines sep- arately, we must define them as separate lines. Fo r example: read more..

  • Page - 481

    Uasically, an O pen_polyline is a fancy word for what we encountered in kindcr- ganen playing "Connect the D ots." C lass O pen_po lyline is defined like this: stru cl O pe n_polyline : Shape { /I open sequence of lines void add(poinl p) {Shape: :add (p); ) ) ; Yes, lImt 's the complete definiti on. TIlere is literally nothing to Open_polyline ex- cept its read more..

  • Page - 482

    452 CHAPTER 13 • GRAPHICS ClASS ES 111c result is (o f course) identical to th at of §13.6 except [or t hat final closing line: TIle definition o f Closed_polyline is strU t t Cl osed_polyline: Open_polyline ( /I closed sequence of lines void draw_lin esO consl; }; void Closed _polyline: : draw_lin esO consl ( } O pen_polyline: :draw_lin esO; /1 first dr(lw the read more..

  • Page - 483

    13 .8 POLYGON FLTK is kept \\~thin the implementation of our class rather than being exposed to our users . No user code needs to mention fU ineO or to know about interfaces where points appear implicit..ly as integer pairs. If we wanted to, we could replace FLTK \,~th another GU I library \\'ilh vel)' litt..le impact on our users' code. 13.8 Polygon A Polygon is read more..

  • Page - 484

    454 void Polygon : :add(Point p) ( C HAPTER 13 • GRAPH ICS ClASSES /I check that the new l ine doesn't intersect existi ng l ines Sha pe::add (p); } Here we inherit Closed_polyline's dcfmition of draw_linesO, thus saving a fair bit of work and avoiding duplication of code. Un[onunatcly, we have to check each add(). That yields an inefficient (order N-squarcd) read more..

  • Page - 485

    13.9 RE C TANGLE Ensuring t.hat a Polygo n rcally represents a polygon turned out to bc surprisingly messy. TI1C chcck for intcrscction that we left out of Polygon: :add O is arguably the most complicated in the whole graphics library. If you are iIllcrested in fiddly coordinate manipulation of geometry, have a look at the codc. And even then wc are not. done. Consider read more..

  • Page - 486

    456 CHAPTER 13 • GRAPHI CS CL ASS ES We can specify a rectangle by two points (top left and botlom right) or by one point (top Icft) and a width and a hcighL The conSlnlctors c.'m be defmed like t.his: Recta ngle: : Rectangle<Point x l', int WW, int hh) : w(ww) , h(hh) { if (h <=O II w<=O) e rror(lt Bad rectangle: no n·positive s ide "): add(xy); read more..

  • Page - 487

    1 j.9 REC TAN GL E \Vhcn you don 't havc a fill color, the rectanglc is transparelll; that's how you can see a corner of the yellow reetOO. We can move shapes aro und in a window (§14.2.3). For eXillllple: rect11.move(400,O); /I to the right of rect21 rcct11 .seCfiI Ccolor(Colo r: : while); win12.scUabel(" rectangles 2"); 111is produces 457 read more..

  • Page - 488

    '58 CHAPTER 13 • GRA PH ICS CLAS SES Note how only part of the while recl11 fiLS in the window. What doesn't fit is "clipped"; thal is, it is not shown anywhere on the screen. Note also how shapes are placed one on top of another. ~111is is do ne J USt like you would put sheets of paper on a table. 111C first one yOli put will be onlhc bOl - read more..

  • Page - 489

    13 . 10 MANAGING U NNAMED O BJECTS Note that with bOlh fill color and line color set lO invisible, rect22 ca.n no longer be seen. Because it has to deal with both line color and fill color, Rectangle's draw_lincsO is a bit messy: void Rectangle: :drawJi nesO consl { } if (fill_colo rO. visibility()) ( 1/ fill } fI_ color(£ill_ colo r O .as_in to); fUectf(poin t read more..

  • Page - 490

    C HAPTER 13 • GRAI) HI (S ( LA SSE S them in a 16-by- 16 matrix that shows how colors with similar color valucs relate. First, here is thc result: Naming those 256 squares would not o nly be tedious, it would be silly. TIle obvi- ous "name" of the top left square is its location in the matrix (0,0), and any Olh er squa re is similarly identified read more..

  • Page - 491

    13. 10 MANAGIN G U NNAMED OBJE CT S Rectangle x (Poin I (1 00,2(0), Poinl(200 ,3(0» ; reCl.pu sh_back(x)i II add named recl.push_back(new Reciangle(Point(50,60), Point(80,90))); /I add unnamed for (in I i=O; krect.size(); ++i) recl[i) .move(10,10); /I usc rcct vVe expbin the new operato r in Chapter 17, and the implementation of Vector_ref is presented in Appendix E. Fo r read more..

  • Page - 492

    462 ( HA PTE R 1 3 • GRAPHICS C LASSES 13.11 Text Obviously, we WanllO be able to add text to our displays . For example, we might want to label our "oddn Closed_polyline from § 13.8 : Te,,' t(Point(200,200), "A closed polyline tha t isn't a polygon ") ; l.set_color(Color:: blue); We get Basically, a Text obj ect defines a line of text starting at a read more..

  • Page - 493

    13. 11 TEXT void seUabel(const string& s) ( lab = s; ) string labe lO co nst { re lurn lab; } void seUonl (Font 0 { fnt = f; } Font fonl O consl ( relurn Font(fnt); } void seUonCsize(int s) { fn,-sz = s; } inl fonCsizeO const { return fnt_5z; } private : string lab; !! Iabel Font fnl ; int fnl_sz; }; Text has its own draw_lin esO because only the read more..

  • Page - 494

    ... CHA PTER 13 • G RAPHI CS ClASSES Ii mes _ bold j lali c=Fl_ TIMES _BOLO _IT All C, symbol=FL_SYMBOl, ); screen=FL_SCREEN, screen_bold=FL_SCREEN _BOLD, zapC dingbats=Fl _ZAPF _DINGBATS Font(Fo nUype to : f(fO {} Font(inl to :f(ff) {} int as_intO consl { return fi } private: int f ; ) ; 111c Sl yle or class definition lIsed to defme Font is the srun e as we read more..

  • Page - 495

    13.12 C IRCL E This produces three circles of differe nt sizes aligned with their centers in a hori· zontalline: "n le main pcculiarity o f Circle's implementation is t.hat the point stored is nOt the center, but thc top left comer of the square bounding lhe circle. We could have stored either but chose the one FLll<. uses for its optimized circle·drawing r read more..

  • Page - 496

    ... CHAPTER 13 • G RAPHI CS CLASS ES NOle the lise of fI_arcO to draw the circle. ·fbe initial t wO arguments specify the top left corner, ule next twO arguments specify the width and the height of the smallest rectangle that encloses the circle, and the final two arguments specify the beginning and end angle to be drawn. A circle is drawn by going the full read more..

  • Page - 497

    13 . 13 ELLIPSE Note that an Ellipse with majo r()==minor() looks exactly like a circlc. Another popular view of an ellipse specifics two foci plus a sum of distances from a point to the foci. Given an Ellipse, we can compute a focus. For example: Point Ellipse: :focus1() const ( ret u rn Po int( center().x+sqrt(d ouble( w· w - h • h)) ,cente r(). y); ) Why is read more..

  • Page - 498

    .68 CHAPTER 13 • GRAPHI CS CLA SSES When we design classes, we have to be careful nOt to be too clever and not to be deceived by OLir "intuition " into defining classes that don't make sense as classes in our code. Conversely, we have to take care thaI our classes represent some coherent concept and are not just a collection of data and fun ction read more..

  • Page - 499

    13 . 15 MARKS struct Marked_polyline : Open_polyline ( Marked_polyline(const string& m) : mark(m) { } void draw_linesO const ; private : s iring mark; }; By deriving from Open_polyline, we get the handling of Points "for free " ; all we have to do is to deal with the marks. In particular, draw)inesO beco mes void Marked_polyline : :draw_linesO consl ( read more..

  • Page - 500

    470 Marks PP("X")i pp .add (Point(l00, lOO»; pp .add (Poi nI(150,200»; pp .add (Poi nl(250 ,250»; pp .add (Point(300,200»; 111is produces • C HAPTER 13 • GRAP HI C S CLASS ES • • One obvious lI SC of Marks is to display data that represents discrete events so that drawing connecting lines would be inappropriate. An example would be (height, weight) read more..

  • Page - 501

    13 . 16 MARK indicate it by a pair orIi nes as in § 13.2 or by using Marks.llmt's a bit verbose, so we have a simple version of Marks that is initialized by a point aJld a character. Fo r exam ple. we could mark the celllers of OLlr circles from § 13. 12 Iike this: Mark ml (Poin I( 100,200), '. '); Mark m2(Poinl (150,200), 'y') ; Mark m3(Po inl read more..

  • Page - 502

    C H APTER 13 • GRAPHI CS C LASSES All Mark provides is a conveniem notation for creati.ng a Marks obj ect with a single point marked with a single character. Is Mark worth our effort to defin e it? Or is it juSt "spurious complication and confusion"? TIlere is no clear, logical an- swer. vVe went back and forth on this question, but in the end decided read more..

  • Page - 503

    1). 1 7 IMA G ES We can selCCt part of tha t image a nd ad d a p hoto of Rita as seen from space (rita.jpg) : Image rila(Point(O,O), "rita.jpg"); Image path (PoinI(O,O)," rita_ path.gifll); pa th .seCmask(Point(SO,250),600,400); /I select I ikely landfall win .attach(path); win .altach{rita); TIle seCmaskO operation selects a sub-picture of an image to be read more..

  • Page - 504

    474 C HAPTER 1 3 • GRA PHI CS ClA SS ES In our graphics imcrfacc library, wt: represent an image in memory as an o bjeCl of class Image : strucllmage : Shape { Image(Point xy, string file_name, Suffix: : Encoding e = Suffix: : none) j - lmageO { delete Pi } void draw_lin esO const; void seCmask(Point "y, inl ww, inl hh) { w=ww; h=hh ; cx=xy.x; cY=XY.Yi read more..

  • Page - 505

    13 . 17 IMAGE S ) p = new Bad_image(30,20); II the ""error image" return ; ) if (e == SUffi K: :none) e = gel_e ncoding(s) ; switch(e) ( II check if it is a known encoding case SuffiK: : jpg: p = new FU PEG_lmage(s .c_str(»; break; case SUffiK: :gif: p = new FI_GIF _Image(s.cslr(»; break; default : /I unsupported image encoding fn. seIJa read more..

  • Page - 506

    47. CHAPTER 13 • GRAPHICS ClASSES ~ Drill 1. Make an 800-by-1000 Simple_window. 2. PlIl an B-by-8 grid on the leftmost 800-by-BOO par t of thal window (so that each square is 100 by 100). 3. Make the eight squares on the diagonal starting from the top lert corner red (use Rectangle). 4. Find a 200-by-200-pixcJ image (jPEG or GIF ) and place three copies of it read more..

  • Page - 507

    ClM PTER !J EXE RCISE S 2 1. What is a fO Ill and why do we care? 22. \.vha t is Vector_re f fo r and ho w do we usc it? 23. What is the difference between a Circle and an Ellipse? 24. W hat happe ns if you try to dis play an Image given a me name that doesn't refer to a rtle containing an image? 25. How do you display part of an image? read more..

  • Page - 508

    I 478 CHAPTER 13 • GRAPHICS CLASSES 10. Defi ne a class Regular_po lygon. Usc the center, the number of sides (> 2), and the distance fro m the center to a corner as construclOr argu- me nts. 11. D raw a 300-by-200-pixcl ellipse. Draw a 400-pixel-lo ng x axis a nd a 300- pixel-lo ngy axis thro ugh the center of the ellipse. Ma rk the foci. Mark a point read more..

  • Page - 509

    \t "-· 14 Graphics Class Design "Functional, durab le, beau tiful." -Vitruvius T he purpose of the graphics chapters is dual: we walll to provide useful tools for displaying infomlalion . but we also usc the famil y o f graphical inte rface classes to illustrate general design and implementation techniques. In particular, this chapter presents some ideas o f read more..

  • Page - 510

    14.1 Design principles 14.1. 1 Types 14.1.2 Operations 14.1.3 Na.ming 14. 1.4 Muta.bility 14.2 Shape 14.2. 1 An abstra.ct class 14.2.2 Access con trol 14.2.3 Dra.wing shapes 14.2. 4 Co pying ;lnd mutability 14.1 Design principles C HAPTER 14 • G RAPHI CS CLASS DESIGN 14.3 Base and derived classes 14.3. 1 Objectla.yo ut 14.3.2 Deriving cl.lsses and de fining virtua.l read more..

  • Page - 511

    14 . 1 DE SIG N PRINCIPLE S The sct of our graphics imerfacc classes is a library; the classes are meant to be used together and in combination. They arc meant to be used as exam ples to follow when you define classes to represent other I,'l'aphieal shapes and as build- ing blocks for such classes. We are not j ust defining a set of un related classes, so we read more..

  • Page - 512

    482 C HAPTER 14 • GRAP H ICS ClASS D ES IGN small classes most closely and most usefully models our domain of graphics. A sin- glc class providing "everything" would leave the user messing with data and op- tions without a framework to help understanding, debuggin g, and perfonnancc. 14.1.2 Operations We provide a minimum o f operations as part o f each read more..

  • Page - 513

    14 . 1 D ESIGN PRI N C IPL ES Logically identical operations have the same name. For example, every func· tion that adds points, lines, etc. to any kind of shape is called add() , and any fUll c, tion that draws lines is called draw_linesO . Such uniformity helps us remem ber (by offering fewe r details to remember) and helps us when we design new classes read more..

  • Page - 514

    ... C HAPTER 14 • GRAPHI CS C LAS S DESIGN Basically, add() uses pass·by·valuc (copies) and attachO uses pass-by-rcfcrcncc (shares a single object). We could have chosen to copy graphical objects into Windows. However, that would have given a different programming model, which we would have indicated by using addO rather than attac hO. As it is, we just "'attach" read more..

  • Page - 515

    14 .2 SH APE other than our class's member functions need LO read the value o f label, and if so, how. Fo r example: stru el Circle ( II ... private : int r; 1/ radius ); Circle c( Point(100,200),SO); c.r = -9; 1/ OK? No - compi le-time error: Circle: :r is private As you might have noticed in Chapter 13, we decided to prevent direct ac· cess LO most read more..

  • Page - 516

    ... (HAPTER 14 • GRAPHICS CLASS DES IGN We'll first present the complete class and then discuss its details: class Shape ( 1/ deals wi th color and style and holds s,equence of lines public: void drawO const; 1/ deal with color and draw lines virtual void mOlle(int d x, int dy); /I move the shape +=dx: and +=dy void scCcolo r(Color col); Col or colarO canst; read more..

  • Page - 517

    14 .2 S HAP E 14.2.1 An abstract class Consider fi rst Shape 's constructor: protected: Shape(); l lle constmctor is pro tecled . TImt means that it can only be used direct.l y rrom classes de ri ved rro m Shape (using the :Shape notation). In other words, Shape can only be used as a base ror classes, such as line and O pe n_polyline . TIle pur- pose or read more..

  • Page - 518

    ... (HAPTER 14 • GRAPHI CS C LASS DESIGN that can be used to create objectS - that is, the opposite of an abstract class - is called a CQIlCr(ie class. Note that abstrrul and concrete are simply lcdmical words fo r an everyday distinction. We might go to the SLOre to buy a camera. However, we can't just ask for a camera and takc it home. VVhat brand o f read more..

  • Page - 519

    14 .2 S HAPE "me main inconvenience of this style is that you can't give the member variable the same name as its readout function. As ever, we chose the most convenient names for the fu nctions because they are part of the public interface. It matters far less what we call our private variables. Note the way we use const to indicatc thatlhe readout functions do read more..

  • Page - 520

    490 CHAI'TER 14 • GRAPHI CS CLASS DES IGN hexagon." On the other hand, if we changed one of the points of a rectangle, the result would still be a rectangle. In fact, we didn't fmd a need for seCpointsO in our example classes and code, so seCpoinlO is there, just to ensure that the rule that we can read and set every attribute of a Shape holds. Fo r read more..

  • Page - 521

    14 .2 SHAP E virtual void drawJinesO canst; II draw the appropriate lines virt ual void move(int dx, int dy); /I move the shape +=dx and +=dy ); veclor<Point> points ; Color leolor; Line_style Is ; Color feolor; /I not used by all shapes What value did we add by those extra 12 member functions and t'o'>O lines of access specifications (private : and protected: read more..

  • Page - 522

    492 (HAPTER 14 • GRAPHICS ClASS DESIGN to do lhe actual drawing on the screen, and then tries to restore the color and shape to what they WCfe before the call: vo id Sha pe : :drawO consl { I/there is no good portable way of retrieving the current style fI _col or(lco lor.asj nt()); 1/ set color fUin c _stylc(ls .stylc O,ls. width()); II set style drawJ in read more..

  • Page - 523

    14 . 2 SHAPE virlual void drawJines O consl; /I let each derived class define its II own draw_linesO if it so chooses 1/ . . } ; slrue! Circle : Shape { /I . .. void draw_linesO consl: II"ovcr ride ~ Shape::drawJinesO /I ... } ; So, Shape's drawJinesO must somehow invoke one of Circle's functions if the Shape is a Circle and one of Reclangle's fun ctions read more..

  • Page - 524

    494 CHAPTER 14 • GRAPHICS CLASS DE SIGN What gui_mainO? So far, we haven't actually seen g ui_rnain O in Ollf code. lnstead we usc wail_for_bullon(), which invokes the display engine in a more simple- minded manner. Shape's moveO fu nction sim ply moves every poim stored rcl:uivc to the cu r- rc nt IX'sition: void Shape : :move(int dx, int d y) { /I move the read more..

  • Page - 525

    14 . 2 S H APE 1/ . .. op = op2; /I error: Shape's assignment is private } BUI copying is useful in so many places ! Just look at that push_baek(); without copying, it is hard even to usc vectors (push_backO puts a ropy of its argument into its vector). Why would anyone make trouble for programmers by preventing copy- ing? You prohibit the default copy read more..

  • Page - 526

    4% CHAPTER 14 • GRAPHICS C LASS D ESI G N If we want to copy objects of types where the default copy operations have been disabled, we can write an explicit function to do the job. Such a copy fune- lion is often called doneO . Obviously, you can write a done() only if the fune- lions for reading members are sufficient for expressing what is needed to read more..

  • Page - 527

    14 .] BASE AND DE RIVED CLA SSES Shape Circle Ellipse Text Line Open....j)Olyline Lines ~ .... =::k:::ed7='=t:i:::n~ e Closed....polyline Polygon "m e arrows point rrom a deri ved class to its base. Such diagrams help visualize class relations hips and orten decorate the blackboards or program mers. Com- pared to commercial rrameworks this is a tiny "class hierarchy" read more..

  • Page - 528

    ' 98 (HAPTER 14 • GRAPHICS ClASS DESIGN To handle a vi rtual function caU, we need (and have) one m o re piece of data in a Shape object: something to tell which function is really invoked when we call Shape's draw_linesO. The way that is usually done is to add the .lddrcss of a table of functio ns. This table is usually refe rred to as the vtbl (fol' read more..

  • Page - 529

    14 .3 BA SE AND DERIVED ClA SS ES Why are we telling you about vtbls and memory layout? Do you need to know about that to use object-oriented programming? No. However, many peo- ple strongly prefer to know how things are implemented (we are among those), and when people don't understand something, myths spring up. vVe have met people who were terrified of vinual read more..

  • Page - 530

    500 CHAPTER 14 • GRAPHI CS Cl ASS DESIGN virtual void Shape: :draw_linesO const {/- . .. -'} vo id Shape : : moveO { / - .. . -'} 14.3.3 Ove rriding 1/ error /10K When YOll want to oven-ide a virtual function , you mus t lise exactly the same name and type as in the base class. 1-or example: struct Circle: Shape { ); void drawJines(i nl) const; void read more..

  • Page - 531

    14 .3 BASE AND DERIVED C LASSES void call(con st B& b) { ) /I a D is J kind of e, so ca li n can accept a D /I a DO is a kind of 0 and a 0 is a kind of S, so call{) can accept a DO b.fO; b .gO; int ma inO { ) B b ; Dd ; DOdd ; call(b); call(d ); call(dd); b.f() ; b.g() ; d .fO; d .gO; dd .fO; dd .gO; You'll get B:: f read more..

  • Page - 532

    502 C HAPTER 14 • GRAPHICS ClASS DESIGN Protected: If a member is protected , its name can be used only by mem- bers of the class in which it is declared and members o f classes de rived from that. Public: If a member is public, it!! name can be used by all fu nctions. Or graphically: AU users IDerived class's members I IC lass's own members I .... j read more..

  • Page - 533

    14 .3 BAS E AN D D ERI VED CLAS SES posed to any particular kind of animal), "device dri ver" (as oppose to the d river for any particular kind of device), and "publication" (as opposed to any particular kind of book or magazine). In programs, abstract classes usually define interfaces to groups of related classes (class hiemrcliieJ). In § 14.2. 1, we read more..

  • Page - 534

    C HAPTER 14 • GRA PHI CS C LASS DESIGN class D3 : public 0 2 { pu bli c: void gO ; ); 0 3 d3; /I ok C lasses with pure virtual fun ctions tend to be pure interfaces; that is, they tend to have no data members (the data members will be in the derived classes) and con' sequently have no constructors (if there arc no data members to initialize, a read more..

  • Page - 535

    C H APTER 14 DRill ities) was written and compiled years before our graphics classes! We juSt define particular shapes and attachO them to Windows as Shal>es (Window::attachO takes a Shape& ar gument ; see §E.3). Furthennore, since class Shape doesn't know abOLn your graphics classes, you don't need to recompile Shape each time you de· fin e a new graphics interface read more..

  • Page - 536

    CHAPTER 14 • GRAPHICS CLASS DE SIG N 7. Defin e a class 82 with a pure virtual functi on pvf() . Define a class 021 with a string data member and a member functi on tha t overrides pvfO ; 021: : pvfO should output the value of the string. Define a class 022 that is just like 021 except that its data member is an int. Define a fun ction fO that read more..

  • Page - 537

    C HAPTER 14 EXERCISES Exercises 1. Defin e two c1asscs Smiley and Frowny, which are both derived from class Ci rcle and have two eyes and a mouth. Next, derive c1asscs from Smiley and Frowny, which add an appropriate hat to each. 2. Try to copy a Shape. What happens? 3. Define an abstract class and try to define an object of that lype. What happens? 4. Defin e read more..

  • Page - 538

    S08 C H APTER 14 • GRAPHI CS CLA SS DESIGN 14. Add an operation to Binary_tree that adds text to a node. You may have to modify the design of Binary_lree to implement this elegantly. Choose a way to identify a node; for example, you might give a string "Irrlr" for navigating left, right, right, left, and right down a binary tree (the root node would read more..

  • Page - 539

    ' ct.. ,. 15 Graphing Functions and Data "The best is the enemy of the good." -Voltaire I f you are in any empirical field, you need to graph data. If you are in any field that uses math to model phenomena, you need 1O graph functions. This chapter discusses basic mechanisms for such graphics. As usual, we show the usc of the mcdlanisms and also discuss read more..

  • Page - 540

    510 CHAPTE R 15 • GRAPHING FUNCTIONS AND DATA 15. 1 Introductio n 15.2 Graphin g simple fun ctions 15.3 Function 15.3.1 De fa ult a rg um e nt s 15.3.2 More elamples 15.4 Axis 15.1 Introduction 15.5 Approximatio n 15.6 Graphing data 15.6. 1 Read ingafile \5.6.2 C(" ne ra ll ayo ul 15.6.3 Scaling dala 15.6.4 Buildi ng th e grap h Compared to the read more..

  • Page - 541

    IS .2 G RA PHI NG SIMPL E FUNCTIONS Actually, sincc tltis chaptcr is about graphing functi ons, that horizontal linc isn't just a horizontallinc ; it is what wc gct from graphing thc fun ction double one(double) { return 1; } TIlis is about thc simplest function we could think of: il is a function of onc argu- ment that for evcry argument returns 1. Since we don read more..

  • Page - 542

    512 C H APTER 15 • G RAPHING FUNCTION S AND DATA Function s(one,,_min , r_max,orig, R_poinls ,x_scale,y_scale); Fu net ion s2(slope, r _m in, r _max, orig. " _poi nts,x_scale, y _seal e) ; Fu net ion s3(sq uare,r _mi n , r _max,orig, " _poi nts,x_scale, y _scale); win .attach(s); win .atta ch (s2); win .attach(sJ); win .waiCfor _buttonO; First, we define a read more..

  • Page - 543

    1 5.2 G RAPHING SIMPLE F UNCTIONS We always try to make our graphs self-explanatory. People don't always read the surrounding text and good diagrams get moved around, so that the surrounding text is "Iose" Anything we put in as part of the picture itself is most likely to be noticed and - if reasonable - most likely to help the reader understand what we read more..

  • Page - 544

    514 CHAPTER 15 • GRAPHING FUNCTIONS AND DATA Using xlength/x_scale as the number of notches ensures that a notch represents the values 1, 2,3, etc. Having the axes cross a t (0,0) is conventional. If you preFer them along the len a nd boltom edges as is conve ntional for the display of da m (sec §15.6), you can of course do that instead. Another way of distinguishing read more..

  • Page - 545

    15.3 FUNCTION Function (Fct f, double fl , double f2, Point orig, int count = 100, double xscale = 25, double yscaJe = 25); ) ; Function is a Shape with a constructor that generates a lot o f line segm ents and stores them in its Shape part. TIlose line segments approximate the values of function f. "n le values of f are calculated counl times for values read more..

  • Page - 546

    516 C HAPTER 15 • G RAPHING FUNC T IONS AND DATA This is equi valent to Function s (one, ,_min , , _max, orig, " _points, x_scale, y_scale); Function s2(slope, , _min , , _max,orig, " _points, x_scale, 25); Function s3(square, ,_min , , _max, orig, " _points, 25, 25) ; Function s4(sqrt. orig, , _min , ' _max, 100, 25, 25) ; Default arguments are read more..

  • Page - 547

    15 , 3 FU NCTION In other cases, such as Function , choosing a default is less easy ; we found the ones IVe used afcer a bit of c.'<perimemation and a f ailed attempt. Remember, you don't have to provide default arguments, and if you find it hard to provide one, just leave it to your user to specify that argument. 15.3.2 More examples \-\'e added a couple more read more..

  • Page - 548

    518 (HAPTER 15 • GRAPHING FUNCTIONS AND DATA Fu netion f1 (log,O.OOOOO1 , f _max,orig,200,30 ,30); Function f2(sin ,,_min,,_max,orig, 200,30,30); f2 .seCcolor(Color: : blue); fu nclion £J( COS,, _mi n .r _max,orig,200 ,30,30); Fu n clion f4( exp.' _min, r _max ,orig,200,30,30) i II logO logarithm, base e /I si nO /I cosO 1/ expO exponential cA x Since 10g(0) is undefin read more..

  • Page - 549

    15.4 AXIS ); void draw_lin esO const; void move(int dx, int dy); void set_eolor(Color e); Text la bel ; Lines notches; TIle label and notches objects are left public so that a user can manipulate them. For example, you can give the notches a different color from the line and moveO the labe l to a more convenient location. Axis is an example of an object com· read more..

  • Page - 550

    520 } } C HAPTER 15 • GRAPHING FUNCTIONS AND DATA for (int i = 0 ; k ni ++i) { notches.add(Point(xy.x,y), Point(xy.x+S,y»; y -= disl ; } la b e l. move(xy." - 1 0 ,.y. y-Ie ngth- l 0); break; /I put the label at top caseAx is : : z: e rror("z axi s not imple me nted "); } Compared to much real-world code, tills constructor is very simple, read more..

  • Page - 551

    1 5.5 APPROXIMATION Similarly, Axis:: move() moves all the parts of the Axis together: void Axis: : move(i nt dx, int dy) { ) Shape : :move(dx,dy) ; notches.move(dx,dy); label.move(dx,dy); 15.5 Approximation Here we give another small example of graphing a function: we "animaten the calculation of an exponential function. The purpose is to help you get a feel for read more..

  • Page - 552

    522 C H A PTER 15 • GRAP HIN G FU NCTIONS AND DATA return f ; For an alternative im plementation of fac O, sec exercise 1. Civen fa cO, we can compute the nth tern) of the sen es like this: double term (double X, int n) { return pow(x,n)/fac(n ); } 1/ nth term of series Given te rmO, calculating the exponential to the precision o f n terms is now read more..

  • Page - 553

    15.5 APP RO XIM AT ION fo r (int n = 0; n<50; ++n) { ostringstream ss; ) ss « "exp approxi mation; n== " « n ; wi n. sel_label (ss.strO. c_slrO); expN_numbe r_oCterms = n; /I gel next app roxi malion : Functio n e(expN, r_min, r_max,orig,200,x_scale ,y_scalel; win .attach(e) ; win .wait_fo r_b utto nO; win .d etach(e); ote the final detach(e) in that read more..

  • Page - 554

    524 C HAPTER 15 • GRAPH ING FUNCTIONS AN D DATA gel the approximation usingjusl one tcrm. NOle that we display the number of terms lIsed in the approximation in the window label: one nDtc:h". 1 That's the function exp1(x)==l , the approximation usingjusl one term of the se- quence. 1t malcilcs the exponential perfectly at (0,1), but we can do bette r: With twO read more..

  • Page - 555

    15.5 APPROXIMATION one noICh· , With ten terms we arc doing rather well. cspeciaJly for values larger than -3: If we don't think tOO much about it, we might believe that we could get bener and better ap proximations simply by using more and more tem lS. H owever, there are limits. and after 13 terms something strange starts to happen. Hrst, the approximations start read more..

  • Page - 556

    526 CHAPTER 15 • G RAPHING FUNCTIONS AND DATA one i"IOICI'I'" 1 Remember, nanling-point aritrunctic is nOt pure math . Floating-point numbe rs are simply as good an approximation LO real numbers as we can gel with a fixed number of bits. What happened was that our calculation started LO produce val- ues t.hat cou ldn 't be represented as doubles so that Olll' read more..

  • Page - 557

    15 .6 GRAPHING DATA . .. , , ' .f age 15.J;4 ------------1-------_ .g~ G-U .---- .,e li5' We' ll usc tltis example to discuss the progranulling problems involved in present- ing sLich data: Reading a file 5caJing dam to fit the window Displaying the data I ... ,bcling the graph We will not go into artistic details. Basically, this is "graphs for gceks,'" not read more..

  • Page - 558

    528 C H APTE R 15 • G RA PHI NG FUNCT IONS AND DATA way a function of me Olher. For example, for a (year,steel production) pair it would be quite reasonable to consider the steel production a fun ction of the year and display the data as a continuous line. Open_polyline (§ 13.6) is the obvious choice for graphing such data. If y should not be seen as a read more..

  • Page - 559

    15. <> GRAPHING DATA else ret urn is ; d =ddi return is ; TIlis is a straightfonvard application of the ideas from Chapler 10. If tills code isn't dear to you, please review tllat chapter. We didn't need to defme a Distribution type and a » operator. However, it simplifies tile code compared to a bnlte-force appl'Oadl of "juSt read tile numbers and graph read more..

  • Page - 560

    530 CHAPTER 15 • GRAPH ING FUNCTIO NS AND DATA 15.6.2 General layout So what do we want to appear on the screen? You can sec our answer at the be- ginning of §15.6. The data seems to ask for three Open_polylines - one for each age group. These graphs need to be labeled, and we decided lO write a "caption n for each line at the left-hand side of the window. read more..

  • Page - 561

    15.6 GRAP HI NG DATA We find that without sllch a "schematic view" of where things arc in our window and the symbolic constilllts lhat define it, we get lost and become frustrated when our ou tput doesn't reflect our wishes. 15.6.3 Scaling da ta Next we need to define how to fit our data into that space. We do that by scaling the data so that it fits read more..

  • Page - 562

    C HAPTER 15 • GRAPHING FUNCTIONS AND D ATA 15.6.4 Building the graph Finally, we have all the prerequisites for writing the graphing code in a reason- ably elegant way_ We start creating a \vindow a nd placing the axes: Window win(Point (l00, l00),xmax, ymax, "Aging Japan "); Axis x(Axis: :x, Poi nt(xoffset,ymax-yoffset) , xle ngth, (e nd_yea r-base_year)/10, "year read more..

  • Page - 563

    15 . 6 GRAPHIN G DATA O pe n_polyline childre n ; O pe n_po lyline adults; O pe n_po lyline aged ; Distribution d ; white (ifs>>d) { if (d .year<base_yea r II e nd_yea r<d .year) e rro r("yea r o ul of ra nge "); if (d .young+d.middle+d .old != 100) e rror(" pe rcenlages don 't add up"); inl x = "s(d .year): chi Idre n read more..

  • Page - 564

    534 ( H APTER 15 • GRAP H ING FUNC TI ONS AND DATA win.attach(x); win.attach(y); win.altach(currenl_year); All the code could be placed inside main O, but we pre fer to keep the helpe r classes Scale and Oistribution outSide together Wilh Dislribution's input operalOr. In case you have forgotten what we were producing, here is the outp ut again : _ A~nr: Jap .. read more..

  • Page - 565

    CHAPTER 15 REVIEW I. Graph the function double one(double x) ( return 1; ) in the range [-10, 11 ] with (0,0) at (300,300) using 400 points and no scaling (in the window). 2. C luUlge it to lise x scale 20 and y scale 20. 3. From now 0 11 use that range, scale, etc. for all graphs . 4. Add doubl e slope(double xl ( return xflj ) to the window. 5. read more..

  • Page - 566

    CHAPTER 15 • GRAPHING FUNCTIONS AND DATA 5. H ow do you make an x axis? Ay axis? 6. What is a dcfault argumem and when would you use one? 7. H ow do you add functions together? 8. H ow do you color and label a graphed function? 9. What do we mean when we say that a series approximates a function? 10. Why would you sketch out the layout of a graph read more..

  • Page - 567

    CHA PTER I S POSTSC RIPT 5. "Animate" (as in §IS.5) the series 1- 1/3 +1 /S- 1n +119- 1/11- .... It is known as Lcibniz's series and converges to piJ4. 6. Design and implement a bar graph class. Its basic data is a veclor<double> holding .N values, and eacl) value should be represented by a "bar" that is as a rectangle where the heiglll read more..

  • Page - 568

    read more..

  • Page - 569

    .t .. r 16 Graphical User Interfaces "Computing is not about computers any more. It is about living." - Nicho las Negropo nte A graphicaJ user interface (G U 1) allows a lIscr to interact with a program by pressing buttons , selecting from menus, cmering dam in various ways, and displaying textual and graphi- cal entities on a screen. TImt's what we are used read more..

  • Page - 570

    16.1 User interface alte rnatives 16.2 The " NeJCtH button 16.3 A simple window 16.3. 1 It c.arollback function 16.3.2 It wail loop 16.4 Bulton and other Widgets 16.4.1 Widgets 16.4.2 Bul10 ns 16.4.3 In_box and Out_box 16.4.4 M enus CHAPTE R 16 • GRA PHI CAL USE R INTERFACES 16.5 An example 16.6 Control inversion 16.7 Adding a menu 16.8 De bugging GUt code read more..

  • Page - 571

    16. 2 THE " NEXT w BUTTON munication bel\\'een the program and the screen is again textual (using streams of characters). A browser is a CUI application that translates SOUle of that text into graphical elements and translates the Ulouse clicks, etc. into textual data that can be sent back to the program . "Ib many, the lise of C U I is the essence o f read more..

  • Page - 572

    542 CHAPTER 16 • GRAP HI CA L US ER INTERFACES /I define variables ancVor compute values, produce output d n » va r; II wait for input /I define variables ,1n{Vor compute values, produce output d n » va r; /I wai t for input /I define variables an{Vor compute values, produce output d n »vari /I wait for input From an implementation point of view, these read more..

  • Page - 573

    16 .3 A SIMP LE W I NDOW Defin e a fun ction for the G U I to call 1'C1l the CUI about that butto n and that functio n Wait for the CU I to call our fu nctio n Let'S do that. A button is part of a Window, so (in Simple_window. h) we d efine ollr class Simple_window to contain a member nexC button : struct Simple_window: Graph_lib :: Window ( read more..

  • Page - 574

    544 C HAPTER 16 • GRAPHI CAL US ER INTERFACES The button_pushed member is a pretty obscure implementation detail; we usc it to keep track of whether the button has been pushed since last we executed next() .ln faCl, just about everything here is implementation details, and therefore declared private. Ignoring the implementation details, we sec: struct Simple_window: Graph_lib: read more..

  • Page - 575

    16.3 A SIMP LE WINDOW cb_nexi O to be called. We pass the address of cb_nexiO and the address of our Simple_window down through the layers of software ; some code "down there" t.hen calls cb_nexiO when lhe "Next" button is pressed. TIle CU I system (and the operaling system) can be used by programs writ- ten in a variety of languages , so it cannot read more..

  • Page - 576

    546 C HAPTER 16 • G RAPHI CAl US ER INTERFA C ES We could have wriuen all the code we wanted to exeCLlle in cb_next(), bUl we -like most good CUI programmers - prefer to keep messy low-level stuff separate from our nice user code, so we handle a callback with two functions: cb_nexlO simply maps the system conventions for a callback into a call to an ordinary read more..

  • Page - 577

    1 &.3 A SIMP LE WINDOW 16.3.2 A wait loop So, in this - our simplest case - what do we want done by Simple_window's next() each time the button is "pressed n ? Basically, we want an operation that stops the execution of our program at some point, giving us a chance to see what has been done so far. And, we want nextO to restart our program after read more..

  • Page - 578

    CHAPTER 16 • GRAP H ICAL USER INTERFACES Afte r wai ting, wait_for_buttonO needs to reset button_pus hed and redrawO the window to make su re that a ny cha nges we made can be seen o n the screen. So that's wha t it did . 16.4 Button and other Widgets We define a butto n like this: strucl Button : Widget { Bullon(Point xy, int w, int h, const read more..

  • Page - 579

    16.4 BU TTON AND OTH ER WIDGETS A Widget has two imeresting functions that we can usc for Bullon (and also for any other class de rived fro m Widget, e.g., a Menu ; sec § 16.7): hideO makes the Widget invisible. showO makes the Widget visible again. A Widget Sta TU out visible. Just like a Shaj>e, we can move{) a Widget in iu Window, and we must atlachO read more..

  • Page - 580

    55<1 C H APTER 16 • G RAPHI C AL USE R INTER FACES class Button: public Widget { public : }; Bulton{Point "Y, int ww, int hh, const string& s, Callback cb) :Widgel(xy,ww,hh,s,cb) {} void attach(Window& win); ll1at's aiL TIle attach() functio n contains all the (relatively) messy FLTK code. We have banished the explanation to Appendix E (not to be read read more..

  • Page - 581

    16.4 BUTTON AND OT HER WIDGETS Siring s = some_inbox.get_stringO; if (s =="") { /I deal with missing input An Ou C box is used to present some message to a user. In analogy to In_box, we ean putO eit.her integers or strings. §16.5 gives examples of the use of In_box and Out_box. We could have provided geUloatins-pointO , geCcomplexO, etc., but we did not read more..

  • Page - 582

    552 C HAPTER 16 • GRAPHICAL USER INTER FACE S 16.5 An example To gel a better feci for the basic CU I facili ties, consider the window for a simple application involving input, outpul, and a bit of graphics: This program allows a user to display a sequence of lines (an open polyline; § 13 .6) specified as a sequence of coordinate pairs. The idea is that the read more..

  • Page - 583

    16 .5 A N EXAMP LE Let'S define a class for rep resenting such windows. It is pretty straightfonvard: struCl lines_window : Window { lines_window{Point xy, int w, int h, const string& title ); Open_po lyline lines ; private : ) ; Button next_button ; Button quiCbutton ; 1/ add (next_x/nexcy) to lines In_box nexCx ; In_box nexCy; OuCbox xy_out; static void cb_next(Address, read more..

  • Page - 584

    554 ( HAPTER 16 • GRAP HICAL USER INTERFACES lines_window: : Lines_windo w(Point xy, int w, int h, consl string& title) : Window(xy, w,h,t itle), nexCbullo n(Point(,cmax()- l50,O), 70, 20, "Ned point", cb_nexl) , quiCbutlon{Point(x_max()-70,O), 70, 20, "Quil" , cb_quil), nexex(point(x_max ()-310,O), SO, 20, "next x: "), nexCy(Point(x_maxO-210,O), SO, 20, "next y: read more..

  • Page - 585

    16 .5 AN EXAMPLE void Lines_wi ndow: :n extO ( ) inl x = ncxCx.geU nl(); int y = nexcy.geUnIO; I ines.add (Poin I (x, y»; II update current position readout: slringslream ss; 55« '(' « x« ',' « y « ')'; xy _o ut . put(ss.SI rO); redrawO; 111at's all pretty obvious. We gel integer coordinates from the In_boxes lIsing geUnl O. We usc a slringstream to read more..

  • Page - 586

    556 CHAPTER 16 • GRAPHICAL U SER INTERFA CES just a call o f FLTK's run O. Looking further, we can find that rUIlO is simply the illfmile loop : while(wait(»i Except for a few implcmcillalion details postponed to Appendix E, we have seen all of the code that makes Ollr lines program run. We have seen all of the fund a- mental logic. So what happens? 16.6 read more..

  • Page - 587

    16. 7 ADDING A MENU One implication or this "control inv ersion" is that the order or execution is com- pletely determined by the actions or the user. l 11is complicates bOlh program or- ganization and debugging. It is hard to imagine what a user will do and hard to imagine every possible effect or a random sequence or callbacks. "Illis makes sys - tematic read more..

  • Page - 588

    '''' CHAPTER 16 • GRAPHI CAL USER INTERFA CES void c ha nge(Colo r c) ( lin es.seLeolor(c); ) /I . . . as before ... }; Writing all of those almost identical callback functions and "action" fun ctions is tedious. However, it is conceptually simple, and offering something that's signifi· camly simpler to type in is beyond the scope of this book. When a read more..

  • Page - 589

    16.7 ADDING A MENU Having played with this ror a while, we decided that what we really wamed was a '·pop·up menu "; that is, we didn 't want to spe nd precious screen space on a menu except when we are using it. So, we added a "color menu" button. When we press that, up pops the color menu, and when we have made a selection, the menu is read more..

  • Page - 590

    560 CHAPTER 16 • GRAPHICAL USE R INTE RFACES Note that the "color menu " hun an is now hidden. We don 't need it until we arc fin ished with the menu . Press "blue" and we get : ~nlC lines arc now blue and lhe "color m enu" button has reappeared. ~Io achieve this we added the "'color m enu" button and modified the "pressed " read more..

  • Page - 591

    16 .7 ADD I NG A MENU l ; /I actions invo ked by callbacks: void red_pressed O { changc(Color:: red ); hidc_menu() ; } void blue_pressed () ( change(Color: : blue) ; hide_menu O; } void black_pressedO (cha nge(Color: :black); hide_menu O;} void menu_pressed O { menu _button .hideO; color_menu .s howO; } void next(); void quitO; /I ca ll back fun ctions: stalic void read more..

  • Page - 592

    562 ) CHAPTER 16 • GRAP H ICAL US ER INTERFAC ES colOT_m enu .hide(); att ach (men u _button); attac h (lines); Note that the initializcrs arc in the same order as the data member definitions. 111at's the proper order in which to write the inicializers. In fact , member initial- izcrs are always cxccUlcd in the o rder their data members were declared. Some read more..

  • Page - 593

    16.8 DEBUGG I NG GU I CODE So what was the problem? Here is me correct version (from §16.5): int ma inO ( Lines_window win(Point(l oo, 100),600,400, "lines") ; re turn g ui_mal nO; We "forgot" the name of the Lines_window, win. Since we didn't actually need that name that seemed reasonable, but the compiler then decided that since we didn't usc that read more..

  • Page - 594

    564 CHAPTER 16 • GRAP HI CAL US ER INTER FAC ES Me nu disaslers(Point (100, 100),60,20,Me nu : : horizo nta l, "disaste rs "); load _ d isasle r _m e n u(disasle rs); win .a llac h(disasle rs); 1/ . . . ~fbis w ill not work. All those butto ns arc local to the loa d_disaster_me nu fun c- tion and attaching them to a menu will not change read more..

  • Page - 595

    CHAPTER 16 EXER CISES 3. What is a software layer? 4. Why would you want to layer software? 5. What is the fundament."lI problem when communicating with an operat· ing system from C++? 6. What is a callback? 7. What is a widget? 8. What is another name ror widget? 9. What docs the acronym FLTK mean? 10. How do you pronounce FLTK? II. What other CU I read more..

  • Page - 596

    566 ( HAPTER 1 6 • GRAPHICAL USER INTERFA CES 4. Make a menu with items mal make a circle, a square, an equilateral tri- angle, and <l hexagon, respectively. Make an input box (or two) for giv- ing a coordinate pair, and place the shape made by pressing a menu item at that coordinate. Sorry, no drag and drop. 5. Write a program that draws a shape of your read more..

  • Page - 597

    Part III Data and Algorithms read more..

  • Page - 598

    read more..

  • Page - 599

    -'. . "'- '7 Vector and Free Store "Use vector as the default! " -Alex Stepanov T his chapter and the next four describe the containers and algorithms part of the C++ standard library, traditionally called tllC STL. We describe the key fa cilities fro m the S11.. and some o f their uses. In additio n, we present the key design and programming techniques read more..

  • Page - 600

    570 CHAPTER 17 • VECTOR AND FREE STORE 17.1 Introduction 17.2 vecto r basics 17.3 Memory, addresses, and pointers 17.3. 1 The sizeof o perator 17.4 Free store and pointers 17.4.1 Free·slore allocation 17.4.2 Acce ss through pointers 17.4.3 Ranges 17.4.4 Initialization 17.4.5 The null pointer 17.4.6 Free·slore d ealloca lion 17.5 Destructors 17.5. 1 Gene rated destructors 17.5.2 read more..

  • Page - 601

    17.1 INTR ODUCTION available as part or every C++ implementation LO ease the writing and testing or Ollr libraries. We have already seen and used one or the standard library's most usdul algorithms: sartO. We approach the standard library vecto r through a series or increasingly so- phisticated vecto r implementations. First, we build a very simple vecto r. 111en, we see read more..

  • Page - 602

    572 CHAPTER 17 • VECTOR AND FREE STORE "implementation details" just as we do the device physics. However, if we did that, yo u would l10ljust have to "believe in magic"; you would be unable to implement a new container (should you need one, and tlml's not uncommon). Also, you would be unable to read huge amounts of C and C++ code that di rectl y uses m read more..

  • Page - 603

    1 7. 2 V ECTO R BASICS size and one to hold its clements. But how do we represent a set of clements where the number of elements CU I vary? We could lise a standard library vecto r, but that would - in this conte..xt - be cheating: we are building a vector here. So, how d o we represe nt that a rrow in the drawing above? Consider d oing without it. read more..

  • Page - 604

    574 C HAPTER 17 • VE C TOR AN D FREE STO RE 17.3 Memory, addresses, and pointers A computer's m emory is a sequence of bytes. We can number the bytes from 0 to the last one. We call such "n number that indicates a locatio n in mCIllOlY'" an (u/dreSJ. Yo u can think of an address as a kind of integer value. ' 11C first byte of memory has read more..

  • Page - 605

    17.3 MEMORY, ADDRESSES, AND PO IN TERS cout « "pc== " « pc« " i contents of pc== " « 'pc« "\n "; cou f « "pi=="« pi« It; contents of pi==" « ' pi « "\n"i ' Ille olltpm for ' pc will be lhe character c and lhe omput for ' pi will be lhe inte- ger 17. TIle output for pc and pi will vary read more..

  • Page - 606

    57. CHAPTER 17 • VECTOR AND FREE STORE Exacliy how lhe compiler allocates variables in memory is implementation de- fined , but we might very well get something like this: ehl: pi : Now, had the compiler allowed the code, we would have been writing 12345 to the memory sLarting at &chl. TImt would dcfmi tcly have changed the value of some nearby memo ry, such as read more..

  • Page - 607

    17 .4 FREE STORE AND POINTERS TRY THI S Execute the example above and see wha t you get. Then extend the example to determine the size of baal, double, and some other type. 111e size of a type is no! guaranteed to be the same on every implementation of C++. 111cse d.'ys, sizeof(int) is typically 4 on a la ptop or desktop machine. With an 8-bit byte, that read more..

  • Page - 608

    578 C HAPTER 17 • VECTOR AND FR EE STO RE TIle C++ language m akes this "free store " (also called the heap) available lhrough an operator called ne w. Fo r example: double p = ne w double(4) ; /I al locate 4 doubles on the free store This asks the C++ run-time system to allocate 4 double s on the free Slo re and re- turn a pointer to the read more..

  • Page - 609

    17.4 FREE STORE ANO POINTERS double pd = new double; /I allocate one double double· qd = new double[n) ; 1/ allocate n doubles (an array of n doubles) Note thlt the number of objects allocated can be a variable. l1tat's important becausc that allows us to sclca how Ill,my objccts we allocate at rUIl time. If n is 2, we get pi : qi: Pointers to objects of read more..

  • Page - 610

    580 . p = 7.7; pl2J = 9.9; CHAPTER 17 • VECTOR AND FREE STO RE II write to the (first) object I>ointed to by p II write to the 3rd objecl pointed to by p A pointer poims to an object in m emory. The "contents o r n operator (also called the dmference operator) allows liS to read and write the object pointed to by a pointer p: double x = .p; read more..

  • Page - 611

    17. 4 FREE STO RE AND POINTERS pd : pdl-31 : pd l-21: pd l-11 : pdlOI: pdl1l : pd121: pd131 : pd141 : -3.3 2.2 4.4 We ha ve no idea what the memory locations marked pdI-3] and pd[4] are used ror, H owever, we d o kn ow that they weren't meant 1.0 be lIsed as pan or ollr array o r three double s pointed to by pd . M ost likely, they arc p.1.rts read more..

  • Page - 612

    50' CHAPTER 17 • VECTOR ANO FREE STORE By now, we hope that you are asking, "But why can't pointers remember the size?" Obviously, we could design a "pointer" that did exactly that - a vector is almost that, and if you look through the C++ literature and libraries, you'll find many "smart poimers" that compensate for weaknesses of the read more..

  • Page - 613

    17. 4 FREE STORE AND POIN TER S Now p4 points to objects of type do uble co ntai ning lhe values 0.0, 1.0, 2.0, 3.0, a nd 4 .0. As usual, we should worry abo ut un initialized objects and make sure we give them a val ue before we read them . Beware that compilers often have a "debug mode" where they by default initialize every variable to a read more..

  • Page - 614

    S84 CHAPTER 17 • VE C TO R ANO FREE STORE We need 10 use the null poimer when we have a pointer that sometimes points to an object and sometimes nolo That's rarer than many people think ; COIl - sider: if YOli don't have an object for a pointer to point to, why did you define that pointer? Couldn't YOLI wait until you have an object? 17.4.6 Free-store read more..

  • Page - 615

    17 .4 FREE STO RE A ND PO IN TER S Incidentally, this example demo nstrates one of the major reasons for using free store: \ve can create objects in a function and pass them back to a caller. '11ere arc two fonns of delete : delete p frees the memory for an individual object allocated by new. deletel l p frees the memory for an array of objects allocated by read more..

  • Page - 616

    CHAPTER 17 • V ECTOR AND FREE STORE library should not leak memory because someone might use it as part of a system lim shouldn 't leak memory. In general, it is sim ply a good idea not to leak. Many programm ers consider leaks as proof of sloppiness. However, that's slightly over- stating the point. When you run a program under an operating system (Uni\:, read more..

  • Page - 617

    1 7.5 DESTRUCTORS void f(int nJ ( ) vector v(n); II . .. /I allocate n doubles When we leave fO , the elements creaLCd on the free store by v are nm freed. We could define a clean_upO operation for vector and call that: void f2 (int nl ( vector v(n); /I define a vector (which allocates another n ints) 11 • •• usev ... v.clean_up(); /I clean_upO deletes read more..

  • Page - 618

    588 Given that, we can write void f3(int n) { C H A PTER 17 • VECTO R AND FREE STORE int- p = new int(n]; /I allocate n inls vector v(n) i /I define a vec tor (which alloca tes anot her n ints) II ... use pand v .. . delete(] p; /I deallocate the ints } 1/ vector automatically cleans up after v Suddenl y, that delete[) looks rather tedio us and read more..

  • Page - 619

    17 . 5 DESTRU CTORS indeed often how the obviolls and necessary guarantee that destructors are called is implemented. TIle destructors for members - and for bases - arc implicitly called from a derived class deslruclOr (whether user-defined or generated). Basically, alJ the niles add up to: "Destructors arc cal led when the object is destroyed " (by going out of scope, read more..

  • Page - 620

    590 C HAPTER 17 • VECTOR AND FR EE STORE from fclOr n c calling fu nction fO has no idea that q points LO a Text ; all it knows is lhat it points to a Shape . 111cn hO\,.. docs delete p get to c."1l1 Text's dCSlnlClor? In §14.2. 1, we breezed past the fact that Shape has a destruCLOr. In fact, Shape has a virtua l dCSlIlictOf. That's the key. read more..

  • Page - 621

    17 . 7 POIN TE RS TO ClASS O I~ JECT S ) ; int sizeO const { return sz; ) doubl e gel(int n) { retu rn elem!n]; } void set(inl n, do uble v) { ele m!nl=v; ) /I the current size /I access: read II access: write Both gelO and sel() access the clements using the [ J operator on the elem pointer: elem[n). Now we can make a vector of do ubles and read more..

  • Page - 622

    5'2 ( HA PTER 1 7 • VECTO R AND FREE STORE void ffO { ) veclo r· q = ((4); /I use 0q de le te q ; /I free veclor on free store NOle that when we d ele te a vecto r, its destructor is called. For example: vector· p = n ew veclor(S)j d elete Pi /I allocate a vector on free 5tore /I deallocate Creating the vecto r 011 the free store, Lhe ne read more..

  • Page - 623

    17.8 M ESS IN G WIT H TYPE S: VOIO' ANO CAS TS vector v (4 ); int " = v .size(); double d = v_gel(3); Similarly, all classes support the operator - > (arrow) for accessing members, given a pointer to an obj ect: vector· p = new veclor(4); inl " = p ->size(); double d = p->geH3); Like . (dot), -> ( arrow) can be used for both data members and read more..

  • Page - 624

    594 (HAPTER 17 • VECTO R AND FREE STOR E A pointer to any object type can be assigned to a void ". For e xample: void " pvl = new int i /I O K: int· converts to void ' void" pv2 = new doubleflO]; /! OK: double" converts to void" Since the compiler doesn't know what a void" points to, we must tell it : void f(void " pv) { read more..

  • Page - 625

    17 .9 POINTERS AN D REFERENCES in : I OxFF I O~r:-"----' III the second example, cons,-cast stri ps the co nsl from the co nsl Buffe r· c l.lIed p. Presumabl y, we kllOW what we are doing. At least stat ic_cast can't mess with the poimer/imeger distinction o r w ith "const-ness," so prefer sia lic_cast if you feci the need for a cast. When you read more..

  • Page - 626

    596 C HAPTER 17 • VE C TOR ANO FR EE STORE The equivalent example for references is inty = 10; int&r =y; r = 7; inty2=r; int& ,2 = y2; r2 = ' i r = &y2; II the & is in the type, not in the inilial izer /I assign to y through r (no' needed) /I read y through r (no' needed) /I gel a reference 10 another int /I the va lue of y read more..

  • Page - 627

    17 .9 POINTER S AND REFE RENCE S U sing a pointer arh'llment alerts the programmer tha t something migh t be changed. For example: inl x = 7; incr_p(&x) lIthe & is needed incr_r(x); "Il,e nee d to usc & in incr_p(&x) ale rts the user that x might be changed . In con- trast, incr_r(x) "looks innocent." Thi s leads to a slight preference for read more..

  • Page - 628

    C HAPTER 17 • VECTOR AND FREE STO RE 17.9.2 Pointers, references, and inh eritance In § 14.3, we saw how a de ri ved class, such as Circle, could be used where an o b- ject of its public base class Shape was required. We can express that idea in terms of pointers or references: a Circle- can be implicitly converted to a Shape* be- cause Sha pe is a read more..

  • Page - 629

    17. 9 PO INTER S AND REFERE NCES ) ; link · prey; l ink· S UCC i link(co nsl string& v, link · p = 0, link- s = 0) : value(v), p rev( p), s ucc(s) ( ) 111at is, given a link, we can get to its successor using the S UCt pointer and to its predecessor using the pre y poimer. We usc the null pointer to indicate that a link doesn't have read more..

  • Page - 630

    600 C HAPTER 17 - VE C TOR AND FREE STO RE link - insert(link - p, link · n) II insert n before p; relurn n ( ) if (n==O) return Pi if (p==O) return n; n->succ = P i II P comes after n if (p->prev) p ->prev->s ucc = n j n->prev = p-> prevj /I p's predecessor becomes n's predecessor p->prev = n j II n becomes p's predecessor return n j Given read more..

  • Page - 631

    17.9 POINTERS AND REFER ENC ES link " add {link " p, link · n) /I inserl n afte r p; return n { 1/ muc h like inserl (see exe rcise 11) ) link " era se(link " p) /I re move 'p from li sl; return p's successor { ) if (p==O) re turn 0 ; if (p->su cc) p->succ- >prev = p-> prev; if (p->prev) p-> prey->succ = p ->succ; re turn p- read more..

  • Page - 632

    602 ( HAPTER 17 • VECTO R AND FREE STO RE NOle the lise of the postfix n++ . This form of increment ("posl·incremcm") yields the value before the incrcmelll as its value. 1 7.9.5 list use ru a little exercise, let's build 1'.\10 lists: link· no rsc-!;ods = ne w Link("Tho r"); no rsc....god s = inser t( no rsc....gods,new Link(" Odin read more..

  • Page - 633

    17.10 THE THIS POINTER erase(p); greek_gods = inserl(greek_gods, p); ) While we were at it, we also corrected the second bug: when we insert Zeus IxjQl"e the first Creek god, we need to make gree k--sods point LO Zeus's Link. Pointers are extremely useful and nexible, but subtle. Finally, let's print out those IisLS: void pri nt_all(Li nk- p) { coul «"{ "; read more..

  • Page - 634

    CHAPTER 17 • VECTO R AND FREE STO RE Link(const string& v, Link · p = 0, Link " s = 0 ) : value(v), prev(p), succ(s) ( ) Link " insert(Link " n) ; /I insert n before this object Link " add(Link" n) ; /I insert n after this object Link " e rase() ; /I remove this object from list Link " (ind(const string& s); /I find s in list canst read more..

  • Page - 635

    1 7. 10 THE T HI S P O INTER Link - Link :: insert(Link- n) { /I insert n before this object; return n } if (n==O) return thi s; if (this==O) return n; n->su cc = this; II this object comes a(ter n if (t his- >prev) thi s- >prev->succ = n; n->prev = thi s->prev; /I this object's predecessor /I becomes n's predecessor this->prev = n ; /I n read more..

  • Page - 636

    CHAPTER 17 - VECTOR AND FREE STORE 17.10.1 More link use Having dcalt wilh the implemcntation issues, we can see how the use now looks: Linke norse....gods = new Link( tlThor"); norse....gods = norse....gods->insert(new Link("Odin tl »; norse_god s = norse....gods->inserl(n ew Link(tlZeustl »; norse....gods = norse....gods->i nse rl(new Link(" Freia ")); Linke read more..

  • Page - 637

    C H APTER 17 DR ILL prinCall(norsc_sods); (out«''\n ''; pri nt_all(greek-8ods); cout«"\n"; 111is should again hrive { Freia, Odin , Thor) { Zeu s, Poseidon, Ares, Athena, Hera } So, which version do you like better: the one where insertO, etc. arc member fu nctions or the one where they are freestanding functions? In this case the dif· ferences don't matter read more..

  • Page - 638

    CHAPTER 17 • VEC TOR AND FREE STORE The second part focuses on pointers and their relation to arrays. Using print_array() from the last drill: l. Allocate an int , i11itialize it to 7, and assign its add ress to a variable pl . 2. Print out the value o f pl and of the int it points to. 3. Allocate an array of seven ints; initialize it to 1,2,4,8, etc.; read more..

  • Page - 639

    CHAPTER 17 EXERCISE S Terms address address of: & alloe-ltion cast container comcnts o f: • deallocation delete de lete[J dereference Exercises desuuctor free store link list member acccss: -> member destructor memory memory leak new null poimer pointer range resource leak subscripting subscript: [ J this type conversion virtual destructor void · 1. What is the outpm read more..

  • Page - 640

    61. CHAPTER 17 • V ECTOR AND FREE STO RE 9. Which way does lhe stack grow: up (toward higher addresses) or down (to- ward lower addresses)? Which way does the free store initially grow (that is, before you usc delete)? Wrile a program to dctcnninc the answers. 10. Look at your solution of exercise 7. Is there any way thal input could gel the array to overflow; read more..

  • Page - 641

    I. r 18 Vectors and Arrays "Caveat empto r! " - Good advice T his chapter describes how vectors are copied and accessed through subscripting. To do that , we discuss copying in general an d consider vector's relation to lhe lower-level notion of arrays . We present arrays' relation to pointers and consider the problems arising from their use. We also present the read more..

  • Page - 642

    i12 18.1 Introduction 18.2 Copying 18.2.1 Copy constructors 18.2.2 Copy assignme nts 18.2.3 Copy terminology 18.3 Essential operations 18.3.1 Explicit co nslructo rs 18.3.2 Debugging co nslructo rs and deslruclors 18.4 Access to vec tor elemen ts 18.4. 1 Oye rloadi ng on consl 18.1 Introduction CHAPTER 18 • VECTORS AND ARRAYS 18.5 Arrays 18.5. 1 Pointe rs 10 array elemenls read more..

  • Page - 643

    18.2 C OPY I N G Inevitably, we get to discuss how memory is manipulated when we don't have higher-Ievcltypcs such as vector and string. We examine arrays and point- ers, their relationshi p, their usc, and the traps and pitfalls of their use. This is es- semial information to anyone who geLS to work with low-level uses of C++ or C code. Please note that the read more..

  • Page - 644

    ,1' CHA PTER 18 • VECTORS AND ARRAYS what docs it do wrong? How? And why? Once we know that, we Ct"Ul probably fix the problems. More importantly, we have a chance to recognize and avoid similar problems when we sec them in other contexts. TIle default meaning of copying fol' a class is "Copy all the data members." 11mt often makes perfect sense. For read more..

  • Page - 645

    18 .2 CO PYING defined to take as its argument a reference LO the object from which to copy. So, for class vector we need veclor(const veclor&); ~nlis constructor will be called when we try LO initialize o ne vector with another. We pass by reference because we (obviously) don't want LO copy the argument of the constructor that defines copying. We pass by canst read more..

  • Page - 646

    616 C HAPTER 18 • VEC TOR S AND ARRAYS Given this copy constructor, consider again our example : vector \'2 = v; lllis dc rmition will initialize v2 by a call of vector's copy constructor with v as its argument. Again given a vector wilh three clements, we now gel v: [3~~==~----'[1 ==~====~2~.2CJ v2: ~3=r=====r-------[=====r=====r~2.~2~ Given that, the destructor can do read more..

  • Page - 647

    18 .2 COPYING ) v.sel (2,2.2); veclar v2(4); v2 = v; /I . .. II assignment: what ha ppens here? We would like v2 to be a copy of v (and that 's what the standard library vector does), but since we have said nothing about the meaning of assignment of our veclor, the default assignment is used ; that is, the assignment is a memberwise copy so that v2's sz read more..

  • Page - 648

    618 CHAPTER 18 • VECTO RS AND A RR AY S Assignment is a bit mo re complicated than construction because we must deal with the old clc mclllS. OUf bas ic stra tegy is to make a copy of the elements fro m the source vecto r: do uble- p = new do ubl e[a.5z)i copy(a ); /I a llocate new space 111cn we free the old clements from the target vector : de read more..

  • Page - 649

    18 .2 COPYING Sh,lI/ollJ copy copics o nly a pointer so that thc twO pointcrs now refer to thc samc objcct. 111at's what poimers and references do. Deej) copy copies what a pointer points to so that the two po inters now refer to distinct objcctS. That's what vectors, strings, etc. do. We defin e copy constniclOrs and copy assignments when we want deep copy for read more..

  • Page - 650

    ,2. CHAPTER 18 • VECTORS AND ARRAYS 18.3 Essential operations We ha ve now reached the point where we can discuss how to decide which CO Il- structors a class should have, whether it should have a destructo r, and whether you need to provide a copy assignment. There arc five essential operations to cons ider : Constructors from one or m ore arguments Default read more..

  • Page - 651

    18.3 ESSENTIAL OPERATIO NS vector, the empty vedor serves well . For every type T, TO is the default value, if a default exists. For example, doubleO is 0.0, stringO is '''' , and vector<inl>() is the empty vector ori nts. A class needs a destructor if it acquires resources. A resource is something you "get from somewhere" and that you must give back once read more..

  • Page - 652

    622 class vector { }; 1/ . .. vector(inf); 1/ . .. vector v = 10; v= 20; CHAPTER 18 • VEC TOR S AND ARRAYS II odd: makes a vector of 10 doubles II eh? Assigns a new vector of 20 doub les to v void f(const vector&); f(10); /I eh? Calls f with a new vector of 10 doubles It seems we are getting m ore than we have bargained for. Fortunately, it read more..

  • Page - 653

    18 .3 ESS ENTIAL O PERATIONS Whenever an object of type X is created, one of X's constructors is invoked. Whenevef an objeet of type X is destfoyed, X's dest1uctor is invoked. A destructOf is called whenever an object of its class is destroyed ; tha t happens when names go OUi of scope, the program terminates, or delete is used on a pointef to an object. A read more..

  • Page - 654

    624 ( loe2 = copy(l oc) ; loe2 = copy2(1oc); X loc3(6); X& r = re Uo(1oc); delete make(7); delete make(8); veclor<X> v(4 ); xx loc4; X· P = new X(9); delete Pi X· pp = n ew X[5] i delete pp ; Try executing that. TRY THIS C HAP TE R 18 • VE C TO RS AND ARRAYS /I an X on the free store /I an array of Xs on the free store We really read more..

  • Page - 655

    18.4 ACC ESS TO VEC TOR ELEMEN TS 18.4 Access to vector elements So far (§ 17.6), we have used se(() and getO member fun ctions to access elements. Such uses are verbose and ugly. We want our usual subscript nouuion: v[i). The way to get that is to defin e a member function called operato r[J. Here is our frrst (naive) tly: class vecto r { int sz; do read more..

  • Page - 656

    .,6 veclaT v(10); for (in! i=Oj i<v.size(); ++i) ( ·v[i] = i; cout« · v[i] ; ) CHAPTER 18 • VECTO RS AND A RRAY S /I works, but sti ll too ugly Here, v[i] is interpreted as a call v.operator[] (i), and that call rctums a pointer 10 v's clement number i. The problem is that ""'C have to write · to dereference that pointer to get to the read more..

  • Page - 657

    1 a.s ARRAYS double operator[J(inl n) con st; II for const vectors } ; We obviollsly couldn't return a double& from the eonst version, so we re- turned a double value. We could equally well have returned a const double &, but since a double is a small object there wo uld be no point in returning a refer- ence (§8.5.6) s o we decided to pass it back by read more..

  • Page - 658

    628 void f(int n J ( ) char lac[20); inllai(60)i double ladln ]; II . C HAPTER 18 • VE C TO RS AND A RR A YS II loca l array; " I ives~ until the end of scope /I error: array size not a constant Note the limitation: the number of clements of a named arm)' must be known at compile time. If you want the number of eiClUclllS to be a variable, read more..

  • Page - 659

    18 . 5 A RR A YS We now have a pointer p to the double known as a d (51: We can subscript and dereference lhat pointer: . p =7; pl'l = 6, pl-31 = 9, Wegct TIlat is, we can subscript the pointer with both positive and negative numbers. As long as the res ulting clement is in range, all is well. However, access outs ide the ra nge or the array pointed read more..

  • Page - 660

    C HAPTER 18 • VECTORS AND ARRAY S We get p: Using +, - , +=, and -= to move pointers around is called painter tln·tflmctic. Obvi· ollsly, if we do that, we have to take great care to ensure that the result is nOt a pointer to memory outside the array: p += 1000; doub le d = .p; . p = 12.34; /I insane: p points into an array with just 10 e read more..

  • Page - 661

    18.5 ARRAY S do uble p1 = &ad(O], double· ,,2 = p1+7, double" p3 = &pll71; if (p2! = p3) coul « "impossible!\n"; Mainly, the reason is historical. TIlese n iles werc crafted for C decades ago and can't be re moved without brcaking a lot of code. Partly, there can be some con- venience gained using pointer arithmetic in some important low· level read more..

  • Page - 662

    632 char lois [l00000J; void fO { ) int nchar = slrlen(lots); /I . . . C HAPTER 18 • VECTORS AND ARRAYS Naively (and quite reasonably), you might expect this call to copy the 100,000 characters specified as the argument to sirlen(), blll mat's not what happens. In- stead, lhe argument declaration char pll is considered equivalent to char· p and the call strle n(lo read more..

  • Page - 663

    18 . 5 ARRAYS If wc want assignmcnt, wc havc to use somcthing like vector . TI1C vector eCluivaicnt to the copying code above is veclor<inl> x(100); veclor<inl> y(100); II. x = y; /I copy 100 ints 18.5.3 Array initialization Arrays have one significant advantage over vectors and Olhcr llser-defmcd con- tainers: the C++ language provides notational support for the read more..

  • Page - 664

    634 CHAPTER 18 • VECTORS AND ARRAYS Actually, we don't have to define slrlenO because it is a standard library function defmed in the <slring .h> header (§27.S, §B.1O.3). Note that strlenO coums the characters, but not the temlinating 0; that is, YOli need 11+ I chars LO SLOre /I char- acters in a C-stylc string. Only character arrays can be initialized by read more..

  • Page - 665

    18.5 ARRAY S Obviollsly, in real-world programs, this typicaJly occurs when there is some code in between the initialization and the usc. In particular, passing p lO a function or receiving it as the result from a function arc common examples. We prefer not to pass null poimers around, but if you have la, test for the null pointer before lise: and int o. p = read more..

  • Page - 666

    '36 CH A PTER 18 • V ECTOR S AND A RRAY S Be careful with the first and last elemenLS of a loop, and try not to pass arrays around as poimcrs to their first elements. Instead usc vectors. If you really must usc an array in morc than one function (passing it as an argument), then be extra careful and pass its size along. DOll'l access through a deleted read more..

  • Page - 667

    18 . 6 EXAMPLES : PAliNDROME II. return x; 1/1he vector x is destroyed here II. vector& p = UO; II . . . p!41 = 15; 1/ ouch! Qtite a rew compilers catch this variant or the return problem . It is cOlllmon ror programmers to underesumate these problems. However, many experienced programmers have been defeated by the innumerable varia- tions and combinations o r read more..

  • Page - 668

    CHAPTER 18 • VECTORS AND AR RAYS int last = s. lengthO- l; I/inde)( of last leller while (first < last) ( II we haven't reached the middle if (s[first] !=s[last]) re turn fa lse; ) ++first; -- last; return true; II move forward II move backward We return true if we reach the middle without finding a difference. We suggest that you look at this code to read more..

  • Page - 669

    18 .6 EXAMPL ES: PALINDROM E while (first < last) ( /I we haven't reached the middle if (sl first)l=s[lasl» r eturn fal se; ++first i -- last; return Irue ; II move for.vard 1/ move backwa rd To exercise is_palindromeO, we first have to get characters read into the ar ray. One way to do I.hat safely (i.e., without risk of overflowing the array) is like this: read more..

  • Page - 670

    C H APTE R 18 • V ECTORS AND ARRAY S We consider this "array solution" significantly messier than the "string sol u- tion," and it gets much worse if we try to seriously deal with the possibility of long strings. See exercise 10. 18.6.3 Palindromes using pointers Instead of using indices to identify characters, we could use pointers: bool is_palindrome(const read more..

  • Page - 671

    ( H APTE R 18 ORl ll if (lirsklasl) { if (* firsl!=*last) return false ; retu rn is_pali nd rom e( ++fi rsl ,-- Iasl) ; ) return tru e ; ) 111is code becomes obvious when we rephrase the definition o f palilldrome: a word is a Ih'llindrome if the first and the last characters arc the same and if the substring yo u gel by removing the firs t an d the read more..

  • Page - 672

    642 CHAPTER 1 B • VECTORS AND ARRAYS h. Copy the values from gv intO Iv. c. Print out lhe elements of Iv. d. Defmc a local veclor<int> 1\12 ; initialize it to be a copy of the argu- ment array. e. Print Ollt the clements of Iv2. 4. In m ain() : a . Gall fO with gv as its argumell t. b . Define a ve ctor<int> vv, and initialize it with the read more..

  • Page - 673

    CHAPTE R 18 EXERCISES Exercises 1. Write a function, char· strdup(const char·), that copies a C-style string into memory it allocates on the free store. Do not usc any sta.ndard library functions. Do not use subscripting; usc the dereference operator · instead. 2. Write a function, char · findx(const char· s, const char · xl , that finds the frrst occurrence of read more..

  • Page - 674

    644 C HAPTER 18 • VECTORS AND ARRAYS 10. Look at the "array sol ution" to the palindrome problem in §lB.6.2. FIX it to deal with long strings by (a) reporting if an input string was tOO long and (b) allowing an arbitrarily long string. Comment on the complexity of the tWO versions. 11. Look up (e.g. , on the web) skiJ) list and implement that kind read more..

  • Page - 675

    .L r 19 Vector, Templates, and Exceptions "Success is never fmal ." -Winston Churchill T his chapter completes the des ign and implementation of the most common and most useful STL container : vector. H ere, we show how to implement comainers \vhere the number of elements can vary, how to specify containers where the cle- ment type is a parameter, and how to read more..

  • Page - 676

    CHAPTER 19 • VECTOR, TEMPLATES, AND EXCEPTION S 19.1 The problems 19.2 Cha nging size 19.2.1 Representation 19.2.2 reserve and capacity 19.2.3 resize 19.2.4 push_back 19.2.5 A.ssignment 19.2.6 Our vector so far 19.3 Templates 19.3. 1 Types as template parameters 19.3.2 Generic programming 19.3.3 Containers and inheritance ' 9.3. 4 Integers as template parameters 19.3.5 Template read more..

  • Page - 677

    19.1 THE PROBLEMS int n ; cin»n; vc.resize(n); 1/ make vc have n elements Obviously, it is nice and useful to have vectors that allow this, but why is it im- portant from a programming poilll of view? What makes it interesting to some- one collecting useful progranuning techniques for future use? We arc usin g two kinds of nexibility. We have a single elllil"Y, the read more..

  • Page - 678

    ... } } ( HAPTER 19 • VE CTOR , TEMPLATES, AND EX C EPTIONS delete p; p = q ; (· p )[n] = d i ++n; '1131 '5 not prell)'. Are you convinced thai we gOI it right? How can you be sure? NoLC how we suddenly started to use poimers and explicit melllory management. What we did was to imitate the style of programming we have to usc when we are read more..

  • Page - 679

    19. 2 C HANG ING SIZE Well , data structures are the key to most significant applications. There are many thick and useful books abom how to organize data, and much of that in- forma tion could be described as answers to the question "How do 1 best store my data?" So, the ans wer is that we need many difTerem kinds of containers, but it is too large a read more..

  • Page - 680

    650 CHAPTER 19 • VECTOR , TEMPLATES , AND EXCE PTI O NS So, we can optimize our programs by anticipating such changes in size. In fact, all vector implementations keep track of both the number of elements and an amo unt of "free spa ce n reserved for "future expansion." Fo r example: class vector { /I number of elements /I address of fi rst element read more..

  • Page - 681

    19 .2 CHANGING SIZE 111at gives _____ ._0 ___ 0_ .. _ ... sz : elem : space : § . · .. L . --- ---- ----- ............ -.. ..; : " "1" -- .. ------ _. -- --.- ~nlm one-beyond-the-end clement is completely imaginary. The default constructor docs no free-store alloc.'luon and occupies minimal storage (but see exercise 16)_ Please note that Ollr vector read more..

  • Page - 682

    .52 (HAPTER 19 • VECTOR , TEMPLATES , AND EX C EPTI O NS 19.2.3 resize Given reserveO, implementing resize() for ollr vector is fairl y simple. 'A'e have to handle several cases: TIle new size is larger than the old allocation. TIle new size is larger than the old size, but smaller than or equa l to the old allocation. The new size is equaJ to the old size. read more..

  • Page - 683

    19.2 C HANGI NG SIZE In other words, if we have no spare space, we double me size of lhe allocation. In practice that turns out to be a very good choice for the vast majority of uses of vector, and that's the strategy used by most implementations o f lh e standard Ii· brary vector. 19.2.5 Assignment We could have defined vector assignment in several different read more..

  • Page - 684

    654 C HAPTER 19 • VECTO R, TEMPLATE S, AND EX CEPT ION S Like this : vector& vector: :o peralor=(con st vector& a) { ) II like copy constructor, but we must deal with old elements double- p = new double[a.sz]; for (int i = 0; ka.sz; ++i) p[i] = a.eJem[i] ; delete[J elem; space = 5Z = a.5Z; clem = p ; return "'this; II allocate new space /I copy read more..

  • Page - 685

    19.2 CHANG IN G SIZ E however, show a common usc of the this poimcr checking if t.he argument a is the same object as the object for which a member function (here, operalor=O) was called. Please convince yourself tha t this code actually wo rks if we remove the Ihis==&a line. The a.sz<=space is also just an optimization. Please convince yourself t.hat this read more..

  • Page - 686

    656 (HA PTE R 1 9 • VECTO R, TEMPLATES , AND EXCEPTIONS Note how it has the: essential operations (§ l S.3): constructor, defauh conStmctor, copy operations, destructor. It has an operation for accessing data (subscripting: II) and for providing information about that data (si:teO and capacilyO), and for controlling growth (resize(), push_backO, and reserveO). 19.3 Templates read more..

  • Page - 687

    19 .3 TEMPLATE S Pele m; inl space; public: /I a pointer 10 Ihe elements /1 size+free_space vectorO : sz(O), elem(O), space(O) { } vector(int s); vecto r(co nst vecto r&): vector& o perator=(const vector&); .... vecto rO { d eletell ele m; } /I copy constructor /I copy assignment /I destructor T& o pe rato r{J(i nt n) { return el em[n]; } /I access; read more..

  • Page - 688

    658 ) ; (HAI'TER 19 • VECTO R, TEMPL ATES, AND EXCEPT IONS vector_char(const vectol_char&); II copy constructor vectof_char& operator=(co nst vector_char &); /I copy assignment II destructor cha r& operatorll (int n); II access: return reference const char& operator[J (int n ) con st; int sizeO con st; int capacityO const; void re size(int newsiz e); void pu read more..

  • Page - 689

    19.3 TEMPLATES from the template definition te mplale<c1ass T> void vecto r<T> : :push_back(const T& d ) {/- ... -/ }; TImt way, there is a function for v.push_back("No rah ") to call. 1.11 other wo rds, when you need a fun ction for a given argument type, the compiler will write it for you based on its template. Instead of writing template<class read more..

  • Page - 690

    660 CHA PTER 19 • VEC TOR, TEMPL ATES , AND EXCEPTIONS of programming is called objed-orinl1td programming (§ 14.3-4). TIle rcason that both styles o f programming are called polymmphum is that each style relies on the pro- granuner to presclll many versions of a concept by a single intClfacc. EVI)"nl)lpllism is Greek for " many sha pes:' referring to the many read more..

  • Page - 691

    19.3 TEM PLATES So - assuming you have had your fill of philosophy for now - what do peo- ple actually use templates for? For unsurpassed nexibility an d perfomlance, Usc templates where performance is essential (e.g. , numerics and hard real time ; see Chapters 24 and 25). Usc templates where nc.x.ibility in combining information from several types is essential (e.g. , read more..

  • Page - 692

    662 CHAPTER 19 • VECTOR, TEMPLATES, AND EXCEPT IONS \IS = ve ; /I error: vector<Shape> required void f(vector<Shape>&); fIve) ; /I error: veclor<Shape> required But why not? After all, YOli say, I can convert a Ci rcle to a Shape ! Actually, no , yo u can'l. You can convert a Circle- to a Shape* and a Circle& to a Shape&, but we deliberately read more..

  • Page - 693

    19 .3 TEMPLATE S Consider an example of the most common use o f an integer value as a tem- plate argument, a container where the number of elements is known at compile time: templale<class T , inl N> s lrucl array { T e lem(NJi /I hold elements in member array 1/ rely on the default constructors, destructor, and assignment T& o peralor(J (int n); /I access: read more..

  • Page - 694

    664 CHAPTE R 19 • VE CTO R, TEMPLATES , AND EXCE PT IONS More importantl y, some programs simply can't he allowed to use free stOre. Such programs are typically embedded systems programs and/or safcty-criticru pro- grams (sec C hapter 25). In such programs, array gives us many of the adva ntages o f vecto r without violating a critical res triction (no free-s tore read more..

  • Page - 695

    19 .3 TEMP LA TES void to { till (buf, 'x'); fill (b2,0.0); } /I for nllo, T is char and N is 102 4 /I because Ihafs wha t buf has /I for fi ll(), T is double and N is 10 /I because that's what b2 has Technically, fill{buf, 'x') is shorthand for filkchar, 1024>(buf, 'x ') , and fill (b2,0) is shorthand for filkdouble ,10>(b2,O), but fonunately we read more..

  • Page - 696

    ... C HAPTER 19 • V ECTOR , TEMPLATE S, AND EXCEPTIONS struct No_default ( No_defau lt(int); /I the only constructor for No_default /I . .. }; veclor<No_defaull> v2(10); vectof<No_defaull> v3; v3. resize(1(M), No_default(2»; v3 .resize(200); lIerror: tries to make 10 No_default(~ /1 add 100 copies of No_defa ult(2) /I error: tries to make 100 No_def;lUItOS ~nle dcstnlctor read more..

  • Page - 697

    19 .3 TEMPLATE S Unsurprisingly, an all ocator is exactly what we need ror implememing vec- tor<T>: : reserveO. We start by giving vector an allocator parameter: template<class T, class A = aliocator<T> > class vector ( ); A alloc; II use allocate to handle memory for elements II ... Except rOJ" providing an allocmor - ,md using the standard one by ddault read more..

  • Page - 698

    ... CHAPTER 19 • VECTO R, TEMPLATES, AND EXCE PTIONS Similarly, veclor<T,A>: : resize() is nOt too difficult: template<class T, class A> void vector<T,A> : :resize(int newsize, T val = TO) ( reserve(newsize); for (int i=sz; knewsize; ++i) alloc.construcI (&elem[il,val) ; 1/ construc i for (int i = newsize; k s z; ++i) alloc.deslroy(&elem[i)) ; II destroy 5Z read more..

  • Page - 699

    19.4 RANGE CH ECK I NG AND EX CEPTIO NS slruct oUI_oCra nge { r ... " ' }; /I class used 10 reporl range access errors le mplate<class T, class A = aliocalo r<T> > class vec tor ( /I . .. } ; T& al (inl n); const T& at(i nl n) const; T& o pe ralorl1( inl n); consl T& o pe ralo r( Hinl n) consl; /I. /I checked access /I checked read more..

  • Page - 700

    67. ( HAPTER 19 • VEC TOR, TEMPLATES, AND EXCEPTIONS 19.4.1 An aside: design conside rations So far, so good , but why d idn't we just add the range check to operato rllO? Well, the standard library vector provides checked all) and unchecked operatorllO as shown here. Let's try to explain how that makes some sense. There arc basically fOllr arguments: I . read more..

  • Page - 701

    19.4 RANG E CH EC KING AND EXCEPTION S 19.4.1.4 Optional checking 111e ISO C++ standard simply states that oUl-of-range vector access is not guar- anteed to have any specific semantics , and that such access should be avoided. It is perfectly standards-conforming to throw an exception when a program tries an out-of-range access. So, if you like vector to throw and don't read more..

  • Page - 702

    672 CHAPTER 19 • VE C TOR , TEM P LATE S, AND EXC EPTI O N S We use Range_error to make the olTending index available for debugging. The typedef introduces a convenient synonym ; see §20.5. 11lis Vector is very simple, arguably too simple, bm it has been useful in debug- ging nonuivial programs. ~nlC a1tcmalive is to use a systematically checked imple- mentation read more..

  • Page - 703

    ! 9.5 RE SO U RC ES AND EXCEPT!O NS Basically, we define a resource as something that is acquired and must be given back (released) or reclaimed by some "resource man ager." TIle simplest example is free-store memory that we acquire using new and return to the free store using de lete . For example : void suspicious(int S, int xl { int- p = new jnl [S]i read more..

  • Page - 704

    674 CHAPTER 19 • VECTOR , TEMPLATE S, AND EX CEPTION S void s us piciou s(int 5, int xl { int - p = new int[s); II acquire memory 1/ . . . if (x) return ; 1/ . . . d eletelJ Pi /I release memory Maybe we never get to lhe delete because we threw an exception: void suspiciousOnt 5, inl x) { ) inl· p = new intis}; /I acquire memory veCl o r< read more..

  • Page - 705

    19 .5 RESO URCES AND EXCEPTIONS ' nlis solves the problem at the cost of some added code and a duplication of the resource release code (here, d ele teU p;). In other words, this solution is ugly; worse, it doesn't generalize well. Consider acquiring more resources: void sus picious(vecto r<inb& v, int s) { ) int - p = new intIs1 ; vecto r<inbv1; 1/ . .. read more..

  • Page - 706

    676 CHAPTE R 19 • VECTOR , TEMPLATES , AND EX CE PTI ONS \OVc actually solved tills particular "exception problem" when we solved the mem- ory leak problems for vectors. The sol ution is general ; it applies to aU kinds o f re- sources: acquire a resource in the constructor for som e object that manages it, and release it again in the m atchin g d read more..

  • Page - 707

    19 .5 RESOUR CES AND EX CEPTI ONS ) catch ( ... ) { delete p; throw; ) /I do our local cleanup /I re-throw to allow our caller to deal with the (act /I thaI some_function O couldn't do what was /I required of it 111is ma ke_vecO functi on illustrates a very common sty le of error handling: it tries to do its job and if it can't, it cleans up any read more..

  • Page - 708

    678 CHAPTER 19 • VECTOR , TEMPLATES , AND EXCEPTIONS 19.5.4 auto_plr So, make_vecO is a useful kind of function that obeys the basic !Ulcs for good re- source management in the presence of exceptions. It provides the basic guarantee - as all good funCli ons should when we want to recover from exception throws. Unless something nasty is done with nonlocal data in the read more..

  • Page - 709

    19 .5 R ESO U RCES AND EXCEPT IONS template<class T , class A> void vector<T,A>: : reserve(int newalloc) { if (newalloc<=space) return ; p p = alloc.allocate(newalloc); /I never decrease allocation /I allocate new space for (int i=O; ksz; ++i) alloc.construcU&p[i],elemliJ); II copy for (int i=O ; ksz; ++i) alloc.destroy(&elemfiJ); /I dewoy alloc.deallocate(elem,s pace); read more..

  • Page - 710

    680 CHAPTER 19 • VECTOR , TEMPLATES, AND EXCEPTIONS Note that vector_base deals with memory rather than (typed) objects. Our vector implementation can usc that LO hold objects of the desired clement type. Basically, vector is simply a convenient interface to vector_base : templale<class T , class A = allocator<T> > class vector : private vecto,_basc<T,A> { public: 1/ read more..

  • Page - 711

    C HAPTER 19 REVIEW ~ Drill I. Defme template<class T > s hud S { T val; }; . 2. Add a constmcLOr, so that you can initialize with a T. 3. Deftne variables of types S<int>, S<char>, S<double>, S<string>, and S< vedor<int> >; initializ e them with values of your choice. 4. Read those values and print them. 5. Add a function tem plate getO that read more..

  • Page - 712

    682 C H APTE R 19 • VEC TOR , TEMPLATES , AND EXCEPTIONS 14. How does array differ from vecto r? 15. How does a rray differ from the built·in array? 16. How docs resizeO differ from reserve()? 17. \"'hat is a resource? Define and give examples. 18. What is a resource leak? 19. What is RAIl? What problem does it address? 20. What is auto_plr good for? read more..

  • Page - 713

    CHAPTER 19 EXERCI SES 8. Implement an allocator (§19.3.6) using the basic alloc.-ttion functions maliocO and freeO (§B.1O.4). Get vecto r as defined by the end of §I9.4 to work for a few simple test cases. 9. Re-implement veclo r:: ope rator= () (§I 9.2.5) using an allocator (§ I9.3.6) for lllelllOlY management. 10. Implement a simple auto_ph supporting only a read more..

  • Page - 714

    584 CHAPTER 19 • VECTOR, TEMPLATE S, AND EX C EPTI ONS Postscript Templates and exceptions arc immensely powerful language features. They sup- port programming techniques of great flexibility - mostly by allowing people to separate conccOlS, that is, to deal with olle problem at a time. For example, using templatcs, we can defme a container, such as vector, separately from read more..

  • Page - 715

    \:1. . ,.. 20 Containers and Iterators "Write programs tha t do one thing and do it welL Write programs to work together." -Doug M cilroy T his chapter and the next present the S1L, the containers and algorithms part of the C++ standard library. 111C STL is an extensible framework for dealing with data in a C++ pro- gram. Mter a rlfSl simple exam ple, we read more..

  • Page - 716

    686 C H A PTE R 20 • CON TA I N ER S AND I TERATO RS 20.1 Storing a nd p rocessing data 20.1.1 Wo rk ing wi th data 20.1.2 Gene ralizing code 20.2 STl ideals 20.3 Sequ e n ces and ile rato rs 20.3.1 Back to th e example 20.4 linked lists 20.4 .1 list ope ratio ns 20.4.2 Ite ratio n 20.5 Ge ne ralizing vector ye t agai n 20.6 An e xa read more..

  • Page - 717

    2 0 . 1 STORING AND PRO C ESS IN G DATA The assumption is that the data is stOred on the free sLOre and that we should delete it when we are fini shed using it. Another assum ption is that we can' t rewrite J ack's and Jill's code, or wouldn't want to. 20.1.1 Working with data C learly, this is a somewhat simplified example, but it is not dissimilar to read more..

  • Page - 718

    ... CHAPTE R 20 • CONTA INE RS AND ITE RATO RS because [ J binds tighter than .. so we need the parentheses around · jill_data and gel (·ji ll_dala )[iJ. TRY THI S If you were able to change Jill's code, how would you redesign its interface to get rid of the ugliness? 20.1.2 Generalizing code VVhat we would like is a unifonn way o f accessing and read more..

  • Page - 719

    20.1 STO RING AND PROCE SS IN G DATA 111is looks better. We don't introduce so many variables and we write the loop and the loop body only once (in highO). If we want to know the highest values, we can look at · jack_high and -jill_high. For example : cout « "Jill 's max: " « -jill_high « "; Jac k's max : " « *jack_high; Note that highO read more..

  • Page - 720

    690 CHAPTER 20 • C ONTA IN ERS AND ITERATOR S Here highl will point to the clement with the largest value in the first half of the vector and high2 will point to the clement with the largcst value in the second haJf. Graphically, it will look something like this: &v(OJ Middle &v[OI + v.sizeO ,-'-1-- \ - --,-I'----\----.I.l:J hi g hl hi g h2 We used palmer read more..

  • Page - 721

    2 0 . 2 STL IDEALS There are two major aspects o f computing: the computation a nd the data. Someti mes we focus o n the computation and talk about if·s tate ments, loops, functio ns, error handling, etc. At other times, we focus on the data a nd talk about arrays, vectors, stri ngs, flIes, etc. However, to get useful work done we need both. A large amo read more..

  • Page - 722

    6'2 (HAPTER 20 • CON TAINER S AND ITERATORS NOle U1a( we can d escribe each of these casks without actually mentioning how the data is stored. Clearly, we must. be dealing with something like lists, vectors, files, input streams, etc. for lilesc tasks to make sense, but we do n't have to kno w the details about how the data is stored (or gathered) to talk about read more..

  • Page - 723

    20.2 STl IDEAL S We'd like to do these t.hings without getting sucked into a swamp of details abollt diffe rences among containers, differences in ways o f accessing clements, and dif- ferences among clement types. If we can do that, we'll have come a long way to- wa rd our goal of simple and efficient usc of large amounts of data_ Looking back at the programming read more..

  • Page - 724

    ... Fast Retrieval o f dam Addition of data Deletion of data C HAPTER 20 • CONTAINERS AND lTERATORS Standard versions of the most common algorithms Such as copy, find , search, sort, sum, . . . TIle STL provides that, and morc. We will look at it not just as a very useful sct of facilities , bLll also as a n example of a library designed for ma:'(imai read more..

  • Page - 725

    20,3 SEQ U EN CES AND ITER ATO RS beyond the end of the sequence. The usual mathematical notation for such se- quences (ranges) is [begin:end)_ The arrows from one element to the next indi- cate that if we have an iterator to one element we can gel an iterator to the next. \¥hat i s an itermor? An iteralor is a rather abstract notion: An iteralor points to read more..

  • Page - 726

    ... CHAP TE R 20 • CONTA INERS AN D ITER ATORS iteralors are used to connect OUf code (algorithms) to our data. The writer of the code kll OWS about the iterators (and not about the details of how the itcrators actually get to the data), and the data provider supplies itcrators rather than ex- posing details about how the data is stored to all users. The read more..

  • Page - 727

    2 0 .3 SEQUENCES AND ITERATORS Note that we eliminated the local variable h that we had used to hold the highcst value seen so far. \¥hcn we don 't know thc namc of the actual type of the ele- mClus of the scqucnce, the initialization by - 1 secms completely arbitrary ,md odd. llmt's because it was arbitrmy and odd! It was also an error waiting to hap- pen: read more..

  • Page - 728

    ... ( H APTER 20 • CONTA I NERS AND ITERATORS TRY THI S We again left a serious error in !.hat program. Find it, fLX it, and suggest a general remedy for that kind of problem. 20.4 Linked lists Consider again the graphical representation of the notion of a sequence : Compare it to the way we vis ualize a vecto r in memory : begin O,' }L--' 0: 1: read more..

  • Page - 729

    2004 UNKED LISTS 'n,is can be represented in code as template<class E lem> s tru ct Link ( link · prev; II previous link link · S U CC i /I successor (next) link Elem valj /I the value ); tcmplatc<class E lem> s t,u Cl list ( link<Elem>* first j link<Ele m>* lastj /I one beyond the last link ) ; l11e layout of a link is pOft suee Oem read more..

  • Page - 730

    ' 00 C HAPTE R 20 • CONTAINERS ANO ITERATORS template<class Elem> class list ( /I representation and implementation details public: ) ; class iterator; /I member type: iterator iterator beginO ; /I iterator to first element iterator end( ); /I iterator to one beyond last element iterator insert(iterator p, consl Elem& v); iterator erase(iterator pI; /I insert v into read more..

  • Page - 731

    20.4 LI N KED LI STS 20.4.2 Ite ration rille list itcrator must providc . , ++, ==, and ! =. Since thc standard library list is a do ubl y-linked list, it also provides -- for iterating "backward" toward the front of the list: le mpla le<class B ern> class l isI<Ele m>: : ite ra to r { Lin k<Ele m>· curr ; /I current link publ ic: ); ite read more..

  • Page - 732

    '02 ) CHAPTE R 20 • CONTA I NERS AND ITERATORS int x; while (ci n » x) Isl.push_front(x ); lisl<inl> : :iterator p = high(lst ,begin(), Ist.end(); cout« "the highest value was" « . p « endl ; H ere, the "value" of the Ite rator argu ment is list<int> : :ite rator, and the imple- mentation of ++, . , and ! = has changed read more..

  • Page - 733

    20 .5 GEN ER ALIZ I NG VECTOR YET AGAIN We usc this kind of test systematically with STL algorithms. Because the standard library provides a list, we won't go funh er into the im- plementatio n here. Instead , we'll have a brief look at what lists arc good for (see exercises 12-14 if you arc interested in Jist implementation details). 20.5 Generalizing vector yet read more..

  • Page - 734

    704 C HAPTE R 20 • CONTA INERS AND tTERATORS The point is tha t to write that, we don't actually have LO know what types a rc na med by iterator an d size_lype. In particular, the code above, because it is ex- pressed illlcnns of ilerator and size_type, will work with vectors where size_type is not an uns igned long (as it is not on many embedded systems read more..

  • Page - 735

    20.6 AN EX AMP LE : A S IMPLE TEXT EDI TOR \.yhich operations? Let's assume that a document will fit in your computer's main memory. TImt way, we can choose any representation that suits us and simply convert it to a stream or bytes when we want to store it in a file. Similarly, we can read a stream or bytes rrom a me and convert those to our in-memory read more..

  • Page - 736

    706 C HAPTER 20 • CONTAINER S AND JTERATOR S characters. For example, we could insert "This is a new line." after "docume nt. " to get This is the start of a ve ry long docume nt. This is a new line . The re a re lots of . .. All we needed to do was to insert a new "line" in the midd le: Lind This is the start of iI we long read more..

  • Page - 737

    20.6 AN EXAMPLE : A SIMPLE TEXT EDITO R logical concept that you can represent in your program as a (linked) list or as a vedor. The closest STL analog to our everyday concept or a list (e.g. , a to·do list, a list or groceries, or a schedule) is a sequence, .md most sequences are best rep· resented as vectors. 20.6.1 lines How do we decide what's a read more..

  • Page - 738

    708 CH APTER 20 • CONTA INER S AND ITE RATO RS Both vector and list have a member functi on backO tha t returns a refe rence to the las t clement. To usc it, yOli have to be sure that there really is a last clement for bac kO LO reFe r to - do n't lI SC it o n an empty comaincr. ll1at's why we defined an empty Docume nt to have one e mpty read more..

  • Page - 739

    20.6 AN EXAMPLE: A SIMPLE TEX T EDITOR To make TexUte rato r useful, we need to equip class Docume nt with conven· tional begi nO a nd e nd() functions: struct Docume nt { lisf<li ne> lin e ; TexUte rato r begin O /I first character of firS I line { re turn TexUterato r(line. beginO, (· Iine .begin ()) .begin ()) ; } TexUte rato r e ndO /I one read more..

  • Page - 740

    ·10 C HAPTER 20 • CONTA INER S AND IT ERATORS Note that advanceO can be used to simulate subscripting. In fact, for a vector called v, ·advance(v.beginO,n) i s roughly equivalclll to vln1. Note that "roughly" means that advance() laboriously moves past ule first n- 1 clements one by one, whe reas the subscript goes straight to the m h elemcm. For a list, read more..

  • Page - 741

    20 . 7 VECTO R, LI ST. AND STR ING TexUterator find _txt(TexU terator first, TexUte ralo r last, canst string& s) ( if (s, sizeO==O) return last; /I can't find an empty siring char first_char = slDl; while (t rue) ( ) TexU te ralor p = find (fir st,last,firsCchar); if (p==last II match (p,last,s)) return p; Returning the end o f the sequence to indic.ate read more..

  • Page - 742

    712 CHAPTER 20 • CON TAINERS AND lTERATO R$ We can ask a slightly morc general variant of this question. We have now seen four ways to store a sequence o f characters : chari! (array of characters) vec to r<char> string list<char> How d o we choose am ong them for a given problem? For really simple tasks, they arc imcrchan gcablc ; that is, they read more..

  • Page - 743

    20.7 VEC TOR, LIST, AND STRING AIl we have seen (§17.2, § 18.5), arrays are useful and necessary for dealing with memory at the lowest possible level and for interfacing with code written in C (§27. 1.2 , §27.5). Apart from that, vector is preferred because it is easier to usc, more flexib le, and safer. TR Y THI S What does that list of differences mean in read more..

  • Page - 744

    71. CHAPTER 20 • CON TAINERS AN O ITERATORS vector<int>: : ite rator p = v.begin() ; ++p ; ++p ; ++p; II take a vector /I poinl lo its 3rd element vector<int> : :ite rator q = Pi ++q ; /I poinllo its 4th e lement v ~ P-cp ~ 1 0 11 1 2 1 3 1 -15i''''''':'''''''''''''''''''''''''''''', p = v.inserl(p,99); /I p points at the inserted element P' read more..

  • Page - 745

    20 .8 ADAPTING OUR VE C TOR TO THE STl p = v.inserl(p,99); /I P poinls at th e inserted elemenl v ~[~}-{!J Note that q still poi.nts to the clement with the value 4 . p = v.erase(p); "I' point s at the elemenl after the erascd onc Again we find ourselves back where we started. However, for list as opposed to fo r vector, we didn't move any elemcnts and read more..

  • Page - 746

    716 CHA PTER 20 • CONTAINER S AND ITERATOR S int space; A alloe; pUblic: /I number of elements plus number of free space "sIOls" /I use al locate to handle memory for elements ); 1/ . .. all the other stuff from Chapter 19 and §20.5 .. . I ypedcf r- iteratof; /I Elem o is the simplest I>ossibie iterator iterato r insert(iterato r P, const T& read more..

  • Page - 747

    2 0.8 ADAPT I NG OU R V EC TOR TO THE STL 111e code for eraseO is quite simple, but it may be a good idea to tryout a couple of examples by drawing them on paper. Is the empty vector cOlTectly handled? Why do we need the p==endO test? What if we erased the last clemem of a vector? Would this code have been easier to read if we had used the subscript read more..

  • Page - 748

    718 C H APTER 20 • CONTAINERS AND ITERATORS inserl() and e raseO operations are available for all vectors, and their pcrfonmmcc is unbea table when you are j ust moving a few words of data - or even a few dozen words - because modem computers are really good at this kind of copying; sec ex- ercise 20. Avoid Oinked) lists fOT representing a list of a few read more..

  • Page - 749

    20 . 10 CONTA I NER OVERVIEW 111is definition isn't complete or completely standards·conforming, but it will give yOll the idea, It will also give yo u something to use if your implementation doesn't yet provide the standard a rray. If available, it is in <array>, Note that be· cause a rray<T, N> "knows" lhat its size is N, we can (and do) read more..

  • Page - 750

    no CHAPTER 20 • CONTA I NERS AND ITERATORS Standard containers (continued) uno rde red_multi ma p ,,' multiset unord ered_set unord ered _mulliset array a hash table where there can be multiple copies of a key; an optimized version of multimap; use it for large maps when you need high performance and can devise a good hash function (see §21.6.4) a balanced ordered read more..

  • Page - 751

    20.10 C ONTAINER OVERVIEW Do you feel cheated? Do you think we should explain all about containers and their use to you? That's just not possible. There are too many standard facil - ities, too many useful techniques, and too many useful libraries for you to absorb them all at once. Programming is too rich a field for anyone to know all facilities and techniques - read more..

  • Page - 752

    722 "AlmoSI con taine rs" T(n] built-in array string valarray (HAPTER 20 • CONTAINERS AND ITERATORS no sizeO or other member functions; prefer a container, such as vector, string, or aHay, over a built-in a rray whcn you have a choice holds only characte rs but provides opera tions useful for text manipulation, such as concatenation (+ and +=); prefer Ihe standa read more..

  • Page - 753

    CHAPTER 20 DR ILL Iterato r ca tegories (continued ) random ·access iterato r We can iterate forward (using ++) and backward (using - - ) and read and write (unless the elements are consl ) element values using · or ( J. We can subscript and add an integer to a random-access iterator using + and subtract an integer using - . We can find the distance between read more..

  • Page - 754

    CHAPTER 20 • CONTAINERS AND ITERATORS 6. Write a simple copyO operation, template<class Ite rl , class lter2> (opy(lter fl , Iterl el , Itcr2 12); that copies [fl ,el ) to [f2,f2+(el- fl » just like the standard library copy function. Note that if fl==el the sequence is empty, so that there is noth- ing to copy. 7. Use your copyO to copy the array into the read more..

  • Page - 755

    Ct-IAI'TER 20 EXERC I SES Term s algorithm array container beginO container contiguous dou bly-linked list element Exercises empty sequence e nd () e rase() inserl() iteration iterator linked list sequence si ngly~link ed list size_type STL typedef valu e_type 1. If you haven't already, do all Try this exercises in the chapter. 2. Get the J ack-and:Jill example from §20. read more..

  • Page - 756

    Tl6 CHAPTER 20 • CONTAINERS AND rTERATOR S IS. Define a pvector to be like a vector of pointers except that it contains pointers to objects and its desuuctor deletes each object. 16. Define an ovector that is like pvector except that the ( I and • operators rerum a reference lO the object poimed to by an element rather than the pointer. 17. Define an read more..

  • Page - 757

    Algorithms and Maps "In theory, practice is simple." -Trygve Reenskaug T his chapler completes our presentation of the funclamclllal ideas o f the STL and O Uf survey of the facilities it offers. Here, we focus on algorithms. Our primary aim is to imrocluce you to about a dozen of the most useful o nes, which will save you days, if not months, of work. Each is read more..

  • Page - 758

    '28 21.1 Standa rd libraryalgo rilhrns 21.2 The simplest algorithm : find O 21.2.1 Some ge ne ri c uses 21.3 The ge ne ral search : findjfO 21.4 Fu nction o bjects 21.4.1 An abstract view of functio n objects 21.4.2 Prediciltes o n class membe rs 21.5 Nume ri cal algo rithms 21.5.1 Accumulate 21.5.2 Ge n(" ralizi ng accumulaleO 21.5.3 Inn e r product 21.5.4 read more..

  • Page - 759

    2 1. 2 THE SIMPLEST ALGORITHM: FIND O Selected standard algorithms (continued ) eq ual(b,e,b2) x=accumulate(b,e,i) x=accumulate(b, e, i,op) Do all elements of Ib:ej and Ib2 :b2+(e-b)) compare equal ? II: is the sum of i and the elements of Ib : e). like the other acc umulate, but with the "sum" calculated usi ng op. x:inner_product(b,e,b2,i) x is the inner product of read more..

  • Page - 760

    7JO (HAPTER 21 • ALGORITHMS AND MAPS by find O is an ilcratof. That result points either to the HrSl clcmcm of the sequence with the value val o r to last. Returning an iterator to the one-bcyond-the-Ias t cle- melll of a sequence is the most common S11. way of reporting +; nOl found." $0 we can usc find O like Lhis: void f(vector<inl>& v, inl x l { read more..

  • Page - 761

    21 .2 TH E S IMPLE ST ALGORITHM : FIND O ) for (In p = first; p!=last; ++p) if (* p == val) return p; return last; These two defi nitions arc logically equivalent, and a really good compiler will generate the same code for both. However, in reality many compilers arc not good enough to eliminate that extra variable (p) and to rearrange the code so that all read more..

  • Page - 762

    732 ( HAPTER 2 1 • ALGORITHM S AND MAPS a pointer. The itcrator comparison (in fir sl!=lasl) is a pointer comparison, and the value comparison (in °fir sl!=val) simply compares two integers. Let's try wilh a list void f(I ist<slring>& v, string )It) ( /I works for lis! of str ing list<string:>:: iter atol p = find (v.begin(),v.end O,x); if (p !=v. end()) read more..

  • Page - 763

    21 .3 THE GENE RAL SEARC H : F1ND _ IF O "nlc sta ndard algorithm that scarches bascd on a user-supplied critcrio n is find_if 0 : template<class In , class Pred> In find j f(ln first, In lasl , Pred pred) { while (firsl!=lasl && !pred(·first» ++first; return fir st; Obviously (when you compare the sourcc code), it is just like find O except read more..

  • Page - 764

    CHAPTER 2 1 • ALGOR ITHMS AND MAP S 111is last example is nOl very satisfying, though. \-Vhal if we next wanted to find an element larger than 41? We would have to write a new function. Find an ele- ment larger than 19? Write yet another fun ction. 111ere has to be a better way! If we want to compare to an arbitrary value v, we need somehow to make v read more..

  • Page - 765

    21.4 FUN CTION OBJECT S void f(list<double>& v, int x) { list<double>: :iterator p = find_if(v.begin O, v.endO, larger_than(31»; if (p!=v.e nd(» ( r we found a value > 31 */ ) lisl<do uble>: :iterator q = find_if(v.begin O, v.end O, Larger_than(x»; if (q !=v.e nd (» {/* we found a value> x */} II .. . Obvio usly, larger_than must be somethiJlg that We can read more..

  • Page - 766

    736 ( HAI)TER 21 • ALGORITHMS AND MAP S call &jJeralar and the ajJjJlico.twn C!jJeratrtr. So ( ) in pred(*first) is given a meaning by Larger_than: :operatorO , just as subscripting in vIi] is given a meaning by vector: :operator[ 1. 21 .4.1 An abstract view of function objects We have here a mechanism that allows for a "function n to "carry around" read more..

  • Page - 767

    2 1.4 FUNCTI O N OB JECT S ance. The reason is simple, but surp rising to people more fami liar with passing fun ctions as arguments: typically, passing a function object leads to signifi cantly smaller and faster code than passing a function! ll1is is true only if the object is small (something like zero, one, or two words of data) or passed by reference and if read more..

  • Page - 768

    738 CHAPTER 2 1 • ALGORITHMS AND MAPS comparing their addr members. To allow the user to specify such compariso n 0;- leria, ehe standard library sort algorithm takes an optional third argume nt specify. ing the sorting crilcl;a. Cmp_by_nameO creates a Cmp_by_name for sortO to usc to compare Records. TIlat looks OK - meaning lhat we wouldn't mind maintain- ing code that read more..

  • Page - 769

    2 1. 5 NU MERI CA L ALGO RITHM S Numerical algo rithms x:accumulale(b,e,i) x=i n ner _producl(b,e, b2, i) r=partial_su m(b, e, r) r=adjace nCdiffere nce(b,e,b2,r) Add a sequence of values; e.g., for (a,b,c,d) produce a+b+c+d. The type of the result x is the type of the initial value i. Multiply pairs of values from two sequences and sum the results; e.g., for (a, read more..

  • Page - 770

    740 C H APTER 2 1 • A LG ORITH MS AND MAP S void f(vector<double>& vd , in' · p, int nJ ( double sum = accumulale(vd.begin(), vd.e ndO, 0.0); int 5um2 = acc umulate(p, p+n,O) ; The type of the result (the sum) is the type of the variable that acc umulaleO lIses to hold the accumulator. TIlls gives a degree of OexibililY that can be important. Fo read more..

  • Page - 771

    2 1.S NUMERICAL ALGORITHMS quence, so the STL offers a second four-argument version o f acc umulateO where we ca.Il specify the operation to be used: template<class In, class T , class Bin O p> T acc umulate (ln first, In las t, T init, BinO p o p) { } while (firsl!=last) ( } init = o p(init , · first); ++firsl; return init ; Any binary operation that read more..

  • Page - 772

    742 C H APTER 21 • ALGORITHMS AND MAl'S void f(const vector<Record>& vr) { ) double total = accumulale(vr.beginO, vr.end O, 0.0, price); " .. We were "lazy" and used a function, rather than a function object, to calculate the price - just to show that we could do th at also. We tend to prefer function o bjects If they need to SLOr e a value read more..

  • Page - 773

    2 1.5 NUMERICAL ALGOR ITH MS to take a set of companies and assign each a "weighl." For example, in the Dow J o nes Industrial index Alcoa had a weight of 2.4808 when last we looked. To get the current value o f the index, we multiply each company's share price: with its weight and add all the res ulting weighted prices togeth er. O bviously, that's read more..

  • Page - 774

    744 C H APTE R 21 • ALGOR ITHMS AND MAPS template<class In , class In2, class T, class BinOp, class BinOp2 > T inner_product(1n first, In las t, 1"2 fif Sl2, T init, BinOp op, BinOp2 o p2) { while(firsl!=last) ( inil = op(init, op2(- first, -first2»; ++first; ++first2; re turn init; ) til §21.6.3, we rerum to the Dow Jones example and usc this read more..

  • Page - 775

    2 1.6 A SS O CI ATIVE CONTAINER S 21.6.1 Maps Consider a conceptually simple task: make a list of the number of occurrences of words in a t'ext. TIle obvious way of doing this is to keep a list of words we have seen together with the number of times we have seen each . When we read a new word, we see if we have already seen it; if we have, we read more..

  • Page - 776

    746 CHA PTER 21 • ALCORITHMS AND MAPS This reads every (whitespace-separatcd) word on input and computes the num- ber of occurrences for each. Now all we have to do is to produce the output. We can iterate though a map, just like any oilier STL container. The clements of a map<Slring, int> are of type pai r<string, in t>. The flrst member of a pair is read more..

  • Page - 777

    2 1.6 ASSO C IATIVE CONTAINERS language : 1 language.: 1 make: 1 minor: 1 mo re: 1 new : 1 of: 1 programmer.: 1 programming: 3 provided : 1 provides: 1 purpose: 1 serious: 1 superset : 1 th e: 3 to : 2 types.: 1 If we don 't like to distingu ish between upper- and lowercase letters or would like to eliminate punctuation, we can do so: see exercise 13 read more..

  • Page - 778

    748 C H APTE R 2 1 • AL G ORI THM S AND MAPS Frui ts: Orangt: 99 Grnp< 2345 Appl< 7 KiM 100 Plum 8 : One ~~-b"s;-: !... ______________ J Given that the name of the Node member that holds the key vaJue is first, the basic rule of a binary search tree is lefl->fir stdirst && firsl<right- >first TImt is, for every node, Its left read more..

  • Page - 779

    21.6 ASSOCIATIVE CONTAINERS lois tree still meets the criteria that the key of every node is greater than that of its left sub-node and less than that of its right su b-node: left->firsldirsl && firsl<right->first However, this version of the tree is unbalanced, so we now have three "hops" to reach Apple and Kiwi, rather than the two we had in the read more..

  • Page - 780

    751l ); ( HAPTER 21 • ALGORITHMS AND MAPS T1 fi rs t; T2 second; pa irO :first(Tl{)), second(T2()) ( ) pa ir(consl T1 & x, co nsl T2& y) :first(x), se co nd (y) () le mplate<class U, class v > pair(co nst pa ir< U,V>& p) :firsl(p.firsl), second(p.second ) ( ) te mplate<class T1 , class 12> pa ir<T1 ,T2> m a ke_pair(Tl x, T2 y) ( read more..

  • Page - 781

    21 ,6 ASSOC IATIVE CONTAINERS a company !laille used where a terse representation is needed. Similarly we can keep the company's ticker symbol together with its share price, e.g. , ("AA",34.69). Finally, r or those or us who don' t regularly deal with lhe U.S. stock market, we can kee p the company's ticker symbo l together with the company name, e.g., read more..

  • Page - 782

    752 C HAPTER 2 1 • ALGOR ITH M S AND MAP S Iterating through a map is easy. We just have LO remember lha! lhe key is caJled first aud the value is called second : typedef map<String,double>: :consUteralor Dowj te ratof j /I write price (or each company in the Dow index : for (Dow_iterator p = dow_price.begin Oj p!=dow_price.end Oj ++p) { const string& sy read more..

  • Page - 783

    { 2 1.6 ASSOCIATIvE CO NTA I NERS mon reason to use a map is simply that we want to look up values based on the key. For large sequences, finding something using find O is far slower than look- ing it up in a sorted structure, such as a map. TRY TH IS Get this liule example to work. Then add a few companies of your own choice, with weights of your read more..

  • Page - 784

    754 ( HAPTER 2 1 • ALGORITHMS AND MAPS We can illustrate lookup in an (unsoncd) vector, a balanced binary tree, and a hash wblc graphically like this: Lookup in unsoncd vector : ···+++++1 Lookup in map (balanced binary (fcc): Lookup in unordered_map (hash table): '. ' . TIle STL unordered _map is implemented using a hash table, just as the 511... map is implcmcmcd read more..

  • Page - 785

    21.6 ASSOCIATIVE CON TAINERS unordered_map<string,double> dow_ price; typedef uno rdered_map<slring,double>: :con sU lerator Dow_iterator; for (Dow_ilerator p = dow_price.beginO ; p!=dow_price.e nd O; ++p) { const string& sy mbol = p->first; /I the "ticker" symbol cout« symbol « '\t' «p->second « '\1' «dow_namelsymboll « '\n ' ; ) Lookup in dow might now be read more..

  • Page - 786

    756 C HAPTER 21 • ALGORIT H MS AND MAP S Fmits: Orange Crape Qymce :-~; b-e~~d-I~~ ': !.. • • _ • • • _- • • _ • • _ • • • ' What are sets useful for? As it happens, there arc lots o f problems that require us to remember if we have seen a value. Keeping track of which fruits are available (independently of price) is one read more..

  • Page - 787

    2 1. 7 COPYING One advantage of set over map is that you can use the vallie obtained from an ilerator directly. Since there is no (key,value) pair as for map (§21.6.3), the de reference operator gives a value of the eleillent type: Iypedef set<fruit>: :consUterator 51; fo r (51 p = inventory.beginO, p!=inventory.end O; ++p) cout« *p « '\n'; Assuming, of course, read more..

  • Page - 788

    758 (HAPTER 21 • ALGORITHMS AND MAP S void f(vecto r<do uble>& vd, lis t<int>& Ii ) { II copy the elements of a list of ints into a vector of doubles if (vd .si zeO < li .sizeO) error(" l arget container too sm all "); copy(li .beginO, li.end(), vd . begin(); II . .. Note that the type of the input sequence of copyO can be read more..

  • Page - 789

    2 1. 7 CO PYING islream_ileralor<slring> ii(dn) : /I reading ·ii is to read a string from cin // meaning cin» s l siring s1 = · ii; Hii ; string s2 = · ii; /I Nget ready for the next input operat ion N /I meani ng cin» s2 Using oSlrearn_iterator and istrearn_iterator, we can use copyO for our 110. For example, we can make a "quick and dirty " read more..

  • Page - 790

    7'" CHAPTER 21 • ALGORITHM S AND MAPS TRY THI S First get the program as written to work and test it with a small flle of, say, a few hundred words. Then try the emphaticaUynot rt!COTIIJ1Ie7Ilkd version that guesses about the size of input and see what happens when the input buffer b overflows. Note that the worst-case scenario is that the overflow led to read more..

  • Page - 791

    2 1 . 7 C OPY IN G Obviously, a newline is a popular choice ror Output meant ror hu mans to read, but maybe we prefer spaces as separators? We could write ostreamjterato r<string> oo(os," "); /I make output iterator for stream This wo uld give us the output bil dog man the 21.7.3 Using a sel lo keep order There is an even easier way or getting read more..

  • Page - 792

    762 ( ) CHAPTER 2 1 • ALGOR ITHMS AND MAPS while (first ! =Iast) ( jf (p (·first)) ·res++ = - firsl ; ++firstj ) return res; Using our larger_than fun ction object from §21.4, we t.'ln find all clements of a sequence larger than 6 like this: void Hconsl vector<inl>& v) ( ) /I copy al l elements wi th a value larger than 6 vector<inl> read more..

  • Page - 793

    21 . 8 S ORTIN G AN D S EAR C H I N G ) ); fo r (int i = 0; i<x .le ngth (); ++i) ( if (i == y. length ()) return fa lse; II y<x char xx = tolowe r(x[i]); char yy = to lowe r(y[i); if (xx<yy) return true ; 1/ x<y if (yy<xx) return fa lse; /I y<x relurn true; II x<y ( fewer characters in x) void read more..

  • Page - 794

    ' 64 ( HAPTE R 21 • ALGOR IT HMS AND MAP S te mplate<class R a n, class T, class Cmp> boot bina ry_searc h(Ran first, Ran las t, const T& va l, Cmp cmp); These algorithms req uire and assume mat their input sequence is soncd. If it isn't, "interesting thi ngs," such as infinite loops, might happen. A bi nary_searchO simply tells LIS whether a read more..

  • Page - 795

    CHA I)TER 2 1 REVIEW 3. OUtput the (name,value) pairs to caul in some format of your choice. 4. Erasc the (name, value) pairs from msi. 5. Write a fu nction that reads value pairs from dn and places them in msi. 6. Read ten pairs from input and enter them into msi. 7. Write the elements o f msi to caul. 8. O utput the sum of the (integer) values in msi. read more..

  • Page - 796

    766 CHA PTE R 21 • ALGORITHMS AND MAPS 13. 'Wha t is an associative container? Give at least three examples. 14. Is list an associative container? Why not? 15. Wha t is the basic ordering property o f binary tree? 16. What (roughly) does it mean for a tree to be balanced? 17. How much space per element does a map take up? 18. How much space per element read more..

  • Page - 797

    CHAP TE R 21 EXERCISES 7. Write a binary search function for a vector<inl> (without using the stan- dard one). You can choose any interface you like. Te~l it. How confident arc you that your binary search function is correct? Now write a binary search fun ction for a lisl<slring>. Test it. How much do the two binary search functions resemble each other? How read more..

  • Page - 798

    768 CHAPTER 21 • ALGOR IT HMS AND MA PS Postscript The STL is the pan of the ISO C++ standard library concerned with containers and algoritluns. As such it provides very general, ncxiblc. and useful basic lools. It can save us a lot of work: reinventing the wheel can be fun, but it is rarely pro- ductive. Unless there are strong reasons not to, use the STL read more..

  • Page - 799

    Part IV Broadening the View read more..

  • Page - 800

    read more..

  • Page - 801

    ~ ,. 22 Ideals and History "When someone says, 'I want a programming language in which I need only say what I wish done,' give him a lollipop." - Alan Pe rlis T his chapter is a very brief and very selective history of pro- gramming languages and the ideals they have been designed to serve. The ideals and the languages that express them arc the basis read more..

  • Page - 802

    m 22.1 History, ideals, and pro fessionalism 22.1.1 Programmin g lang uage aims a nd philosophies 22.1.2 Programming id eals 22.1.3 Stylesfparadi gm s ( HAPTER 2 2 • IDEAL S AND H ISTORY 22.2 Programming language histo ry overview 22.2. 1 The ea rli est la nguages 22.2.2 The roots of mode rn languages 22.2.3 Th e Al gol family 22.2.4 Simul a 22.2.5 C 22.2.6 C++ read more..

  • Page - 803

    22.1 HISTORY, IDEALS, AND PROFESSIONA U SM A means of controlling computerized devices A way of expressing rela tio ns hips among concepts A means of expressing high-level designs Our answer is ''All of the above - a nd more! " Clearly, we arc thinking about gene ral-purpose programming languages here, as we will throughOUl this chap- ter. In addition, there arc read more..

  • Page - 804

    774 C HAPTER 22 • IDEALS AND HI STORY a language that does n't provide them imposes added wo rk and complications on its users. The reason we can't have it all is equall y fundam enta l: several of the propcnics are m utuall y exclus ive. For example, you cannOt be 100% pla tform in- dependent and also access all system resources; a program that accesses a read more..

  • Page - 805

    22.1 HI STORY, ID EALS , AND PROFE SS IONAL ISM Abstraction level M od ulmity Consistency and minimalism Ideals arc meant to be used. They arc tOols for thinking, nOt simply fancy phrases to trOt o ut to please managers and examiners. Ou r programs are meant to approximate o ur ide."lis. \"'hen we get stuck in a program, we step back to sec if o ur read more..

  • Page - 806

    CHAPTER 22 • IDEAL S AND HI STORY structure of the codc cause inefficiency. On the contrary, we find that ac- ceptable perfonnance is often achieved though adherence to the ideals and approaches we recommend. The STL is an example o f code that is si- multaneously abstract and very efficient. Poor pcrfonnance can as easily arise from an obsession with low-level details read more..

  • Page - 807

    22.1 HI STORY, IDEA LS. AND PR O FES SIONALISM We can't build and " prove" enough basic components to eliminate a ll sources of errors. We C."lIl't com pletely compensate for the flaws of buggy basic components (libraries, subsystems, class hierarchies, etc.) when combining them in the final system. However, a combination of approximations to the two a pproaches read more..

  • Page - 808

    77B (HAPTER 22 • IDEALS AND HISTORY Exprw simpk idellJ simply. Following the ideals listed above can lead to overly general code. For example, we may end up with class hierarchies with a more complicated taxoIlomy (inheritance structure) than anyone needs or w ith seven parameters to every (a pparentl y) simple class. To avoid every user havi ng to fa ce every possible read more..

  • Page - 809

    2 2. 1 HI STOR Y. I DEA LS, AND PROFE SS ION ALI SM major cOllcem in an application involving only your personal directory. However, this kind of trade-off becomes interesting when we have LO keep track of - and mao nipulate - millions of entries. More seriously, after a wltile, the usc of low· l evel fea· tures soaks up the programmer's time so that opportunities read more..

  • Page - 810

    780 CHAPTER 22 • IDEALS AND HI STORY These d iagrams arc intended to suggest inheritance and parameterization, respec- tively. In both cases, the imcrfacc provided must be smaller than a sim ple union of A's and B's interfaces for the exercise to be worthwhile. In other words, A and B have to have a fundamental commonality for users to benefit from. Note how we read more..

  • Page - 811

    22.1 HI STORY, ID EALS. AN D PROF ESS IONA LI S M 22.1.3 Styles/paradigms When we design and implement a program, we aim for a consistent style. C++ supports four major styles that can be considered fundamental: Procedural programming Data abstraction Object-oriented programming Generic programming These arc sometimes (somewhat pompously) called "progranuning paradigms." read more..

  • Page - 812

    782 C HAPTER 22 • IDEAL S AND HISTO RY Generic programming: the idea of taking concrete algorithms and "lifting" them to a higher level of abstraction by adding parameters to express what can be varied withollt changing the essence of an algoritilin. '11C highO example fro m C hapler 20 is a simplc example of lifting. loc findO and sortO algorithms from the read more..

  • Page - 813

    22.2 PROGRAMMI NG LA NGUAGE HISTORY O V ER V IEW object. In Olher words, it can easily be classified as plain data abstraction (no in- heritance) or even procedural programming (no data hiding). So, we could claim that this one line of code uses key aspects of all of the four fundamental styles supported by C++. But why would we write the second version of the read more..

  • Page - 814

    784 CHAPTER 22 • IDEALS AND HISTORY Languages) conferences. These arc extensively peer-reviewed papers - and there- fore far more truStworthy and complete than the average web source of informa- tion. TIle languages we discuss here were all represented at HOPL. Note thal if you type the fu ll title of a fatnous paper imo a web search engine, there is a good dml1cc that read more..

  • Page - 815

    22.2 PROGRAMMING LANG U AGE HI STORY OV ERVIEW was a list or machine instructions. The first primitive lists were decimal or octal numbers - exactl y matching their representation in the computer's memory. Later, assemblers and "auto codes" appeared ; that is, people developed languages where machine instructions and machine facilitie s (such as registers) had sym- bolic read more..

  • Page - 816

    786 CHAPTER 22 • IDEALS AND HI STO RY Campbell-Kelly, Martin. "David J ohn Wheeler." BiograJ)hi.cal Memoirs 0/ Fellows 0/ the Royal Society, Vol. 52, 2006. (His technicaJ biography.) EDSAC: http://en.wikipcdia.orglwikilEDSAG. Knuth, DonaJd . The Ar' 0/ Unnputer Programming. Addison-Wesley, 1968, and many revisions. Look for "David Wheel er" in the index of each volume. read more..

  • Page - 817

    22,2 PR OGRAMMING LANG UAG E HISTORY OVERV I EW mathematics, radlcr dmn dIe machine instructions provided by the (then very new) clectronic computers. From a modem perspective, Fortran can be seen as the first auempt to di- rectly re present an application domain in codc. It allowed proh'Tammers to write linear algebra much as they found it in textbooks. Fortran provided read more..

  • Page - 818

    788 CHAPTER 22 • IDEALS AND HI STORY The rust definition of and implementation of Fortran were done by a team at I BM lcd by J ohn Backus: "We did not know what we wanled and how to do il. It just sort of grew." H ow could he have known? Nothing like that had been done before, but along the way they developed or discovered the basic structure of read more..

  • Page - 819

    22.2 PROGRAMMING LANGUAGE H ISTORY OVERV I EW Calculation/com putation was (o ften correctly in COBOVs core application do- mains) seen as a minor matter. It was hoped/claimed that COBOL was so close to "business English" t..hat managers could program and programmers would soon become redundanl. That is a hope we have heard frequently repeated over the years by read more..

  • Page - 820

    CH APTER 22 • IDEALS AND HISTORY Grace Murray H opper is often credited with being the first person to call an error in a computer a "bug." She certainly was among the early users of the term and documented a usc: As can be seen, that bug was real (a moth), and it affected the hardware directly. Most modem bugs appear to be in the software and have read more..

  • Page - 821

    22 . 2 PROGRAMMING LANG U AG E HI STO RY OVERV IE W J ohn McCarthy's B.S. was in mathematics from the Californ ia Institute of lcchnology and his Ph.D. was in mathematics from Princeton University. You may notice that there are a lot of math majors among the programming language designers. After his memorable work at M IT, McCarthy moved to Stanford in 1962 to read more..

  • Page - 822

    792 CHAPTER 22 • IDEALS AND HI STO RY 22 .2.3.1 AIgol60 111C "ALGOritlunic Language," Algol, which resulted from the effofts of the I FIP 2. 1 group, was a breakthrough of modern programming language concepts: Lexical scope Use of grammar to define the language C lear separation of syntactic and semantic rules C lear separation of language definition and read more..

  • Page - 823

    22.2 PROGRAMM I NG LANG U AG E HI STO RY OVERVIEW Peter Naur was educated (as an astronomer) at the University of Copen- hagen and worked at the l echnical University of Copenhagen (DTH) and for the Danish computer manufacturer Regnecemralen. He learned programming early (1950-5 1) in the Computer Laboratory in Cambridge, England (Demnark didn't have computers that early) and read more..

  • Page - 824

    (HAPTER 22 • IDEAL S AND HI STORY TIle Algol family tree is impressive: A1go158 A1go160 A1go168 Ole Simula67 and PascaL These languages are the ancestors to many (probably most) modern languages. Refe rences Dijkstta, Edsger W. "Algol 60 Translation: An Algol 60 Translator for lhe xl and Making a Translator for Algol 60." Report MR 35/6 1. Mathematisch Cemmm read more..

  • Page - 825

    2 2.2 PROGRAMMING LANGUAGE HI STORY OVERVIEW Pascal was completed in 1970 and was indeed simple and somewhat inflexi· ble as a result. It was orten claimed to be intended just ror teaciling, but early pa- pers descri be it as an alternative to Fortran on the supercomputers or the day, Pascal was indeed easy to learn, and arter a very portable implementation be· came read more..

  • Page - 826

    C HAPTE R 22 • ID EAL S AND HI STORY Anders H ejlsberg. Anders Hej lsberg was one of the three founders of Borland. He first designed and implemented Turbo Pascal (providing, among other things, more fl exible argument-passing fa cilities) and later added a C ++ -like object model (but with just single inheritance and a nice module mechanism). He was educated at read more..

  • Page - 827

    22 .2 PROGRAMMING LA NG U AG E HI STORY OVERVIEW §22.2.6). ~ 111 e leader of the group that designed Ada was jean Ichbiah - a past chainnan of the Simula Users' Croup. TIle Ada dcsign emphasized Data abstraction (but no inheritance until 1995) Strong static type checking Dircct language support concurrency "111e design of Ada aimed to be the embodiment of software read more..

  • Page - 828

    ". CHAPTER 22 • IDEAL S AND HI STORY Ada's Lise was mandated for military applications by the 0 00 for many years, leading to the saying "Ada, it's nOtj usl a good idea, it's the law! " Initially, the usc of Ada was just "mandated," but when many projects received "waivers" to L1 SC other languages (typically C++), the U.S. Congress read more..

  • Page - 829

    2 2 , 2 PROGRAMMING LANG U AGE HI STORY OVERVIEW Simula's conlli bution is not limited to language fea tures. It came with an ar· ticulated notion of object-oriented design based on the idea o f modeling re.."ll· world phenomena in code: Represent ideas as classes and class objects. Represelll hierarchical relations as class hierarchies (inheritance). l lms, a program read more..

  • Page - 830

    800 CHAPTER 22 • IDEALS AND HI STOR Y Olc:Johan Dahl was a morc conventional academic. H e was vcry imcrested in specificati o n languages and formal mclllOds. In 1968, he became the fi rst full professor of informatics (compuler science) at O slo U niversity. In August 2000 Dahl and ygaard wcre made Commanders o f the O rder of Saint Olav by the King o f read more..

  • Page - 831

    22.2 PROGRAMMIN G LANG U AGE HISTORY OVERVIEW em ific programming before Fortran. Several indi viduals and groups set out to challenge that orthodoxy. In the long ru n, the C programming language (Chap- ter 27) was by rar the most successful of those effons. Dennis Ritchie designed and implemented ule C programming language in Bell 1clephone Laboratories ' Computer Science read more..

  • Page - 832

    802 CHAPTER 22 • IDEALS AND HI STO RY In the early years, 1974-1979. many people in Bell L1.bs influenced the de- sign of C and ilS adoption. Doug McIlroy was everybody's favorite critic, d iscus- sion partner, and ideas man. He influenced C , C++. Unix, and much morc. Brian Kernighan is a programmer and wri ter cxtraordinairc. Both his code and his prose arc read more..

  • Page - 833

    22.2 PR OG RAMMING LANG UAGE HI STORY OV ER V I EW accessible to large nu mbers of people in their target audience. Verbosity is among the worst enemies of such presentation of ideas; so is obfuscation and over- abstraction. Puris ts often scoff at the results of such popularizatio n and prefer "original results " presented in a way accessible only to expertS. read more..

  • Page - 834

    C HAPTER 2 2 • IDEAlS AND HISTORY Kemighan, Brian, and Dennis Ritchie. 17te C Programming umguage. Prentice Hall . 1978. Second Edition, 1989. ISBN 0131103628. A list of members of the IkU Labs' Computer Science Research Center: http://an.bcll- labs.com/an/csJalumni.hUlll. Ritchards, Martin. BCPL - The Language and Its (;om/)11er. Cambridge University Press, 1980. ISBN 052 12 19655. read more..

  • Page - 835

    22.2 PROGRAMMING LANG U AGE HI STORY OVERVIEW Bjarne Stroustru p received a master's degree (in mathematics with computer science) from the universil)' in his hometown, Arhus in Denmark . TIlen he went to Cambridge. where he got his Ph .D. (in computer science) working fo r David \¥heeler. ~ nle main contributions of C++ were to Make abstraction techniques alTordable and read more..

  • Page - 836

    CHAPTER 22 • IDEALS AND HI STORY Alex Stepanov is the inventor o f the S11.. and a pioneer o f generic program- tning. H e is a graduate of the University of Moscow and has worked on robolics, algorithms, and more, using a variety of languages (including Ada, Scheme, and C++). Since 1979 , he has worked in U.S. ac.,demia and industry, notabl y at CE Labs, read more..

  • Page - 837

    22 .2 PROGRAMMING LANGUAGE HI STORY O V ERVIEW StrouStrup, Bjarnc. "C and C++: Siblings" ; "C and C++: A Case for Compati- bility"; and "C and C++: Case Studies in Compatibility." 7k C/C++ UjC"J JOlimal. July, Aug., and Sept. 2002. SU'OllStrup, Bjame. ;'Evolving a Language in and for the Real World: C++ 1991- 2006. Proceedings o f the Third ACM read more..

  • Page - 838

    ( HAP TER 22 • IDEAL S AND HISTORY lOG (a data-gathering firm), discussions with publishers and compiler suppliers, and various web sources_ Feel free to quibble, but we know the number is larger than I million and less than 100 million for any halfway reasonable definition of "programmer." Which language do they use? Ada, C , C++, Cf', COBOL, For- tran,Java, read more..

  • Page - 839

    C HAPTER 22 REVIEW Review 1. YVhat are some uses of history? 2. \¥hat are some uses of a programming language? List examples. 3. List some fundamental properties of programming languages that are ob- jectively good. 4. What do we mean by abstraction? By higher level of abstraction? 5. \¥hat arc our f our high.level ideals for code? 6. List some potential advantages of high. read more..

  • Page - 840

    810 CHAPTER 22 • IDEALS AND HISTORY Terms In this chapter "Terms" are really languages, people, and organizations. Languages, Ada Algol BCPL C C++ COBOL Fortran Lisp Pascal Scheme Simula People: Charles Babbage J ohn Backus Olc:Johan Dahl Edsgcr Dijkstra Anders H ejlsbcrg Grace Murray Hopper J ean lchbiah BI;an Kernighan John McCarthy Doug Mcllroy Peter Naur Kristen Nygaard read more..

  • Page - 841

    CHAPTER 22 EXERCI S ES Exercises 1. Define programming. 2. Define programming langJl~. 3. Go through the book and look at the chapter vignettes. Which ones were from computer scientists? Write one paragraph summarizing what each of those scientists contributed . 4. Go through the book and look at the chapter vignettes. Which ones were nOt from computer scientists? Identify the read more..

  • Page - 842

    .,2 CHAPTER 22 • IDEAL S AN D HISTORY Postscript Obviously, we have only scratched the surface of both the history of program- ming languages and of the ideals that fuel the quest for better software. We COIl- sider hisLOry and ideals sufficiently important to feel really bad about lila(, We hope LO have conveyed some of our excitement and some idea of the immensity read more..

  • Page - 843

    \ 1 . . ,.- 23 Text Manipulation "Nothing is so obvious that it's obvious ... . The use of the word 'obvious' indicates the absence of a logical argument." - Errol Morris T his chapter is mostly about extracting information from texl. We store lots of our knowledge as words in docu- ments, such as books, email messages, or "printed " tab les, just to read more..

  • Page - 844

    814 23.1 Text 23.2 Strin gs 23.3 VO streams 23.4 Maps 23.4.1 Im pleme ntatio n de tails 23.5 A problem 23.6 The idea of regular expressions 23.7 Searching with regular expressions 23.1 Text CHAPTER 23 • TEXT MANIP ULATI O N 23.8 Reg ular ex pressio n syntax 23.S.1 Characte rs and special characters 23.8.2 Characte r classes 23.S.3 Repeals 23.8.4 Grouping 23.S.S Alt read more..

  • Page - 845

    23 .2 STRINGS Selecte d s trin g ope rati on s sl = s2 S += X sfil sl+s2 s l ==s2 sl<s2 s.sizeO s.lenglhO s.cstrO s. begin O s.end{) s.inserl(pos,x) s.append(pos,x) s.e rase( pos) pos = sJi nd (x) in>>s gelline(in,s) o ut<<s Assign s2 to s l ; s2 can be a Siring or a (-style s iring. Add x at end; x can be a c hara cter, a Siring. or read more..

  • Page - 846

    116 CHAPTER 23 • TEXT MANIP U LATION The standard library string is really a template, called basic_string, that sup- ports a variety of character sets, slich as Unicode, providing thousands of charac- ters (such as [, n, 00 , 0, Q, and ~~ in addition to "ordinary characters"). For example, if you have a type holding a Unicode character, slIch as Unicode, you read more..

  • Page - 847

    23.2 STRING S The opposile conversion, from slrings to numeric values, is about as easy, and as useful: struel bad_from_string : sld::bad_cast /I class for reporting sIring cast errors { consl char · whalO consl II override bad_casl's whalO ( relurn "bad casl from siring"; ) ); lemplale<class T > T from_slring{consl s lring& s) ( istringslream isIs); T I; if (!(is» read more..

  • Page - 848

    818 CHAPTER 23 • TEXT MANI PULATION So mere is a possibility of error, which we have represented by the exception ba d_fram_slring. In §23.9, we demonstrate how fro m_slringO (or an equi valent function) is essential for serious tex t processing because we need to extract nu- meric values from text fields. In § 16.4.3, we saw how an equivalent fu nction gcUIlIO was read more..

  • Page - 849

    2) . ) 1/ 0 STREAMS that by seeing if we arc at "end of file." So if we arc trying to read an int from a string using lexical_cast, "123 " and "123 " will s ucceed , but "123 5" will not be- cause o f that last 5. "nlis rather elegant, though oddly named , lexicaCcast is provided by the boost library, which we will read more..

  • Page - 850

    8W ( H APTER 23 • TEXT MANIP U LATION 23 .4 Maps Associative arrays (maps, hash tables) are key (pun imended) to a lot of text pro- cessing. The reason is simply that when we process text, we collect informatio n, and that information is often associated with text strings, such as names, ad· dresses, postal codes, SociaJ Security numbers, job titles, etc. Even if read more..

  • Page - 851

    23.4 MAP S To: "Mary Smith : Personal Account " <sm ith@home.example> From : John Doe <jdoe@maehine.example> Subject: Re: Saying Hello Date: Fri, 21 Nov 1997 11 :00 :00 - 0600 Message- ID: <abed .1234@loeal.maehin e. lld> In- Re ply-To: <3456@example. net> Refe re nees: <1234®loeal. mae hi n e. exam pic> <.l456@cxampl c. net> This is a re ply read more..

  • Page - 852

    822 CHAPTER 23 • TEXT MANIP U LATION To this , we will add itcrators and beginO and end() functions, so that we can iter- ate through the lines and through t.he messages in the usual way. "111is "boiler- plate" will allow liS conveniem access to the messages . Given that, we will write our " toy application " to gather all the messages from read more..

  • Page - 853

    2 3.4 MAPS class Message ( /I a Message points to the first and the last lines of a message line_ite r first; Line_ite r las t; publi c: } ; Message(Line_ile r pl , line_ile r p2) :firs((pl ), lasl(p2) { } lin e_ite r beginO co nst ( re turn first; } lin ej le r e n dO const { re turn last; } 1/ . . . We define a MaiU ile as a structure read more..

  • Page - 854

    824 C HAPTER 2 3 • TEXT MANIPULATION int main O ( ) M ail_fil e mfile(lIm y-mail-file.txt"); II initialize mfi le from a file /I fi rst gather messages from each sender togeth er in a m uhimap: mullimap<Slring, const Message·> sender; fo r (M ess_i ter p = mfile. begin (); p l=mfi le.end() ; ++p) ( con st Message& m = · Pi string S; if (fi read more..

  • Page - 855

    2 ) ,4 M APS What goes into a map is a (ke y, value) pair, whidl wc make with make_pairO_ We use our '·homemade" find_from_addrO to find the name of thc sender. We use the empty string to indicate that an add ress wasn't found . Why do we introduce the refe rcnce m and pass its addrcss? Why don 't we just usc p dircctly and say find_fr om_addr(p,s) read more..

  • Page - 856

    826 CHAPTER 23 • TEXT MANIP U LATION 23.4.1 Implementation details Obviously, we need to implement the fu nctio ns we usc. It was tempting to save a tree by leaving this as an exercise, bUl we decided to make this example complete. The MaiLfile constructor opens the flle and constructs the lines and III vectors: MaiUile:: MaiUile(co nst string& n) /I open fi Ie read more..

  • Page - 857

    2 3.4 MAPS int is_prefix(const string& s, ca nst string& p) /I is p the fi rst part of s? ) int n = p.size(); if (string(s,O,n)==p) return n; return 0; bool find_from_addr(const Message' m, string& s) { ) for(lin ejter p = m->begin(); p!=m->endO ; ++p) if (int n = is_prefix(O p, "From: "» { s = string(" p, n); return true ; ) return false read more..

  • Page - 858

    828 (HAPTER 23 • TEXT MANIP U LATION Is the distinction m ade by find_iro m_addrO useful? Nccessaly? We think lhallhc distinction can be usefu l a nd lhat we definitely sho uld be aware of it. It is a dis- tinction that comes up again and again when looking for information in a data fLle: did we find the field we were looking for and was there something read more..

  • Page - 859

    23 .5 A PROBLEM We accept (intentionally?) every ZIP code number with the lellers in lower case (such as tx77845). If we decided to look fo r a postal code in a different format (such as C8 l OFD), we have to completely rewrite the code. TIlere has to be a better way! Before revealing that way, let 's juSt consider the problems we would encoulller if we decided read more..

  • Page - 860

    83. (HAPTER 2 3 • TEXT MANIPU LAT ION The regular expressions we will usc arc implemented by a library that will be pan of the next C++ standard (C++Ox). It is compatible with the regular expres- sions in PERL. lbis makes many explanations, tutorials, and manuals available. ror example, see the C++ standard COI11l1uttee's working paper {look for "WG21 " on the read more..

  • Page - 861

    23.6 THE IDE A OF REGULAR EXPRE SS IO NS acter by simply repeating. That can be a bit tedious and is potentially error-prone. Qtick: Did we really gel the five digits before the dash and four after it right? We did, but nowhere did we actually Jl!)' S and 4, SO you had to count to make sure. We could add a COLInt after a character to indicate repetition. read more..

  • Page - 862

    832 CHAPTER 23 • TEXT MANIP U LATION ~w{2}\d {S}}{ - \d{'}} I As with the curly braces in the count notation (e.g. , \w(2l) , we lise lhc question mark (1) as a suffiX. For example, (-\d{4})1 means "optionally -\d{4} "; that is, we accept four digits preceded by a dash as a sumx. Actually, we arc not using the parentheses around the pattern for the read more..

  • Page - 863

    23.7 SEA RC HI NG WITH RE GU LA R EXPR ESS IONS 23.7 Searching with regular expressions Now, we will use the ZI P code pattern from the previous section to find ZI P codes in a me. The program defines the pattern and then reads a me line by line, searching for the pattern . If the program finds an occurrence o f the pattern in a line, it writes out read more..

  • Page - 864

    834 C HAPTER 2] • TEXT M AN I PULATION Back to regular expressio ns! Consider: boost : :regex pat ("\\w{2}\\s-'\d{5}(- \\d{4})1 ") ; coul « "pattern : "« pat « '\n 'i Here we first define a patlern, pat (of type regex), and then write it to outpul. Note that we wrote "\\w{2}1" ' lid {5}{ - IId{ 4} I'" If you run the program, read more..

  • Page - 865

    23.7 SE AR CHI NG W ITH REG U LAR EXPRESS IONS ) if (boost: :rcge,,-search(lin e, matches, pat)) { co ut « lineno « ": " « matches[O]« '\n'; if (1<malches.sizeO && malches[l ]. malched) cout «"\I: "« malches[l ]« '\n '; ) II whole match II sub-match Strictly speaking, we didn't have to test l <malchcs .size() because we already read more..

  • Page - 866

    83. ( HAPTER 23 • TEXT MANIP U LATION Only found the first Z I P code from the line with zzz (we only asked for one per line) Found the correct suffIxes on lines 5 and 6 Found the Z IP code "hidden" among lhe xxx's on line 7 Found (unfortunately?) the Z IP code "hidden" in TX12345-123456 23.8 Regular expression syntax 'ATe have seen a rather read more..

  • Page - 867

    23. 8 ":ECUlAR EXPR ES SIO N SYNTAX Characters wilh special meaning an y single character (a ~ wildcard") [ character class { count I • + I s begin grouping end grouping next character has a special meaning zero or more one or mo re optional (zero or one) alternative (or) start of line; negation end of line For example, '.y matches any three-letter read more..

  • Page - 868

    838 C H APTE R 2 3 • TE XT MAN IPULAT ION Special characters for character classes (continued ) II) It IS \U \W not \ d flO! \ 1 not \5 not \ u not \ w I" [:digil :)) ("{ :Iower : )] ' ''[ :space :1I I"[: upp e r:]] [ "[: alnum :lJ Note lhm an uppercase special character means " not th e lowercase version o f th at read more..

  • Page - 869

    2 3.8 REGU LAR EXPRE SS ION SYNTAX Au Axxxxxxxxxxxxxxxxxxxxxxxxxxxxx If you want at least onc occulTence, usc + rather than · . For example, malches an A followed by one or mon: xs, such as A, Au Axxxxxxxxxxxxxxxxxxxxxxxxxxxxx but not A The common case of zero or one occurrcnce ("optionan IS represented by a question mark. Fo r example, Id- l\d matches the two read more..

  • Page - 870

    840 Ab-123 ?b-1234 Yes, digits are \w characters. 23.8.4 Grouping C H APTER 2 3 • TEXT MANIPULAT ION To specify a regular expression as a sub-pattern, you group it using parentheses. For exam ple: 1Id-,) lllis defines a sub-paltern of zero or more digits followed by a colon. A group can be used as part of a morc elaborate pattern. For example: 1Id-,)/IId+) This read more..

  • Page - 871

    23 .8 REG ULA R EXPRES SIO N SYNTA X However. \\'e can specify several alternatives at once: (bsI BslbSIBS) 23.8.6 Character sets and ranges rn le special characlers provide a shonhand for the most common classes of char- acters: digits (\dl; letters, digits, and underscore (\wl; etc_ (§23.7.2l. However, it is easy and often uscfulto define our own. For example : l\w @1 read more..

  • Page - 872

    342 CHAPTER 23 • TEXT MANIPULATION strin g s = "\" [[:alnum : ]I+\"" ; Furthe rmo re, to put tha t string into a regcx, we must escape lhe backslashes as well as th e quotes and usc the () style of initialization because regex's constmctor from a Siring is explicit: regex 5("\\\"11 : alnum : 1J+\\\''''); Using regular expressions leads LO read more..

  • Page - 873

    23 .11 REGU LAR EXPRE SS ION SYNTAX W hen we assign a pattem to a regeJl., the patlem is checked, and if the regular ex· pression matcher can't use it fo r matching hec.1.use it's illegal or too cOlllplic.1.ted , a bad_eJl.pression exception is th rown. Here is a little program that's useful for getting a feci for regular expression matching: #include read more..

  • Page - 874

    144 C HAPTER 2] • TEXT MANIPULATION if (regex_searc h(line, matc hes, patte rn» ( ) e lse co ut « " line " « Iine no « " : " « line « '\n' ; for (int i = 0; kmalches.sizeO; ++ i) co ut « "\Imatches[ " « i « "]: " « matc hes[i) « '\n ' ; cout « "d id n't match\n "; TRY THIS Get the read more..

  • Page - 875

    23.9 MATCHIN G W ITH REGULAR EXPRE SSIONS KLASSE ANTAL DRENGE AN TAL PIGER ElEVE R IALl 6B 9 10 19 7A 7 19 26 7G 3 5 a 71 7 3 10 BA 10 16 26 9A 12 15 27 OMO 3 2 5 01>1 2 01'2 0 5 5 l OB 4 4 a I OCE 0 IMO a 5 13 2CE B 5 13 3DCE 3 3 6 4MO 4 5 6CE 3 4 7 aCE 4 4 a 9CE 4 9 13 REST 5 6 " Aile klasser 184 202 read more..

  • Page - 876

    (HAPTE R 23 • TEXT MANIPULATION We will illustrate the lise of regular expressions to Verify that this table is properly laid out (i.e., every row has the right number of fields) Verify that the numbers add up (the last line claims to be the sum o f the columns above) If we can do lhat, we can do juSt a bout an ything! Fo r example, we could make a new read more..

  • Page - 877

    23 .9 MATC H ING WITH REGULAR EXPRESSIONS which, after putting it into a string literal, is "" [\\ w 1+( \\d+)( \\d +){ \\d+ )$" Now all we have to do is LO use those patterns. First we will juSt validate the table layout: in l mai nO ( ifstream in (" la ble.txl ") ; II input fi Ie if (! in) e nor("no input fil e\n ") ; read more..

  • Page - 878

    848 C HAI' TER 23 • TEXT MANIPULATI ON To check that, we modify row to make the text field a subm3tch so tha t we can recognize "Allc klassc r"; int ma inO ( ifslream in(" table .txl "); /I input fil e if (!in) c rror (" no input fil e "); siring linc; II i nput buffer int line no = 0; regex h eader( "" [\\w ]+( read more..

  • Page - 879

    23 . 10 REFEREN C ES ) 1/ update totals: boys += c urt_boy; girls += curr....girl ; e rror("didn 't find total line "); 111e last row is semantically d ifferent from the other rows - it is their sum. \o\'e recognize it by its label ("Aile klasse r"). We decided to accept no more non-white- space characters arter that las t one (using the technique read more..

  • Page - 880

    850 CHAPTER 23 • TEXT MA N IPULATION ~ Drill 1. Find out if regclI: is shipped as part of your standard library. H int: Try sid : : regell: and tr1 :: rege).:. 2. Get the little program from §23.7.7 to work; t.hat may involve getting boost :: regex installed on yOlll' system (if it isn't already) and figuri ng out how to set the project and/or command·line read more..

  • Page - 881

    (t-tAPTER 23 EXERCISES 22. What is the nOlation for an uppercase charactcr? 23. H ow do you specify your own character set? 24. H ow do you extract the value of an integer field ? 25 . H ow do you represent a noating·point number as a regular expressio n? 26. H ow do you extract a noating-point value from a match? 27. What is a sub·match? How do you access read more..

  • Page - 882

    852 CHAPTE R 23 • TEXT MANIPULATION 8 . Modify the program from §23.8.7 so that it takes as inputs a pattern and a fIle name. Its output should be the numbered lines (line- number: linc) that contain a match of the pattern. If no matches arc found , no Olltput should be produced. 9. Using eorO (§B.7.2), it is possible to detcnninc which line of a ta ble is read more..

  • Page - 883

    ' .. L '-:24 Numerics "For every compl ex problem there is an answer that is clear, simple, and wrong." -H. l. Mencken T his ch apter is an overview o f some fu ndam ental lan gu age and library facilities supporting nu meric computatio n. We present the basic problems of sizc, precision , and truncation . The central part of the chapter is a d iscussion read more..

  • Page - 884

    854 24.1 Intro ductio n 24.2 Size, precision, and overflow 24.2.1 Numer ic limits 24.3 Arrays 24.4 C-slyle multidime nsional a rrays 24.5 The Matrix library 24 .5.1 Dim e nsions and access 24.5.2 10 Matrix 24.5.3 20 Matrix 24.5.4 Matrix I/O 24.5.5 3D Matrix 24.1 Introduction CHA PTER 2 4 • NUMER ICS 24.6 An example: solving linea r e quatio ns 24.6.1 Classical Ga read more..

  • Page - 885

    2 4. 2 SIZE , PREC ISION, AND OVER FLOW and the floating-point types (float , do uble, etc.) a re (only) approximations of t.he ma the matical notion o f real numbers. TItis implies that from a mathema tical point of view, some compmatio ns arc imprecise o r wro ng. Consider: float x = 1.01333; float sum = 0; fo r (int i=O; k 333; ++i) s um+=x; cout « read more..

  • Page - 886

    856 Consider an integer problem: sho rt int y = 40000; int i = 1000000; cout « y« " " « j *j« "\n" i Running this, we got the output - 25536 -n7379968 CHAPTER 24 • NU MERI CS ·nlat was expected. \oVhal we see here is the effeCl of overflow. lmcgcr types re p- resent (relatively) small integers only. There just aren't enough biLS LO cxacLiy read more..

  • Page - 887

    2 4 .2 SIZE , PRECI SION , AND OVERF LOW 21 00000OO9 2100000000 A float and an int take up the same amount of space (4 bytes). A float is repre- sellted as a "mantissa" (typically a value between 0 and I) and an exponent (mantissa* IO ....... ), so it calUlot represent exactly the largest int. (If we tried to, where would we find space for the read more..

  • Page - 888

    858 (HAPTER 24 • NUMERI C S TRY THIS Run gO. Modify fO to prim out c, s, i, etc. Test it with a variety of values. Ille representation of integers and their conversions will be examined fur- ther in §25.5.3. When we can , we prefer to limit ourselves to a few data types. That can help m inim ize confusion. For example, by not using fl oat in a program, read more..

  • Page - 889

    24.4 C-STYlE MULTIDIMENSIONAl ARRAYS 24.3 Arrays An amry is a sequence of elements where we can access an element by its index (p0- sition). Another word for tlmt general notion is ueclor. Here \ve arc particularly eOIl- cellled Witll arrays where the clements arc themselves arrays: multidimensional arrays. A common word for a multidimensional array is IfUltrix. The variety of read more..

  • Page - 890

    .60 int ail4J; double ad[3][4]; char ac[3][4][Sl; ai[l] = 7; ad[2][3] = 7.2; ac[2][J][4] = 'e' ; Il l-dimensional array 1/ 2-dimensional array 11 3-dimensional array CHAPTER 24 • NUMERI C S 1l1is approach inherits the virtues and the disadvantages of the one-dimensional array: Advantages Direct mapping LO hardware Efficient for low-level operations Direct language support Problems read more..

  • Page - 891

    2 4 . 5 Tt-lE MATR IX LIBR A RY void f5(int· m, int diml , int dim2) II odd, but works { for (int i=O j i<diml j ++i) for (int j = OJ j<dim2 ; ++j) mWdim2+jJ = OJ ) Here. we pass m as an int- even though it is a two-d imensional array. As long as the second dimension needs to be a variable (a parameter). there really isn't any way of read more..

  • Page - 892

    862 C H APTER 2 4 • N U M ERIC S Basically, lra nsfon ns conventional array/vector notation into the code yOll would laboriously have had to write yourself (and n ms at least as ef- ficiently as that). You can extend it yourself as needed (no "ma b';c" was used in its imple- mentation). ~nlC Matrix library does that a nd only that. If you waIll more, read more..

  • Page - 893

    24 . 5 THE MATRIX LIBRARY ad2(nl, n2»); those a rguments speeify the dimensions. So, ad2 is a nvo-dim ensionai array with dimensions nl and n2, also known as an nl -by- n2 matrix. To gel an e1emelll of the declared clement type from a onc-di mell5 ional Matrix, you sub- script with one index; to get an clement of the declared element type from a two- dimensional read more..

  • Page - 894

    ... (HAI'TE R 24 • NUMERICS We catch mismatches between the declared number of dimensions and their use al compile time. Range errors we catch at run time and throw a Malril,_error exception. IllC first dime nsion is the row and the second the column, so we index a 20 matrix (two-dim ensional array) with (row,column). We can also usc the [..ow][co1- umn] notation read more..

  • Page - 895

    14.5 THE MATR I X LIBRARY Note that the Malrix library doesn't supply matrix operations, sllch as adding two 40 Malrixes o r multiplying a 20 Malrix with a l D Malrix. Doing so ele- gantly and efficiently is currently beyond the scope o f this library. MatrL,( li- braries of a variety of designs could be built on top of the Malrix library (sec exerCLse 12). 24.5.2 read more..

  • Page - 896

    866 C H APTER 24 • NU MERI CS a.slice(4.4) = a.slice(0,4); /I assign first half of a to second half For example, if a starts out as { 1 23 4 567 8 } we get { 1 23 41 23 4 } Note that the most common slices are the "initial elements" of a Matrix and the "last elements"; that is, a.s lice(O,j) is the range [0:;) and a.s li ce(j) read more..

  • Page - 897

    24 . 5 THE MATRIX lIHRARY The composite assignment operators and applyO modify the elements of lheir Matrix argu mcnt. If we instead want to create a new Matrix as the result, we can use b = apply(abs,a)j /I make a new Matrix with b(i)::abs(a(i)) This abs is the standard library's absolute valuc function (§24.8). Basic.1..IIy, apply(f,x) relates to x.apply(f) as + relates read more..

  • Page - 898

    ... CHAPTER 24 • NUMERICS 11l(~ scale_and_addO operation is often referred to asfitsed lJIullijJly-add or simply /mll; its defmilion is result(i)=arg1(i)"a rg2+arg3(i) for cadI i in the Ma trix.. ~111C dot product is also kllown as the inner_product and is described in §21.5.3; its defini- tio n is resull+=a rgl (i)-arg2(j) fo r each i in the Matri x where result read more..

  • Page - 899

    24 .5 THE MATRIX LIBRARY We can as k for the total number of elements a nd the number of elements of eaeh d imension. We c..""tIl get a pointer to the clements as they arc laid out in mem ory as a matrix. We can subscript: a(i,j); a(iJ; ali][jl; II {i,Pth e lement (Fortran style), but range c hecked II ith row (C style), ra nge checked II (i,Plh read more..

  • Page - 900

    870 C H APTER 2 4 • NUMERI CS It tllrns Ollt that swapping rows is often useful, so we supply that: a .swap_rows (7,9); II swap rO\vs al71 <-> a[9 1 TIlerc is n o swap_column s() . If you need it, write it yourself (exercise 11 ). Be- cause of the row-first layout, rows a nd columns arc nOl completely synunc u'ical conce pts. Illis asymmetry also shows read more..

  • Page - 901

    24.5 TH E MATRIX LIBRARY dn» a, co ut « a, ll1is will rcad four whitcspacc-scparatcd doubles delimited by curly braccs; for cxamplc: ( 1.23.45.67.8 } ~111C output is very similar, so that you can read in what YOll wrote out. 111c 110 for 20 Matrixes sim ply reads and writes a curly-brace-delimited se- quencc of 10 Matrixes. For example: Matrix<int,2> m(2,2) ; ein» read more..

  • Page - 902

    a[iJ[jl (k] ; a.slice(i); a.slice(i,j)i Matrix<int ,3> a2 = ai a= al i a·= 7i a.applY<O i a.a pply(f,n i b=apply(f,a)i b=apply(f,a,n i a.s wap_rows(7,9) i ( HAPTER 24 • NUMERICS /I (i,j,k)th element (e style) /I the elements from the ith to the last 1/ the elements from the ith to the jth /I copy initializa tion 1/ copy assignment /I scaling (and +=, -=, read more..

  • Page - 903

    2 4 .6 AN EXAMPLE: SO LVING LINEAR EQUATIO NS 111e goal is to find values for the unknowns I.hat simultaneously satisfy the 1/ equations. 111cse equations can compactly be expressed in temlS of a matrix and two vectors: Ax = b Here, A is the square n·by-n matrix defined by the coefficients: A= a.... a ..... TIle vectors x and b arc lhe vectors of unkllowns and read more..

  • Page - 904

    874 CHA PTER 24 • N UMERI CS For each II, we divide by a(n,n) so the diagonal values must be nonzero. If t.hat docs not hold, the back substitution method fails, meaning that the system has zero or an infinite number of solutions. 24.6.1 Classica l Ga uss ian e limination ow let us look at the C++ code to express lhis. First, we'll simplify OUf notation by read more..

  • Page - 905

    24 .6 AN EXAMPLE : SOLV I NG LINEAR EQ U ATIONS ~nle "pivot" is the element that lies on the diagonal of the row we arc currently dealing with. It mUSt be no nzero because we need to divide by it ; if it is zero we give up by throwing an exception : Vector back_s ubstitution (const Matrix& A, co nst Vector& b) ( ) consllndex n = A.diml(); Vector read more..

  • Page - 906

    876 } CHAPTER 2 4 • NU MERI CS /I elimi nation: for (Index i=j + 1; i < n ; ++i) ( consl double pivot = A(j, j); } if (pivol==O) error( tlean 'l solve: pivot==O"); consl double mull = AO, j)/pivot; Alil .slice(j) = scale_a nd_add(A[jl.slice(j), -mull, A(i] .slice(j»j b (i) -= mull · b (j); We usc swap_rowsO and scalc_and_multiplyO to make the code read more..

  • Page - 907

    24.7 RAN DO M NUMBERS However, Ollr test is not as realistic as we'd like because gelluincly random matri- ces m·c unlikely to c.'1USC problems ror classicaCeliminalion . To veriry our solution, we print out A - x, which had better equal b (or close cnough ro r our purpose, given rounding errors). The likelihood o r rounding er- rors is the reason we didn't just do read more..

  • Page - 908

    878 ( H AP TER 24 • NUME RI CS Such numbers arc most useful in testing (that's one way of generating a lot of test cases), in games (that is one way of ma king sure that the next nm of lhe game difTers from the previolls nm), and in simula tions (we can make a simulated en- tity behave in a "random" fashion within the limits of its parameters). read more..

  • Page - 909

    2 4 .8 T HE STA ND A RD M AT HE M ATI C A L FUNC TI ONS ' nus used to be a reall y bad idea because this simpl y picks o fT the low-order biLS of th e random number and those biLS are not properly rand o mized by man y tra - ditio nal random number generators. Today, it appears to b e ben er o n many sys- tems, but for portable code, read more..

  • Page - 910

    880 C HAPTE R 24 • NUMERICS The standard mathematical functions are provided for types floal , double , long double , and complex (§24.9) arguments . If YOLI do floatin g-point computations, you 'll fmd these functions useful. If you need more details, documentation is widely availa ble; your online documentation would be a good place to start. If a standard read more..

  • Page - 911

    24 .9 COMP LEX N U MBER S public: complex(const Scala r & r, const Scalar & i) : re(r), im(i) () complex(co nst Scala r & r) : re( r),im (Scalar ()) () complexO :re (Scala r ()}, im(Scalar ()) { } Scalar realO { re turn rej } /I rea l pa r! Scalar imagO { re turn im j } /I imaginary par! /I ope rators: = += -= ' = 1= }; '11C read more..

  • Page - 912

    882 C HAPTER 24 • N UMERI CS void f(dcmplx z, veclo r<dcmplo& vel { ) d cmplx z2 = po w(z,2); d cmplx %3 = 12 *9.3+vc[3J; d cmplx sum = acc umula te(vc.begin(), vc.end(), dcmplx()); 1/ . .. Remember lhat nOt all opcralions that we are lIsed to from int and do uble arc defined for a complex . For example: if (z2<%3) II error: th ere is no < read more..

  • Page - 913

    CHAPTER 24 DRILL Geomctry and topology Mathematical physics Malilemalical astrono my TIle histOlY of mathematics Freeman, T L., and Chris Phillips. Parallel Numerical Algonlll1l1.J. Prentice Hall, 1992. Cullberg,J an. Mallu!IIwha - From tIle Birth of Number;. W. W. Norton, 1996. ISBN 039304002 X. O ne o f the most el~oyable books on basic and useful malilemat- ics. A (rare) math read more..

  • Page - 914

    884 CHA PTER 2 4 • NU MERI CS Review 1. \OVho uses numerics? 2. \.vhal is precision? 3. Wha t is ovcrnow? 4. ,.vha t is a conunon size of a do uble? Of an int? 5. How can you detect ovcrnow? 6. Where do yo u rmd nume ric limits, such as the largest int? 7. VVhal is an array? A row? A column? 8. Wha t is a C -stylc multidimensional array? 9. read more..

  • Page - 915

    CHAPTER 24 EXERCISES Exercises I. The function arguments r for a.apply(O and apply(f,a ) arc differelli . Write a d oubleO fun ction for each and usc each to double the elements of an array { 1 2345 }. Define a single doubleO function that can be used for both a.a pply(double) and apply(do uble,a). Explain why it could be a bad idea to write every function to read more..

  • Page - 916

    886 CHAPTER 24 • NUMERICS Postsc ript If you don't feci comfonable with mathematics, you probably didn't like this chapter and you'll probably choose a field of work where you arc unlikely to need the infonnation presented here. On the other hand, if you do like mathe- matics, we hope that you appreciate how closely the fundamental concepLS of mathematics can be read more..

  • Page - 917

    , t , ' ,.. 25 Embedded Systems Programming " 'Unsafe' means 'Somebody may die .' " -Safety officer W e present a view of embedded systems programming; that is, we discuss topics primarily related to writing pro- grams for "gadgets" that do not look Like conventional computers with screens and keyboards. We focus on the principles, program- ming techniques, read more..

  • Page - 918

    888 C HAPTER 25 • EMBEDDED SYSTEMS PROGRAMMING 25. 1 Embedded s yste ms 25.5 Bits, bytes, a nd wo rd s 25.2 Bas ic co nce pts 25.2.1 Predictability 25.2.2 Id eals 25.2.3 living with failure 25.3 Mem o ry ma nage me nt 25.3.1 Free·sto re pro blems 25.3.2 Alte rnatives to gene ral free sto re 25.3.3 Pool exampl e 25.3.4 Stack exa mple 25.4 Addresses, po read more..

  • Page - 919

    25. 1 EMBEDDED SY STEMS Kitc/u:I/ a/J/Jlimu:n (such as rice cookers and bread machines) Telephont: slIJitc/leJ (typically consisting of thousands of speciali7.cd computers) Pump (J)1I/rollm (for water pumps and oil pumps, etc.) H'i!klillg robolS: some for usc in light o r dangerous places where a human welder cannot go W/I/d tUTb,iU:J: some capable of generating megawalts of power read more..

  • Page - 920

    890 (HAPTER 25 • EMBEDD ED SYSTEM S PROGRAMMING Note the man at the head of cylinder number 5. TIus is a big engine, the kind of engine that powers the largest ships. If an engine like this fai ls, yo u'll rcad about it on the fronl page of your morning newspaper. On this engine, a cylinder COIl - trol system, consisting of three computers, sits on each read more..

  • Page - 921

    25 2 BASIC CONCEPTS Often, lUll/tis-on mllilllerulllct is iTyeasible {Jr Ut'IJ' ran:: You can take a large ship into a harbor to service the computers every second year or so when other parts of the ship require service and the necessary computer spe- cialists arc available in the right place at the right time. Unscheduled , hands-on maintenance is infeasible (no bugs are read more..

  • Page - 922

    .'2 CHA PTER 25 • EMBED DED SYSTE MS PROGR AMM ING available" ; we must try Ollr best using all available tools and techniques. Fortunately, the range of specification, simulation, testing, and other techniques in a given area can be quite impressive. Here, "extremely im- portant" can mean "failure leads to injury o r ruin." Fillllt tolerance: We must be read more..

  • Page - 923

    25.2 BAS IC CONCEPTS to c10sc a filc cvery day will on most operating systcms not survive for marc than about a momh. A program that fails to deallocate lOO bytes every day will waste morc than 32 K a year - that 's enough to crash a small gadget after a fcw momhs. ~nl C nasty thing about such resource '"leaks" is that thc program will work perfectly read more..

  • Page - 924

    .94 CHAPTER 25 • EMBEDDED SYSTE MS PROGRAMMING OmCUTTfmq: An embedded system typically has to respond to events from the CXlcmaJ world. This lcads to programs where many things happen "at oncc" because they correspond to real events that really happen at once. A program that sim ulta neously deals with several actions is called (oncurreTll or /Jamllel. Unfortunately read more..

  • Page - 925

    25.2 BASI C CON C EPTS all constraints}. As ever, try hard to write the clearest, cleanest, most maintainable code. Don't optim ize until you have to. Performance (in time or space) is oft en es- semial for an embedded system, but trying to squeeze performan ce out of cvery little piece of code is misguided. Also, for many embedded systems the key is t"O be con read more..

  • Page - 926

    .96 CHAPTE R 25 • EMB EDDED SYSTEMS PROGRAMMING heard o f a processor that misbehaved only when the tempc raUl re exceeded 130°F (54°C). It was never supposed to gel that hot; however, it d id when the system was (unintentionally and occasionally) covered up on the factory floor, never in the lab while being tested. Errors that occu r away fro m the lab arc read more..

  • Page - 927

    25. 3 MEMORY MANAG EME NT correct and efficient), and have some other module responsible for seri- ous errors. A good reliable syS tem is modular and multi-level. At each level, serious errors arc reponed to a module at the next level - in the end, maybe to a person. A module that has been notified of a serious error (a ile that another module couldn't handle read more..

  • Page - 928

    898 CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMM ING Stack memory can be a problem because it is possible LO usc too much of it, but this is not hard to take care of. "111C designers of a system m ust dCtenllinc tha l for no execution of the program will the stack grow over an acceptable limit. TIUs usually means that the maximum nesting of function calls must read more..

  • Page - 929

    25 . 3 MEMORY MAN AGEMEN T delete p; Node- n2 = new Node (arg3,arg4); 1/ . .. Ench time around the loop we creme twO Nodes, nnd in the process o f doing so we create a Message and delete it again. Such code would not be unusual as pan of building a data structure based on input from some "device." Looking at this code, we might expect to read more..

  • Page - 930

    ( HAPTE R 2S • EMBEDDED SYSTEMS PROGRAMM ING increases the time needed to execllle new as it has to search through lots of ob- jects and fragments for a suitably sized chunk of memory. Clearly this is not the kind of behavior we can accept for an embedded system. This can also be a seri- ous problem in naively designed nOIl'Cmhedded systems. Why can't "the read more..

  • Page - 931

    2 5.3 MEMORY MANAGEMENT proach is to avoid fragmemation in the firs t place. In the example he.re, we could simply have allocatcd bOlh Nodes before allocating the message: while( . . . ) ( Node· nl = new Node ; Node· n2 = new Node; Message" p = geUnpul (dev); II . .. store ini()(mation in nodes ... delete p; II . However, rearranging code to avoid read more..

  • Page - 932

    902 CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMMING 111crc arc twO da ta structures that arc particularly useful for predictable memory al locatio n : Slacks: A stack is a data Slnl ClurC where you can allocate an arbitrary amount o f memory (up to a given maxi mum size) and d eallocate the last allocation (only); that is. a stack can grow and shrink only at the top. read more..

  • Page - 933

    25. 3 MEMORY MANAGEMENT private: /I space for TINI and data to keep track of which Ts are allocated /I and which are not (e.g .• a list of free objects) ) ; Each Pool object has a type of elements and a maximum number of objects. We can use a Pool like this: PookSmall_buffer, 10> sb_ pool i PookSlal us j nd icator,200> i nd kalor _pool; Small_buffer* p = read more..

  • Page - 934

    C H APTER 25 • EMBEDDED 5YSTEMS PROGRAMM ING templale<class T , int N> class S tack { II . /I stack ofTs }; However, IllOSt systems have a need ror allocation or objects o r varying sizes. A stack c.·m do that whereas a pool cannot, so we'll show how to define a stack rrom which we allocate "raw" memory or varying sizes rather than ftxed -sized read more..

  • Page - 935

    2 5. 4 ADDRESSES . POINTERS , AND ARRAYS 25.4 Addresses, pointers, and arrays Predictability is a need or some embedded systems; reliability is a concern o r all. 11lis leads to attempts to avoid language reatures and programming techniques that have proved error-pro ne (in the context or embedded systems programming, ir not necessarily everywhere). Careless usc or pointers is read more..

  • Page - 936

    CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMMING if any. 111is is a cause or many subtle and hard-to-fLX bugs. Here, we examine ex· amples of those array/pointer problems and present an alternati ve. We stall with an example or a very poor (but unrorlunately not ran::) imerrace and proceed to improve it. Consider : vo id poor(S hape p, inl sz) /I poor interlace design { read more..

  • Page - 937

    25.4 ADDRE SSES, POINTER S, AND ARRAY S 2. Use ofa "magic constant" (here, correct): poor(sl ,10). Also, wrong ele- ment type. 3. Usc of a "magic con stant" (here, incorrect): poor(s2,20). 4. Correct (easily verified): first call poor(pl ,l ). 5. Passing a null pointer: second C .. 1.11 poor(pl ,l ). 6. May be COITect: poor(q,maJt:). We can't be sure read more..

  • Page - 938

    908 C HAPTER 25 • EMBEDDED SYSTEMS PR OG RAMMI NG &p[O[ &p[l] &p[2[ >·.· ... . :;l-1-.... ;;}.·.·.··.· .. ·; 1St Ci rcl e 2nd Ci rcle 3rd Circle 11mt is, paorO is calling drawO with a pointer into the middle of the Circle s! ll1is is likely to lead to immediate disaster (crash). TIle call poor(sl,10) is sneakier. It relies o n a "magic con read more..

  • Page - 939

    25.4 ADDRES SES, POINTERS , AN D ARR AYS funct ion declaration - is exactly the kind of code we should worry about. We need a safer way of passing in formation about collections of data without causing other significant pmblems. So, we don't want to pass a built-in array to a fun ction as a pointer plus a size. What do we do instead? TIle simplest solution is read more..

  • Page - 940

    910 CHAPTER 2S • EMBEDDED SYSTEMS PROGRAMMING H ere is one such class: te mpla le<class T > class Array_ref ( publ ic : Array_reHP pp, int s) :p(pp), sz(s) { } T& o p e rato r[ )(int n) { return p [ n]; } consl T& o p erator[ ](inl n) const ( ret u rn p [ n ); } bool assign(Array _ref a) ( if (a.n !=a) re turn false; for (int i=O; read more..

  • Page - 941

    25 .4 ADDRESSES , POINTE RS, AND ARRAYS An Array_ref d oes nm own its elements; it docs no memory management ; it is simply a mechanism fo r accessing and passing a sequence of clements. In that, it differs fro m the sta ndard library array (§20.9). "Ib ease the creation of Array_refs, we su pply a few llseful helper functio ns : templale<c1ass T> read more..

  • Page - 942

    912 C H AP TER 25 • EM B EDDE D SY S TE MS PR OG RAMM IN G Given Array_ref, we can try to rewrite our example: void better(Array_, e kShape> a) { for (int i = 0; i<a.size(); ++i) a [i] .drawO; ) void (Shape· q , veclor<Cirde>& sO) { ) Polygon sl{10]; Shape 52[20J; /I ini tialize Shape· pl = new Rectansle(Point(O,O), Po int(10, 20»; belle read more..

  • Page - 943

    25 .4 ADDRES SES, POINTERS , AND ARRAYS can't. In § 19.3.3 ,md §25.4.2, we saw that the type system has very good reasons for refusing to accept a vector<Circle> as a vector<Shape>. For the same reason, it refuses to accept an Array_rekCi rcle> as an Array_rekSha pe>. If you have a problem re membeling why, it might be a good idea to re read §19.3.3, read more..

  • Page - 944

    914 CHAPTER 25 • EM8EDDED SYSTEM S PROGRAMMING We seem to have strayed into expert territory. In facl, this problem is gen· uinely tricky a nd is unsolva ble w ith the 10015 supplied so far. H owever, let'S sec what it takes to produces a close-la-perfect altcmative 10 our dysfunctional - but all too popular - imcrface style (pointer plus clement count ; sec read more..

  • Page - 945

    2 5 .<1 ADDRESSES , POINTERS , AND ARRAYS /I cast Array_ref: re turn Array _rekco nst Q>(reinte rpreCcast<Q->(P),SZ) i ) /I as before ); This is headache-inducing, but basically: ~nl e o per:nor casts to Array _,ekcost Q > for every type Q provided we can cast an clement o f Array_rckY> LO an clement of Array_rekQ> (we don't use the resul t of read more..

  • Page - 946

    9" C HAPTER 25 • EMBEDDED SYSTEMS PR OG RAMM ING there is no solution for arrays (with morc than onc element) that doesn't involve creating a container of pointers to objects. In conclusion, we can creale simple, safe , easy-to-uSc, and efficient interfaces to compensate for the weaknesses of arrays. That was the major aim of this sec- tion. "Every problem is read more..

  • Page - 947

    2 5.5 BIT S, BYTES, AND WORDS bool - I bit, but takes up a whole byte of space char - 8 bits short - 16 bits int - typically 32 bits, but many embedded systems have l6-bit inls long int - 32 bits or 64 bits 111e sizes quoted are typical, but d ifferent implementations Illay have different sizes, so if you need to know, test. In addi tion, the standard read more..

  • Page - 948

    .,. C HAPTER 25 • EMBED DED SYS TEM S PR OG RAMMIN G You might find the inclusion of "exclusive or" (" , sometimes called "xor") as a fundamental operation odd. However, that's the essential operation in much graphics and encryption code. The compiler won 't confuse a bitwise logical « for an output operator, but yo u might. To avoid confusion read more..

  • Page - 949

    25.5 BITS, BYTE S, AND WO RD S So, using unsigned (§25.5.3) ( 0 keep things as simple as possiblc, we can \vOtc unsigned cha r a = Oxaa ; unsigned char xO = -a; /I complement of a .: 11 I 0 l' I 0 l' I 0 l' I 0 lOx •• -.: I 0 11 I 0 11 I 0 11 I 0 11 I Ox55 unsigned cha r b = OxOf; unsigned c ha r xl = a&b; /I a and b .: read more..

  • Page - 950

    92. CHAPTER 25 • EMBEDDED SYSTEMS I'ROGRAMM ING We can draw bit patterns like this and it is good to get a feci for bit patterns, but it soon becomes tediolls. Here is a little program that converts integers to their bit rep resentation: int m ai n O { int i; while (ci n»i) cout « d ec « i « "== " ) « h ex « "Ox" « i « read more..

  • Page - 951

    2 5.5 BITS , BYTE S, AND WORDS bilsel<12345> lOIs; H ere lois will be all zeros, and dword_bils will have 112 zeros followed by the 16 bits we explicitly specified. If you try to iniliaJize with a string that has characters different from '0' and '1', a std :: invalid_argument exception is thrown: string s; cin»s ; bitset<12345> my_bit s(s); /I may throw read more..

  • Page - 952

    922 CHAPTER 25 • EMBEDDED SYSTEM S PR OGRAMMING int mainO { } const int max = 10; bitsel<max> b; while (cin»b) { } cout« b« '\n'; for (int i =0; kmax; ++i) cout « b(i]; cout« '\0' ; II reverse order If you need a morc complete picture of bilsels, look them up in your online doc- umentation, a manual, or an expen-level textbook. 25.5.3 Signed a nd read more..

  • Page - 953

    25.5 BIT S, BYTES , AND WOR DS So far, we have j ust used signed integers (e.g., int). A slightly better set of rules would be: Use signed integers (e.g. , int) for numbers. Use unsigned integers (e.g., unsign ed int) for sets orbits. 111at'S not a bad rule of thumb, but it's hard to stick to because some people pre- fer unsigned integers for some fomlS of read more..

  • Page - 954

    924 (HAPTE R 25 • EMBEDDED SYSTEM S PRO G RAMMI NG TRY THIS TIle following example may look innocent, but it is an infinite loop : vo id infinileO { unsig ne d cha r max = 160; II very la rge fo r (sig ned char i=O; k max; ++i) coul « inl(i)« '\n '; ) Run it and explain why. Basically, there are tWO reasons fo r using unsign ed intege rs as read more..

  • Page - 955

    2 5.5 BIT S, BYTES . AND WORD S What happens ir an integer overflows? Consider : Inl i= O; while (H i) prinl (i); /I prinl i as an integer followed by a space What sequence or values will be printed ? Obviously, this depends on the dcfini· tiOIl or Inl (no, ro r once, the use o r the capital J isn't a typo). For an integer type with a limited number read more..

  • Page - 956

    926 CHAPTER 25 • EMBEDDED SYS TE MS PROGRAMM ING An aside: Why did we int rod uce tha t prinlO function? We could try: cout « i «"i H o wever, if i was a c ha r, we would the n output it as a character ra ther as an iIu e- geT value. So, to trea t all iIllcger types unifo rml y, we defined templa le<class T > v o id print(T i) {coul read more..

  • Page - 957

    25.5 BI TS, BYTE S, AND WORD S For example, consider how to extract (low-level) information from an integer (maybc because we wanted to transmit it as bytes, the way binary 110 docs): void f(short val) { II assume 16-bit, 2-byte short integer unsigned char left = val&Oxff; unsigned char right = (val>>8)&Oxff; 1/ . .. II leftmost (least significant) byte II read more..

  • Page - 958

    9,. C HAPTER 25 • EMBEDDED SYSTEMS I'ROG RAMMING if (x& o uCoCcolo r) { 1/ .. . } We can still usc & to mas k : /I is out_oCeolor sct? (yes, it is) unsigned char y = x &(out_oCcol or I o uC oC black)i 1/ x becomes 24 Now y has a copy of the biLS from x's positions 4 a nd 3 (oul_oCcolo r and ouc oC black). It is very common to usc read more..

  • Page - 959

    25.5 BITS , BYTES , AND WORDS struct PPN { II R6000 Physical Page Number unsigned int PFN : 22 ; II Page Frame Number int : 3 ; II unused unsigned int CCA : 3; II Cache Coherency Algorilhm boof nonreachabfe : 1 ; bool dirty : 1 ; bool valid : 1 ; bool global : 1 ; }; We had to read the manual to sec that PFN and CCA should be interpreted as read more..

  • Page - 960

    930 CHAPTE R 25 • EMBEDDED SYSTEM S PROG RAMMIN G "111C "acronym soup" (CCA, PPN , PFN) is typical of code at this level and makes little sense Ollt of contcxl. 25.5.6 An exa mple: simple enc rypti on As an example of manipulation of data at the level of the data's re presentation as bits and bytes, let us consider a simple encryption algorithm : read more..

  • Page - 961

    25.5 BIT S, BYTE S, AN D WO RD S ) while(n-- > 0 ) { ) y+= (z« 4 A z»5) + z A sum + k(sum&3Ji sum += de lta ; z+= (y«4 A y»5) + y A sum + k[sum» 11 &3]; w[OI=Yi w(1 1=zi NolC how all data is unsigned so that we can perform bitwise operations on it without fear of surprises caused by spceialtreatmem related to negative num bers. Shifts «< read more..

  • Page - 962

    932 CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMMING We ca.1l usc TEA like this to produce a file to be scm over an unsafe connection: int mainO ( II sender ) consl int nchar = 2*sizeof(long )i consl int kchar = rnc ha ri si rin g op; string key; siring infilc; siring outfile; 1/ 64 bits 1/ 128 bits cout« "please enter input file name, output file name, and key read more..

  • Page - 963

    25.5 BITS , BYTE S, AND WORDS 933 111e essemial piece of code is the while loop; the rest is JUSt support. ~nle while loop reads characters into the input buffer, inbu f, and every time it has eight characters as needed by TEA it passes them to enciphe rO. TEA doesn' t care about characters; in fact , it has no idea what it is enciphering. For example, you read more..

  • Page - 964

    .34 CHAPTE R 25 • EMBEDDED SYSTEMS PR OG RAMMI NG fa168da2 60bcl0ge 7102ce40 9fed3aOb 4424SeSd f612ed4c b5c16lf8 97££2£00 Idbf5674 45965600 b04cOafa b537&7 70 9&b9bee7 16245160 Od3e556b 6de6eda7 d159blOe 7ldScla6 b8bb87de 316aO£c9 62cOla3d 0 ... 24a51£ 86365842 52dabf4d 372&018b 9a5df281 35c9f8d7 07c8(9):)4 36b6d9aS aOBae934 23gefb&5 5fe3fa6f 659dfSOS faf4c378 4c2048d6 read more..

  • Page - 965

    2 5 .6 COD ING STA NDARDS Is TEA an example of embedded system s programming? Not specifically, but you can imagine it being used wherever privacy is needed or financi al trans- actions are conducted - that could include many "gadgets." Anyway, TEA demonstrates many of the characteristics of good embedded systems code: it is based on a well-undersLOod (mathematical) read more..

  • Page - 966

    936 ( H APTER 25 • EMBEDDED SYSTEMS PROGRAMMING Unnu,ewuy fl(J.l'Ut.liQfIS ill prQgramming style, causing code pcrfonning similar tasks to look different and confuse maintaincrs JnappropriaJe programming language, leading to usc of language [eatures that aTC poorly adapted to a particular applic. ... tion area or to a particular group o f progranuncrs blJl!!ficil!7l/ library use, read more..

  • Page - 967

    25.6 COD ING STANDA RD S A good coding standard is prescriptive as well as restrictivc. Recommending some "found ation " library facilities is often the most dfective use of prescriptive rules. A coding standard is a set of rules for what code should look like, Typically specifying naming and indentation rules; e.g., "Usc 'Stroustrujl layollt.'" Typically specifying read more..

  • Page - 968

    938 CHAPTER 25 • EMB EDDED SYSTEMS PR OGRAMMING set o f rules here. Furthcnnorc, every good coding standard is designed for a par- ticular applicatio n area and for a particular set of programmers. So, we don't make any prete nses of uni versality. ~nlC rules arc numbered and contain a (brief) rationale. Many rules contain examples for eas ier comprehension. We distingu read more..

  • Page - 969

    25. 6 CO D IN G STA NDA RD S R102: All code shall conform to ISO/ lEG 14882:2003(E) standard G++. Reason: Language extensions or variations from ISO/ lEG 14882 are likely to be less stable, to be less well specified , and to limit pormbility. Preprocessor niles R200: No macros shall be used except for source COIltTOJ using #ifdef and #ifndef. Reason: Macros don 't read more..

  • Page - 970

    940 (HA I'TER 25 • EMBEDDED SYSTEMS PR OGRAMM ING £WIIII/,/e: if (p <q ) cout « · Pi /I OK R302: Identifie rs should be given descri ptive names. Identifiers may contai n common a bbreviations and acronyms. When Llsed conventionally, x, y, i, j, etc. a rc descriptive. Use the numbe r_oCelc me nts style rather than the numbe rO fIl eme nls style. Hungarian read more..

  • Page - 971

    2S. 6 C O DIN G STA N DARDS E.ample: in t var = 9; { int var = 7; ++var;} /1 violation : var hides var Rell.JoII: Readability. R401: Declarations shall be declared in the smallest possible scope. Reason: Keeping initialization and use close minimizes chances of confusion; letting a variable go out of scope releases its resources. R402: Variables shaH be initialized. read more..

  • Page - 972

    942 CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMM ING RS02: If a class has a virtual function it must have a virtual destructor. Reason: A class has a virtual functio n so tha t it can be used through a base class interface. A fu nction tha t knows an object only thro ugh that base class may delete it and dCI;vcd classes need a chance to clean up (in their read more..

  • Page - 973

    2S.6 CO DING STANDARDS R ,YU(J1I: confusion about precedence has been repeatedly found in code writ- ten by programmers with a weak C/C++ background. We left ga ps in the numbering so that we could add new 11.l1es without ch,mglng the numbering o f existing ones and still have the general classific..1.tion recognized through the numbering_ It is very common for ntles to read more..

  • Page - 974

    944 CHAPTER 25 • EMBEDDED SYSTEMS PROGRAMM ING ~ Drill I. RUll lhis: int v = 1 ; for (int i = OJ i<sizeof(v)·S; ++i) { cout« v « I '; v «=1; } 2. Run mal again with v declared to be a n uns igned int. 3. Using hcxadccilllallitcrals, define short unsigned ints: a. With every bit set h. 111e lowest (least signifi cant bit) set c. ~nle highest read more..

  • Page - 975

    CHAPTER 25 REVIEW 17. What is the potential problem ,.vlth sid :: ve ctor in the context of embed- ded systems? IS. What is the potential problem with exceptions in the context of e mbed- ded systems? 19. What is a recursive function call? Why do some embedded systcms pro- granullers avoid them? What do they use instead? 20. What is memo ry fra gm entatio n? 2 1. read more..

  • Page - 976

    946 C HAPTER 25 • EMBEDDED SYSTEM S PROGRAMMING 54. What is encryption (cncipheri.ng)? Why do we lise it? 55. Can you encrypt a photo? 56. Whal does TEA stand for? 57. H ow do you write a number to ampuL in hexadecimal notation? 58. Whal is the purpose o f coding standards? List reasons fo r having them. 59. Why can't we have a universal coding standard? 60. read more..

  • Page - 977

    CHAPTER 2 5 POSTSCRIPT 9. WIthout using any standard headers (such as <limits» or documenta- tion, compute the number of bits in an inl and detenlline whether char is signed or unsigned on your implementation. 10. Look at the bitfield example from §25.5.5. Write an example that initial- izes a PPN, then reads and prim each field value, then changes each field value read more..

  • Page - 978

    read more..

  • Page - 979

    'cL . ,.-: 26 Testing "I have only proven the code correct, not tested it." -Donald Knuth T his chapter covers testing and design for correctness. ~lncse are huge topics, so we can only scra tch lheir surfaces. T he emphasis is on giving some practical ideas an d techniques for leS l - ing units, such as functions and classes, of a program. We discuss th e read more..

  • Page - 980

    950 26.1 What we want 26.1.1 Caveat 26.2 Proofs 26.3 Testing 26.3.1 Reg ressio n tesls 26.3.2 Unit tes ts 26.3.3 Algorithms and non .algo rithm s 26.3.4 System tests 26.3.5 Test ing classes 26.3.6 Finding assumptions thai d o not hold 26.1 What we want C HAPTER 2 6 • TE STING 26.4 Design for testing 26.5 De bugging 26.6 Performance 26.6.1 Timin g 26.7 References read more..

  • Page - 981

    2 6 . 1 W H AT WE WANT 11mt was a trivially simple piece of code. h implemcntcd a very regular and well-known algorithm. Your compiler is on the OIuer of 200K lines of code, your operating systeIll is 10M to 50M lines of code, and the safety-critical code in the airplane you'll fl y on for your next vacation or conference is SOOK to 2M lines of cod e. read more..

  • Page - 982

    952 CHAPTER 26 • TESTING 26.2 Proofs Wait a minute! Why don', we just prove lhat our programs arc correct, rather than fussing arollnd with tests? As Edsgcr Oijkst:r.l succinctly pointed out, "Tcst- ing can reveal ,he presence o f errors, not their absence." "n tis leads to an obviolls desire 10 prove programs correct "much as mathematicians prove read more..

  • Page - 983

    26 .3 TE STING not make a big deaJ of this distinction ; by all means read the implementation of what you lest. But remember that somcone might later come and rewrite I.hat im· plementation, so try not to depend on anything that is not guaranteed in the in- terfa ce. Ll fact , when testing anything, ule basic idea is to throw anything we C<"111 at its read more..

  • Page - 984

    954 C HAPTER 2 6 • TESTING 26.3.2 Unit tests OK. Enough words for now! Let's try a concrete example: let's teSI a binary scarcll. Here is the specification fro m the ISO standard (§25.3.3.4): template<class Forwardlterator, class T > boo] binary_search(Forwardlterator fint , FOIWardlterator last. const T& value); template<class ForwardIterator, class T , class Compare> bool read more..

  • Page - 985

    2().3 TESTING Tcst ror likely mistakes (find the most errors). Test ror bad mistakes (find the enut"s wit h the worst potential consequenccs). By "bad," we mean errors that would have the direst consequences. In general, that's a ruzzy notion, but it C,1n be made precise ror a specific program. Fo r exam' pic, ror a binary search considered in isolation, all read more..

  • Page - 986

    , .. (HAPTER 2 6 • TESTING when considering sequences (of any sort), we always look for the beginning and the end. In particular, the empty sequence should always be tested. So, le t'S con- sider a few arrays o f integers that are properl y ordered as required: {1 ,2,3,5,8,13,21 } () {O { 1,2,J,4 } ( 1,2,3,4,5 ) ( 1, 1, 1,1 , 1, 1, 1 ) ( 0,1, 1,1 ,1, read more..

  • Page - 987

    2 6 . 3 TE STI NG In general, we look for Extreme cases Qarge, small, strange dislribmions of input, etc.) BoundaJ)' conditions (anything ncar a limit) Wh:H that really means, depends on the particular program we arc testing. 26.3.2.2 A simple test harness We have two categories of tests: tests that should succeed (e.g., searching for a value that's in a sequence) a nd read more..

  • Page - 988

    9sa C H A PTER 2 6 • TE ST ING Befo re going furth er, note anolher example o f (semi-systematic) tcsting tech- niquc: we tested with correct values, choosing some from the ends of the se- quence and some frolll "the middle,'" For lhis sequence we could have tried all values, but typic illy that's not a realistic option. For the failing val ues, we read more..

  • Page - 989

    2 6 . 3 TE STING if (r !=t.res) { cout « "failure: test "« t.label «" binary _sea rch : " « t.seq .sizeO«" elements, val== "« t.va! «" ->"« t.res« '\11 '; ++error_count ; return error_count; } int mainO { int errors = lescallOi cout « "number of errors : "« errors« "\n"; } Here is some test input using read more..

  • Page - 990

    C HAPTER 26 • TESTING loops, etc.). However, that's also what we did whe n we tried to write and debug the code. So, we might repeat a logical mistake from the design whe n we design the tests a nd completely miss a problem. This is one reason it is a good idea to have someone differe nt from the developer(s) involved with designing the tests . We have read more..

  • Page - 991

    26.] TES TI NG randj nt(SOO), 0, ra ndj nt(SO»j /I number of clemen!s /I base 1/ spread Generated tests based on random numbers are particularly useful when we need to test the cumulative effects of many operations where the result of an opera tion depends on how earlier operations were handled , that is, when a system has state ; see §5.2 . 111e reason LhaL read more..

  • Page - 992

    %, C HAPTER 26 • TE STING !USOIITCeS: Its use of resources (time, memory, liles, CIC .) arc not specified quite as well as we would like. By "explicit or implicit" we mean that we have to look nOljust 31 the fo rmal pa- rameter and the return value, bUl also on any effects all global variables, ioslreams, files, frcc-store memory allocation, etc. So, what read more..

  • Page - 993

    26 .] TESTING To test do_ dependentO. we can't just synthesize sets of argumen ts and see what it docs with them. We have to take into account that it uses the global variables cin. cout, and vee . -l1mt's pretty obvious in this little nonsense function, but in real code this may be hidden in a larger amou nt o f code. Fortunately, there is soft ware that can read more..

  • Page - 994

    964 26.3.3.2 Resource management Consider this nonsense function: C H A PTER 26 • TESTING void d o_resourcesl(int a, int b, const char · s) /I messy func tion /I undisciplined resource use } FILE " f = [ope n (s, "r "); int O p = new inlla1; if (b<=O) throw B ad _argO; int O q = new intlb); d ele te[l Pi /I open file (C sty le) II read more..

  • Page - 995

    26.3 TE STI NG as an argument), and sometimes we pass resources Oul of a function (e.g., as a return value). It can be quite hard to detcnnine what is right about SUdl cases. Consider: FILP do_resources3(int a, int · p, const char· s) /I undisciplined resource passing { } f llP f = fo pe n(s, "r") ; delete p; delete var; var = new int[27] ; return read more..

  • Page - 996

    ... CHAPTE R 26 • TESTING There arc three obvious errors. (What are they?) In addition, a good tester will immediately spot the opportunity for an overflow whe re we arc adding to sum : Many loops involve data and might calise some sort of overfl ow when they arc given large inputs. A fatu ous and particularly nasly loop error, the burTer overflow, ralls into the read more..

  • Page - 997

    26 .] TE STING Consider this nonsense function: void do_b ranchl(int x, int y) II messy func tion II undisciplined use of if { ) if (x<O) { if (y<O) cout« "very negative\n"; else cout« "somewhat negative\n"; else if (x>O) { if (y<O) cout « "very positive\n"; else co ut « "somewhat positive\n "; ) rn le most obvious en or read more..

  • Page - 998

    ... CHAPTER 26 • TESTING D ealing with switch-statements is fu ndamcntaH y similar to dealing with ii- statements . void do _bra nc hl (inl x, int y) /I messy func tion 1/ undisciplined use of switch { } if (y<O && y<=3) switch (xl { case 1 : coul « "one\n "; b reak; case 2: cout « "two\n"; case 3: co ut « "three\ read more..

  • Page - 999

    2 6 . 3 TE STI N G 26.3.4 System tests Testing any significant system is a skilled job. For example, the testing or the COIll - puters that control telephone systems takes place in specially constructed rooms with racks rull or computers simulating thc traffic or tens or thousands o r people. Such systems cost millions and are the work o r teams o r very skilled read more..

  • Page - 1000

    .7. C H APTER 2 6 • TESTING whole bunch of pigeons to peck at the screen at random (they work for bird feed! ). H iring large numbers of "ordinary novice users" and seeing where the y "peck" is indeed not uncommon and also necessary, but it is not a systematic strategy. Any rcaJ solution has to involve some repeatable sequence of tcsts. 111i5 read more..

  • Page - 1001

    26.3 TE STING Test output Script ~/ Text 110 ~ "Main program" Intcrestingly, this also allows us to sem.i-systematica.lly test the GUI : we can run scripts using the text 110 and watch the effect on the CU I (assuming that we send the output frOill th e main program to the CU I as well as lhe text-lIO inler- face). More radically, we might bypass the read more..

  • Page - 1002

    972 C HAPTER 26 • TES TING This is also an example of the "design for testing" that we have alluded to: some programs arc far easier to test than others, and if we think about testing from the very onset of OUf design, we can build systems that arc beuer organized and eas- ier to test (§26.2), B etter organized? Consider: User I Program with CUI This read more..

  • Page - 1003

    26 .3 TESTING We have seen an example o r this: the graphical interrace classes in Chapters 13- 16 provided an example. 111ey isolate a "main program" (that is, the code you wrote) from the "ofT·the-sheW' CU I system: FLTK, Windows, Linux's CU I, whatever. With this design we can usc any 110 system. Is this importam? We think it is immensely so. First, read more..

  • Page - 1004

    974 CHAPTER 26 • TEST IN G so that we have to consider it in several contexts (as defined by d ifferent derived classes). Consider the Shape class from §14.2: class Shape ( /I deals with color and style, and holds sequence of lines public: void drawO canst; /I deal with color and draw lines virtual void move(int dx, int dy); void seccolor(Color col); Color colorO read more..

  • Page - 1005

    2 6. 3 TE STIN G Shape has virtual functions ; that is, the behavior of a Shape depends on what (if any) class has been derived from it. Shape is not an algOl;thm. A change to a Shape can bave an effect on t.he screen. 111e last point is really nasty. This basically means that we have to have a human sit and watch to see if a Shape behaves as intended. read more..

  • Page - 1006

    976 C HAPTER 26 • TESTING for (int i=O; i<10; + +i ) { In .move(i-5,i-5); In .draw O; II see jf it moves back to where it started if (po int(O)!= Point(10, 10)) cerr« "wrong poi nt 1 a ft e r move"; if (point(l )!= Po int(l00, l00» ce rr« "wro n g p o int 2 aft e r m ove "; fo r (int i = 0 ; i<100; ++i ) { /I read more..

  • Page - 1007

    26 .3 TESTING someone must either check before each call or as part of the implementation of each c,111 (see §5.5). H owever, if we are testing our own code, we can insert such tcsts. If we arc testers and the people who write the code will listen to us (that's 1I0t always the case), we can teU them about the unchecked requirements and have them ensure that they read more..

  • Page - 1008

    978 ( HAPTER 26 • TESTING te mplate<dass Ite r, class T> 1/ warning: contains p~udo code bool bina ry_search (Ite r first, Ite r last, const T& va lue ) ( ) if (Iesl e na ble d ) { ) if (Ite r is a ra ndom acce ss ite rato r) ( II check if [fi rst last) is a sequence: if (lasl d irst) thro w Bad_scquence() i /I check if the sequence is read more..

  • Page - 1009

    26 . 6 PERFORMAN C E Embed tests of unchecked assumptions (assertions) in the calling code to catdl bad aJ'guments before system testing. Minimize dependencies and keep dependencies explicil. Have a dear resource management strategy. Philosophically, this could be scen as enabling unit-testing techniques for sub- systems and complete systems. If perform ance didn't malter, we could read more..

  • Page - 1010

    980 C HAPTER 2 6 • TE STI NG enable better diagnostics for errors occurring after dcploymem (this can happen to even the best code when it has to coexist with code de veloped "elsewhere") . Consequently, the answer to the "Is it efficient enough?" question is : "Mea' sure how long interesting lest cases take." To do that, you obviously have read more..

  • Page - 1011

    26 .6 PER FO RMAN CE If you think this example was bad, cons ider what would have happened if the row_s um O had had to access a database to get its data. R('ading from disk is many thousands of times slower lhan reading from main memory. Now, you may complain: ;';Nobody would write something that stupid !" Sorry, but we have seen much worse, and usually a read more..

  • Page - 1012

    982 C HAPTER 26 • TESTING and can give it to yOll. For example, on a Unix system, sim ply prcGxing a com- mand with time will make the system print out the time taken. You might usc time to figure out how long it takes to compile a C++ SOUfce fi le x.cpp. Nor- mally, you compile it like this: g++ x.cpp ·10 get that compila tion timed, you juSt add time read more..

  • Page - 1013

    26 . 7 REFERENCES ) co ut « "do_somethingO " « n « " times took " « do uble(t1- I1 )/CLOCKS_PER_SEC« " seconds" « n (measurement granularity : " «C lOCKS_PER_SEC« " of a second)\n "; The clockO function retums a result of type clock_I. TIle explicit conversion double(t2-t1 ) before dividing is necessary because clock_I might be an read more..

  • Page - 1014

    984 CHA PTER 26 • TESTING ".; Drill Get the lcst of binary_search to run : 1. Implement the input operator fo r Test from §26.3.2.2. 2. Complete a ftl c OftCSls for the sequences from §26.3: a. {1 ,2,3,5,8, 13,2l} /I an "ordinary sequence ~ b. {) c. {1 } d. {1 ,2,3,4 } /I even number of elements c. {1 ,2,3,4,5} /I odd number of elements f. {1 , read more..

  • Page - 1015

    C HAPTE R 26 EXERC I SES 15. What makes testi ng a class harder than testing a function? 16. W hy is it impom mt lhal tests be repeatable? 17. W hm can a tester do when finding ma t a " unit" relies o n unchecked as~ sumptions (pre-conditions)? 18. What can a designer/implementer do to improve testing? 19. H ow docs testing differ from deb ugging? read more..

  • Page - 1016

    ... CHAPTER 26 • TES TI NG 9. Add a text-based output format for the graphics interface library. For exam ple, w hen a call Circle( Poinl(O,1), 15) is executed, a string like Cird e( Point(O,1), 15) should be prod uced on an autpUl stream. 10. Usc the tcxt-based interface from exercise 9 to write a better test for t.he graphical interface library. 11 . Time the read more..

  • Page - 1017

    1. . 1"27 The C Programming Language "C is a strongly typed , weakly checked, programming language." -Dennis Ritchie T his chapter is a bl;ef overview of the C progranuning lan- guage and iLS standard library from the point of view of someone who knows C++. It lists the C++ features missing from C and gives examples of how a C programmer can cope withollt read more..

  • Page - 1018

    988 C HAI'TE R 27 " THE C PROGRAMMING LANGUAGE 27.1 C and c++: s iblings 27.4 Free store 27.1.1 CJC++ compatibility 27.1.2 C++ fea tures missin g from C 27.1.3 The C standard library 27.2 Functions 27.2.1 No function name overloading 27.2.2 Function argument type checking 27.2.3 Function definitions 27.2.4 Calling C from C++ and c++ from C 27.2.5 Pointe rs to read more..

  • Page - 1019

    2 7. 1 C AND C++; SIBLING S 1967 ~~u!y , , , , , , , , , 1978 1980 1985 • 1989 1998 , , , , , , , , , , , , , , C with C lasses EadyC++ '11e version orc that is used almost exclusively today is C89 (as described in the second edition or K&R), and that's what we are describing here. '11ere is still some Classic C in usc and a rew read more..

  • Page - 1020

    ( HAPTER 27 " T HE ( PROGRAMMING LANGUAGE Both languages arc now defined/controlled by ISO standards committees. For each, many supported implementations arc in usc. Often, an implementation supports both languages with the desi red language chosen by a compiler switch or a source file suffix. Both afe available on more platforms than any other Ian· guage. Both were read more..

  • Page - 1021

    27. 1 C AND C ++: SIBLING S -nlc typc or a character literal, sllch as 'a' , is int in C and char in C++. However, ror a char variable ch \ .... e have sizcof(ch)==l in both languages. Inrormation related to compatibility and language differences is nOl exactly exciting. -m ere arc no new neat programming techniques to leill·n. You might like printfO (§27.6), read more..

  • Page - 1022

    992 CHAPTER 27 • THE C PROGRAMMING LANGUAGE D erived classes and virtual functions Usc structs, global fUllctions, and pointers to functions (§27.2.3). Te mplates and inlinc function s Usc macros (§27.8). Exceptions Usc error codes, error re turn values, etc. Function overloading Give each function a distinct name. new/delete Usc ma liocO/freeO a nd separate initialization/cleanup read more..

  • Page - 1023

    27 . 1 C AN D C++: SIBLING S The rest o f this chapter explains how to write useful programs without those features. Our basic advice fo r using Cis: Emulate the programming techniques that the C++ features wcrc dc- signed to suppOrt with the facilitics provided by C. When writing C , write in thc C subset of C++. Use eompiler waming levels that ensurc fun ctio read more..

  • Page - 1024

    C HAPTER 27 • THE C PR OGRAMMING LANG U AGE For these, there are often C libraries based on arrays, poimers, and functions to help compensa te. The main pans of the C standard library are <sldlib.h>: general utilities (e.g., maliocO and freeO; see §27.4) <sldio .h> : standard 110; see §27.6 <slring.h> : C ·style string manipulation and memory read more..

  • Page - 1025

    2 7. 2 FU NC TI ONS void prinU nl (int); void prin Cslring(const char ·); ,. print an int . / , . print a string . , 111is is occ.asionally claimed to be a virtue: now you can' t accidelllally usc the wrong fun ction to print an inl! Clearly we don't buy that argumelll , and the lack of overloaded fu nctions docs make generic programming ideas awkward to read more..

  • Page - 1026

    ( HAPTER 27 • THE C PRO GRA MMING LANGUAGE that is rather similar to using a subset of C++. One of the observations that led to the design o f C++ was that the compiler could easily check much (but not all) of what lim checked. You can as k to have fu nction arguments checked in C. You do that simply by declaring a function with its argument types read more..

  • Page - 1027

    27.2 FU N C TI O N S NOle that even though the compiler will allow an argument of the wrong type to be passed , such as a char· to a parameter of type int, the use of such an argument of a wrong type is an error. As Dennis Ritchie said , "C is a strongly typed, weakly checked , progranmling language." 27.2.3 Fun ction definition s You can define read more..

  • Page - 1028

    (HAPTER 2 7 - THE C PROGRAMMING LA NGU AG E I soon regretted that, though, since that looks odd and is completely rcdundant when argument type checking is uniformJy applied. Worse, Dennis Ritchie (the fa - ther of G) and Doug McIlroy (the ultimate arbiter o f tas!'e in the Bell Labs Com- puteI' Science Research Cemer; see §22.2.5) both called it "an abomination. read more..

  • Page - 1029

    27 . 2 FUNC TI ONS checking. 10 call a fu nction defin ed in C from C++ and to have a fUIlClion de- fined in C++ called from C , we need to tell the compiler what we arc doing: II calling C function from C++; exte rn "C" d ouble sqr t(do uble)i II link as a C func tion void my_c_plus_plus_fcIO ( do uble s r = sqrl (2)i Basically extern read more..

  • Page - 1030

    1000 ( H APTE R 27 • THE C PROGRAMMING LANGUAG E The bcnclit of lhis intcropcrabiliry is obvious: code can be written in a mix. of C and C++. In particular, a C++ program can lI SC libraries wri nen in C, and C programs can usc libraries writ ten in C++. Funhcrmorc, most languages (no- tably Fortran) have an interface for calling la/from C. In the exam ples read more..

  • Page - 1031

    27.2 FU N CTIONS struct Shape1 { }; enum Kind ( circle, rectangle} kind ; r ... *' void draw(struct Shape1 * p) { } switch (p- >kind) ( case circle: '* draw as circle *' break; case rectangle : } r draw as rectangle *' break; int f(struct ShapeP pp) ( } draw(pp) ; /* ... *' ~nlis wo rks. There arc two snags, though: For each "pseudo-virtual" read more..

  • Page - 1032

    1002 CHAPTER 27 • THE C PROGRAMMING LANGUAGE void draw(struct Shape2· p ) ( (p->drawHp); ) void rotate(struct Shape2e p, int d) ( (p->rotale)(p,d ) ; ) This Shape2 can be uscd juSl like Shape1 . int f(slruct Shaper pp) ( ) draw(pp); /* . .. 0/ With a little extra work, an object need not hold one pointer to a fu nction for each pseudo-virtual function. Ins read more..

  • Page - 1033

    2 7.3 MINOR LANG U AGE DIFFERENCES Amazingly e nough, thanks to a devious com patibility hack, this also works in C++. H aving a variable (or a functio n) with the same na me as a slrucl is a fairly COlllmon C idiom, though not one we recom mend. If you dan', wimt to write slruct in front of every stTUCmre nrunc, usc a typeder (§20.5). 1 11e foUowing idiom read more..

  • Page - 1034

    1004 C HAPTER 27 • THE C PROGRAMMING LANGUAGE Don 't usc these names as ide ntifiers in C , or your code will not be porta ble to C++. If you usc one o r thesc names in a header file, that header won't be usefu l from C++. Some C++ kC)"\lord s arc macros in C : c ++ keywo rds that a re C macro s .nd n01 biland 0' bilar bool tru e campi read more..

  • Page - 1035

    2 7.3 M I NOR LANGUAGE DIFFE REN CES ( inl al maxl; ,-... *' ) ) In C++, an uninitialized declaration is a definition ; in C, it is just a declaration so that there can be twO of them: inl X; inl x; I" defines or declares a single integer called x in C; error in C++ *' In C++, an entity must be defin ed exactly once. This gets a bit more read more..

  • Page - 1036

    1006 r in file y.c: 0' #indude "x.h" ( HAPTER 27 • TH E C PRO GRAMM ING LANGUAGE /* the declara tion of x is in the header 0/ Belter still , avoid the global variable. 27.3.4 C·style casts In C (and C++), you can explicitly convert a value v to a type T by this m inimal notation: This " e -Style cast" OJ' "old-style cast" is read more..

  • Page - 1037

    27.3 M I NOR LANGUAGE DIFFERENCE S lllis docs not give the type checking done by reinterpreccast and const_cast, but it docs make these inherently ugly operations visible and the progranuner's intent explicit 27.3.5 Conversion of void · In C, a void· may be used as the righ t-hand operand of an assignment to or ini- tialization of a variable of any poimer type ; in read more..

  • Page - 1038

    1008 CHAPTER 2 7 • THE C PROGRAMMI N G LAN GUAG E Unfortunately, implicit void*'IO-P conversions are common in C and possi· bly the major C/C++ compatibility problem in real code (sec §27.4). 27.3.6 enum In C, you can assign an int to an enum without a cast. For example: e num color { red , blue, green }; int x = g ree n; ' " O K in C and C++ read more..

  • Page - 1039

    2 7.4 FREE STORE 27.4 Free store C does not provide the new and d ele te operaLOrs dealing with objects. To use free SLOre, you use functions dealing wit.h memory. The most important functions arc defined in the "general utilities " standard headcr <stdlib.h>: vo id " malloc(si:z:e_1 S:Z:) i /* allocate sz bytes "' vo id free(vo id O pI; '0 read more..

  • Page - 1040

    1010 CHAPTER 27 • THE C PR OGRAMMING LANGUAGE maliocO. However, it can also remove a visual due that a size was wrongly calculated: p = malloc(s izeof(char)*m); r probably a bug - not room for mints *' Don 't use malloc()'fre eO in C++ programs; new' de lete require no casts, deill with initialization (constructors) and cleanup (destructors), report mcmory allo- cation read more..

  • Page - 1041

    2 7.5 C-STY l E ST RING S Rerer to the pape r "Lcamin g Standa rd C + + as a New Language" (see the refer· ence list in §27. 1) ror a more lhorough d iscussion o r in put and allocation stra tegies. 27.5 C-style strings In C, a string (o rten cru led a C .string or a C-.sI)'k .shillg in C++ litc ra tu re) is a zcro· termina ted a read more..

  • Page - 1042

    101 2 C H A PTER 2 7 • T H E C PR OG RAM M I NG LANG U AGE if (stremp(sl,s2)==O) ( '0 do s 1 and 52 hold the same characlers? 0' ) TIle slremp() function docs a three-way comparison of its two arguments. Given the values of sl and s2 above, slrcmp(sl ,s2) will retum 0, meaning a perfec t match. If sl was lexicographically befo"e s2 it wo uld read more..

  • Page - 1043

    27 .5 C~STYLE ST RI NG S use r name with an address, placing the @ character in between. Using std :string lhis can be done like this: siring s = id + ' @' + add r; Using the standard C -slyle string function we ea.n write t.hat as char· cal(const char· id, const char· addr) { } inl sz = strle n(id )+slrle n(add r)+2; char· res = (char·) m read more..

  • Page - 1044

    1014 C H APTER 27 • THE C PROGR AMMING lA NGUAG E TIle C strchrO has a similar but even harder-to-spot problem. Consider: char" st rchr(const char" s, int C)i r fi nd c in constant s (not C++) ., const char aa[] = "asdf"; char· q = slrchr(aa, 'd')i . q = 'x'; r aa is an array of consta nts "' '" find s 'd ' ., r change 'd' read more..

  • Page - 1045

    27.5 C- STYLE ST RING S Don't usc these functions in C++. In particular, me msetO typically interferes with the gu arantees offered by constructors. 27.5.3 An exampl e: s!repyO 111e defi nition of slrcpyO is both famous and infamous as an example o f the terse style that C (and C++) is capable o f: char· strcpy(char· p, const char· q ) { ) while (* p++ = read more..

  • Page - 1046

    1016 C H APTER 27 • TH E C PROGRAMMING LANGUAGE Such declarations are nOt uncommo n in older code. Instead, usc multiple lines and take advantage of the extra horizontal space for comments and initializers: char c = 'a' ; , - termination characler for input using fO-' char- p = OJ ,- last char read by fO -, char a[177] ; ,- inpul buffer -, char- fO; ,- read more..

  • Page - 1047

    27. 6 INPUT/ OUTPUT: STOIO H ere. %g means '" Print a noating-point number using the general formac ," %s means " Prine a C-style strin g," %d means "Prim an integer using d ecimal digits," and %c mea ns '" Print a character." Each such format specifier picks the next sa- far-unused argu ment, so %g prints d , %s prints s , %d read more..

  • Page - 1048

    1018 CHAPTER 27 • TH E C PROGRAMMING LANG UAGE int getc(FILE* stream)i char* gets(char* S) i 1* get a char from stream *' /* gel characters from sIdin *' The simplest way of reading a string of characters is using getsO. For example: char a[12]i gets(a); ' * read into cha r array poi nted to by a until a '\ n ' is input *' Never do that! Consider gels() read more..

  • Page - 1049

    2 7 .6 I NPUT/ OUTP U T: STOIO problem of what to do if someone docs type more than 19 characters. 11lC~ "exira" characters will be left in the input stream to be "found " by later input operations. 111e problem with scanfO implies that it is oft en prudent and easier to lise gelcharO . lllC typic1.l way of reading charactcrs wilh gelcharO is read more..

  • Page - 1050

    1020 CHA PTER 27 • THE C PROGRAMMING LANGUAGE Consider this: there are no exceptions in C, so how do we make sure that the files are dosed whichever enor ha ppens? 27.7 Constants and macros In C, a eonsl is never a compile-time constant: co nsl int max = 30; consl int x; ' " canst nol initialized: O K in C (error in C++) · , void f(i nt v) { read more..

  • Page - 1051

    27.8 MACROS void f(int v) ( ) int alf MAX); switc h (v) ( case 1: , .. ... .. , brea k; case MAX : ) ,,, ... '" break; /' OK . , ~111e name of the macro M AX is replaced by the characters 30, which is the value of the macro; that is , the number of elements o f al is 30 and the value in the sec· ond case label is 30. We usc all read more..

  • Page - 1052

    1022 ( HAPTER 27 • THE C PROGRAMMING LANG U A GE avoid them in C++ programs (especially if you need to write programs that have to be portable to very old compilers or to platforms with unusual constraints). Apologies to people who cons ider the techniques described below "dirty mcks n and believe such arc best not mentioned in polite company. H owever, we read more..

  • Page - 1053

    2 7 .6 MA C RO S template<class T > inline T max(1 a,T b ) ( return a< blb :a; ) the max gets expanded with the arguments T a and T b, and the compiler sees template<class T> inline T «(1 a»=( T b)"f( T a ):( T b» ( return a<b?b:a; ) The compiler error messages are "interesting" and not very helpful. In an emer- gency, yo u can read more..

  • Page - 1054

    1024 (HAPTER 27 • TH E ( PR OG RAMMING LANG U AGE We strongly recommend against this. Mati) people have tried this idea. ·nley (or the people who maintain their code) find that Many people don't share their idea of what is a better syntax. TIle "improved" syntax is nonstandard and surprising; others b'Ct confused. There are uses of the "improved" syntax that read more..

  • Page - 1055

    2 7. 9 AN EXAMPLE: INTRUSIVE CONTAINERS A similar construct, often called an inell/de guard, is commonly used LO prevent a header fi le from being #included twice: r my_wi ndows_hcadcr.h: "' #ifndef MY_WI N DO W S_HEADE R #defin e MY_W IN DOWS _HEA DER '0 here is the header information "' #e ndif 111C #ifndef tcst checks that somcthing is not defincd ; read more..

  • Page - 1056

    1026 CHA PTER 27 - THE C PROG RAMM ING LANGUAGE struCi list { stru ellink · firsl; slru ellink · lasl; ); slru Ci link { / - link for doubly-linked list */ ); shuet link- pre ; struCi link- sue; Here is a graphical representation o f a list: liSI:,.,-,:-__ -, fl"t last link :r-_-''--_-, pre pre sue sue -------------- '-'=-_----.J sue It is nOt our aim read more..

  • Page - 1057

    2 7. 9 AN EXAMP L E: INTRUSIVE CONTAINERS void init(strue! ListO lsI) { /0 initialize 0p to the empty lisl 0/ assert(lsl); Ist->first = I st->Iast = 0 ; We decided not to deal with error handling for bad pointers to lists at nm time. By using assertO, we simply give a (run-time) system error if a list pointer is null. 111e "system eno r" will give the rue read more..

  • Page - 1058

    1028 C H A PTER 27 • THE C PROGRAMM IN G LANGUAGE If we didn't allocate all of Ollf Links on the free store, we had better not call clea rO, or cle ar() will create havoc. 111C deslroyO function is essentially the opposite of createD . that is, a son of combination o f a d cstrucLOr a nd a d e lete : void d eslroy(slrucl Lisl * 151) '* free all read more..

  • Page - 1059

    27.9 AN EXA MPL E: INTRUSIVE CONTA INER S The e raseO function can be written like this: slruct Link · e rase(slru cl Lisl· lSI, slruct Link- p) / , ' / { } remove p from lSI; return a pointer to the link after p asserl (lsl)j if (p==O) return OJ , - OK 10 erase(O) -, if (p == Isl->fir st) { } if (p->suc) { e lse { Isl->firSI = p ->suc; read more..

  • Page - 1060

    1034) C H APTER 27 • T H E C PRO GRAMMING LANG UAG E slruct Nam e { ) ; struct Link Ink; char· p; '* the l ink required by list operations *' ,. the name string *' So fa r, so good, tho ugh h ow we gel to use tha t Link member is a mystery ; b ut since we know tha t a list likes its Links o n the free store, we wr ite a fUll read more..

  • Page - 1061

    CHAPTER 27 RE V I EW 1031 ) curr = names.first; ,- write out all names -, inl count = 0; for (; curr! =O; curr=curr->suc) { co unt++; printf("element %d : %s\n ", cou nt, «struct Name · )curr)->p); ) So we "cheated." We used a cast to lfeat a Name- as a link - . in that way, the user knows about the "library-type" link. However, the read more..

  • Page - 1062

    , 1032 7. 8. 9. 10. II. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 3 1. 32. 33. 34. 35. Terms CHAPTE R 2 7 • THE C PROGRAMM I NG LANGUAGE List a dozen C++ fearures not presenl in C. What organization "owns" C a nd C++? List six C++ standard library components that crumot be used in C. 'Which C standard read more..

  • Page - 1063

    C HAI'TER 27 EXERCISES Exercises For these exercises it may be a good idea to compile all programs with both a C and a C + + compiler. If you lise only a C++ compiler, you may accidentally use non·C f eatures . If YO ll usc only a C compiler, type errors may remain undetected. I . Implement versions of strlenO, strcmp() , and strcpyO. 2. Complete the intnlsive read more..

  • Page - 1064

    1034 CHAPTER 27 • TH E C PROGRAMMING LANGUAGE 15. Simulate single inheritance in C. Let each "base cla ss" contain a pointer to an array o f pointers to functions (to simulate virtual functions as free- standing functions taking a pointer to a "base class " object as their first argument); see §27.2.3. Implement "derivation" by making the "base read more..

  • Page - 1065

    Part V Appendices read more..

  • Page - 1066

    read more..

  • Page - 1067

    el . f'" A Language Summary "Be careful what you wish for ; you might get it." - Traditio nal T his appendix summarizes key language elements or c++. The su mmary is vcry selective and specifically geared lO novices who want to explore a bit beyond the sequence or topics in the book. The aim is conciseness, not completeness. 1037 read more..

  • Page - 1068

    '"'" 14..1 General 14. .1. 1 Terminology 14..1.2 Program sta rt and termination 14..1.3 Comments A.2 Literals 14..2.1 Inleger lite rals 14..2.2 floating-point·lite rals A.2.3 Boole;an liter;llis "'.2.4 Charade r lile ra ls 04.2.5 Siring lit e rals A.2.6 The pointer lite ral A.3 Identifiers A.3.1 k eywords 14..4 Scope, storage class, a nd lifetime 04.4.1 Scope A.4.2 read more..

  • Page - 1069

    A.I GENERAL guage. ~111e defmition of C++ is the ISO C++ sla.ndard, but that document is nei· ther intended fo r nor suitable for novices. Don't forget to usc your online docu- mentation. If you look at this appendix while working o n the early chapters, expect much to be "mysterious," that is, explained in later chapters. For standard library facilities, sec read more..

  • Page - 1070

    '040 APPEND IX A • LANG UAGE SUMMA RY ';thc system." Some systems ignore that value, but succcss fullcrmination is indi- ca.tcd by returning zero and failu re by rClu ming a nonzero value or by an un- caught exception (bUl an unc.1.ught exception is considered poor style), ~nlC arguments to ma in O can be implementation defined, but every imple- mentation must read more..

  • Page - 1071

    A.2 LITERAL S A.2 literals Literals represent valu es of various types . For exam ple, the literal 12 represents the integer value M twelve," "Morning" represents the character string value M om- il/g, and tru e represent the Boolean value fme. A. 2.1 Integer literals /I/ttger Jiterau come in th ree varieties: Decimal: a series of decimal digits Decimal dibrits: read more..

  • Page - 1072

    1042 APP ENDIX A • LAN GU AGE SU MMARY "256+2"16+3 , which is (decimal) 291 . U you have never deah with non-decimal integer representations, we strongly recommend you try converting a few num- bers LO and from decimal and hexadecimal. Note th at a hcxadccimru digit has a VCIY simple correspondence to a binary value : Hexadecimal and binary he> binary read more..

  • Page - 1073

    A2 LITERAL S 123.0 /I double .123 /I double: 0.123 0.123 /I double 1.23eJ II double: 1230.0 1.23e-J II double: 0 .00123 1.23e+J II do uble: 1230.0 l<'oating-po int-litc rals have type double unless a sufiix indicates o the rwise. For example: 1.23 /I double 1.23f /I float 1.2JL II long double A.2 .3 Boolean litera ls rIne literals of lype bool arc true and fal read more..

  • Page - 1074

    1044 APPENDIX A • LANGUAGE SUM MARY A special character is rtprcscmcd as its "C++ name" enclosed in single quotes, for exam ple, '\n ' (newline) and '\1' (tab). The characLCr set includes the following visible characte rs: abcde fghijklmnopqrsluvwxyz ABCDEFGHIJKlMNOPQRSTUVWXYZ 0123456789 !@#S%"'&·(L +I-·u(]: n;'<>7,J In portable code, you C<'l.nn Ot rely on read more..

  • Page - 1075

    A.3 IDENTIF IERS In C++ (but not in C, so beware of C headers), NULL is defined to mean 0 so that you can write int · p4 = NU LL; II (given the right definilion of NU ll) Ihe null pointer In C++Ox. the keyword nullplr will denote the null pointer. For now, we recom- mend just using 0 for the null pointer. A.3 Identifiers An idnltjJier is a sequence of read more..

  • Page - 1076

    '046 APPENDIX A • LANGUAGE SUMMARY Keywords (reserved identifiers) (continued ) of_eq private protected public register reinterpret-cast return shorl signed sizeof static s talic_cast strucl switch template this throw true " Y typedef Iypeid typename union unsigned using virtual void volatile wchar_t while '0' xor_eq A.4 Scope, storage class, and lifetime Every name in C++ (with read more..

  • Page - 1077

    A.4 SCO PE , STORAGE ClASS, AND LIFETIME Class and namcspacc scopes have names, so that we can refer to a member from "elsewhere." For example: void mj /I in global scope names pace N { void ro II in narnespace scope N ( ) int v; /I in local scope :: f() j Il calllhegloba lfO void fO ( N: :fO; /I call N's fO ) What would happen if yo u called read more..

  • Page - 1078

    '048 for (int i=l; i<10; ++i) { vector<int> "I(i ); /I . .. AP PEN D IX A • LANGUAGE SUMMARY /I constructed in each iteration } /1 v1 destroyed here (i n each iteration) return new vector<int>(vO; II constructed on frcc store as a copy of vf } II vf destroyed here void ffO { ) vector<inp· I> = f(10) ; /I ... delete p; /I get vector read more..

  • Page - 1079

    A.S EXP RESSIONS A temporary var iable bou nd to a reference "lives'" as lo ng as the reference. For example: const cha r· s lrins-Ibl[J = { "Mozart", "C rieg", "Ha ydn", "Chopin " }; const cha r· f(inl i) ( re turn strins-tbl [i) ; ) void g(string s){} void hO ( canst slring& r = r(O); g{I{' »; string s = [(2); coul read more..

  • Page - 1080

    10SO Poslfi x ex pressions , . m p-> rn pix) f(l st) l( ls!) ... .-- t ypeid(x) type id m d ynami c_casl<T>(x) static_casl<T>( x) consCcast<T>(x) re inte rpreC cast<T>(x) APPENDIX A • LANGUAGE SUMMARY member access; x must be a class object member access; p must poi nt to a class object; e<luivalent to (· p). m subscripting; equivalent to read more..

  • Page - 1081

    A.S EXPRESSION S Unary expressio ns (continued) new(lst) T(lst2) dele te p de leteD p m, construct a T allocation determined by 1st and initialize it with Ist2 free the object pointed to by p free the array of objects pointed to by p C-style cast; convert x to T No te lhat lhe objeet (s) pointed to by p in delete p and deJete[J p Illust be a llo- cated read more..

  • Page - 1082

    1052 APPENDIX A • LANGUAG E SUMMARY For the (built-in) use of » and « for shifti ng bits, see §25_5.4. Whcn their Icft- most operators arc iostreams, these operalOrs are used for I/O; see Chaptcrs lO and I I. Relational operators x<y x less than y; re turns a bool x<=y x less than or equal to y Dy X greater than y D=y X greater than or equa l read more..

  • Page - 1083

    A .S EX PR ESS IONS l ogical o r 'Ii, logical or; returns tru e o r fa lse; evaluate y only if x is false See §A.5.5. Conditio nal ex pressio n xly :z if x the result is y; otherwise the resuli is z For example: templale<class T> T& max(T& a , T& b) { re turn (a>b)1a:b ; } ·111e '·question mark colon opcralOr" is explained in §8.4. read more..

  • Page - 1084

    1054 APPENDIX A .. LANGUAGE SUMMARY Comma expressio n ',Y Execute x then y; the result is y. Each box holds operators with the same precedence. Operators in higher boxes have higher precedence than operators in lower boxes. For example, a+b "c means a+( b"c) rather man (a+b)"c because " has higher precedence than +. Simi- larly, . p++ means "(p++), not read more..

  • Page - 1085

    A. 5 EXPRESS IONS ate ints out o r shorter integer types. This reflects the o riginal purpose or these promotions: to bring operands to the "natural" size ror arithmetic operations. In addition, float to double is considered a promotion . Promotions arc used as part or the usual arithmetic conversions (see §A.5.2.2). A.S.2 .2 Con versio ns TIle runda mental types read more..

  • Page - 1086

    1056 APPEND IX A • LANG U AGE SU MMARY Usual arithmetic aJllutrsiom: These conversions are performed on lhe operands o f a binary operator to bring them to a common type, which is then used as the type o f the result : 1. If either operand is of type long do uble , the other is conven ed to long doubl e. Othe rwise, if eithe r o pe rand is double read more..

  • Page - 1087

    A.S EX PRE SS IONS switch (x) ( case n : case 41+2 : case va r: 1/ . .. } ; A.S.4 sizeof /10K /10K II error (var is not a conSlant expression) In sizeof(x), x can be a type or an expression. If x is an expression, the value of sizeof(x) is me size of me resulting object. If x is a type, sizeof(x) is lhe size of an object of type x. Sizes arc read more..

  • Page - 1088

    1058 APPENDIX A • LANG UAGE SU MMAR Y If memory is exhausted , new lhrows a bad_alloc exception . A successful new op- eration a llocmes a t least 1 byte a nd rc tums a pointer to the allocated o bject. The type of object allocated is specified after new. For example: inl- pl = new inti inl- p2 = new int(7); int- p3 = new int[l00] i II ... 1/ read more..

  • Page - 1089

    A.6 STATEM ENTS Rcinterpret cast is used for reinterpreting a bit patlcrn. h is not guaranteed to be portable. In fact, it is best to ass ume that every use of reinlerpreCcasl is non- portable. A typical example is an int-w-pointer conversion to get a machine ad- dress into a prOhYTam; see §17.8 and §25.4. 1. The C-slyle and functional casts can perform any conversion read more..

  • Page - 1090

    1060 control-statement: break ; continue; return expreJSiQ11~ i gOlo idclltjfier i stale-l1Im/-/ul: slatement Jlaletn£1II-!ul<l>l rondihfJ1/: (xprcJSioll APPENDIX A • LA NG U AGE SU MM A RY l;ype-speajier dec/arolor = rxpmsi()1l j{Jl'-inil-s/a/emt'll/: expression ; iype-sp;;;" declarator = o:jJmJi01l ; Iull/dleT-lisl: catch ( a«plion-licculraholl ) { sta/e7lle1/t-{ist~ } read more..

  • Page - 1091

    A.7 D ECl ARATI O N S ) while (cin»x) ( ) if (x==te rminato r) break; /I exit whi le loop v. push_bac k(xl; fo r (int i = 0; i<v.s ize() && i<ni H i) ( if (v(i]==" p) re turn Pi else ++p ; ) return 0 ; A.7 Declarations A dularahon consists of three pans: 11Ie name of the entity being declared "n le type of the entity being read more..

  • Page - 1092

    1062 APPENDIX A • LAN GUAG E SU MMARY extern consl int Xi int y; /I a declaration /I (also) a definition int I = 10; /I a definition w ith an explicit initializer A const must be initialized. lllis is achieved by requ iri ng an initializer for a consl unless it has an explicit extern in ilS d eclaration (so that the initia lizer must be o n its de read more..

  • Page - 1093

    A.B BUILT· IN TYPES shorllong inl (that would havc been redundalll), and no long long long long inl. Some compilers anticipate the C++Ox standard and accept long long inl (read that as "very long intcger"). A long long is guaranteed to hold at least 64 bits . "nlC jloaling-poilll typeJ are floal , double, and long double . They arc C++'s approximation of real read more..

  • Page - 1094

    1064 APPENDIX A • LANGUAGE SUMMARY Sec § 17.4 a nd § 18.5.4. 111C operations on a (no n-void) object po il1lcr are: Pointe r o pe ratio ns '. dereferenccli ndi rectioo p [ij derefercnceJsu bscri pi i ng p=q assignment and ini ti alization .==q equa lity p! : q inequ a lity p+i add integer p-i subtract integer .-q di sta nce: su btract poi nters ... read more..

  • Page - 1095

    A.8 IW l lT- IN TYPES If an array is glo bal, its clements will be initialized to the appropriate default val ue fo r the type. For example, the value of a[7] will be o. If the array is local (a vm; able declared in a fu nction) o r a llocated using new, clements of built-in types will be uninitialized and clements of class types will be initial ized as read more..

  • Page - 1096

    1066 vo id f(consl string& S)i II ... APPEND IX A • LANGUAGE SU MMARY {( "this strin g could be somewhat costly 10 copy, so we use a refe rence "); Sec §8.5.4-6. A.9 Functions A jimelioT! is a named piece of code taking a (possibly empty) set o f arguments and optionally returning a value. A function is declared by giving the return type fo l- read more..

  • Page - 1097

    A .9 f U N C T IO N S A.9.1 Overload resolution 0ua(()(U1 resolulion is the process of choosing a fun ction to call bascd on a set of ar- guments. }<o r cxample : void prinl(inl) ; void prinl(double); void prinl (consl sid : :slring&); prinl(l23); print(1.23); print("123"); /I use print{int) /I use print(double) /I use print(const siri ng&) It is the read more..

  • Page - 1098

    1068 APPENDIX A • LAN G UAGE SU MMARY void f( int, const string&, d o uble ); void {(int, const cha r*, intI; f( 1, "he llo ", l )i f(1 ,string(" he llo"), 1.0 ); f(1, "h e llo ", 1.0 ); II OK: call {(jn t, consl char', int) II OK: ca U mnl, consl strin g&, double) II error: ambiguous In the last call, the "he llo read more..

  • Page - 1099

    A. 1 0 USE R- D EF INED TYPES J>rintH "J>rinl a char '%c'\o" ,x); J>rintf(" print a si ring \"%s\"" ,x); II print the int x as a char /I shoot yourself in the foot "111C "fomlat speci fiers" in the fonnat string, such as %c and %s, detennine if and how fu n her arguments arc used. As demonstrated, this Ct1.n lead to nasty read more..

  • Page - 1100

    1070 APP END IX A • LA NGUAGE SU MMARY For examples, see sid : :oslream (Chapters 10- 11), sid : :vector (Chapters 17- 19, §B.4), sld::complex (§B.9.3), and Matrix (Chapter 24). All but the follow ing operators can be user-defined : 1, • sizeof Iype id Functions defining lhe following operators must be members of a class: = II () -> All other operators can read more..

  • Page - 1101

    A.12 CLASSES Fo r a discussion of the uses of enumera tions, see §9.5. A.12 Classes A dms is a type fo r which the user defin es the represe ntation of iLS objeclS and the opera tions allowed on those objecLS: class X ( public: /I user interface private : /I implementation ) ; A variable, fu nction, or type defined within a class declaration is called a read more..

  • Page - 1102

    10n APPENDIX A • LANGUAGE SU MMARY For morc d etails of member access, including a discussio n of prote cted , see §14.3.4. M embers of an object can be accessed through a variable or referenced usi ng the . (dot) operator or through a pointer using the -> ( arrow) operator: slru ct Date { int d, m, y; int da rO const { return d ; } /I defined read more..

  • Page - 1103

    A.1 2 ClAS SES A.12.1.1 The this pointer If we wam to be explicit when referring to the object for which the member func- cion is called, we ean use the predefined poilllcr this : struct Date { intd , m,y; } ; int mo nthO ca nst { return this->m; } II ... A mcmber function declared canst (a canst member function) cannOl modify the value of a member of the read more..

  • Page - 1104

    1074 APP ENDIX A • LANGUAGE SU MMARY As shown, this is usually done for fun ctions that need to access two classes, An- Olher usc of friend is to provide an access function that should not be c.'dled using the member access syntax, For example: class Ite r { public : inl distance_to(const iter& a) canst; frie nd int diHe re nce(const Ite r& a, co nst read more..

  • Page - 1105

    A. 12 ( LA SS ES TIle stati c canst int members arc an odd special case. TIley just derUle sym bolic integer constaills and do not take up memory in the object. Non·static data memo bers do not require separate definition , cannot be separately defined, and cannot have in·class initializers: strucl X { }; inl Xi int y=7; /I error: non·slatic data members /I cannot read more..

  • Page - 1106

    1076 AP P ENDIX A • LANGUAGE SUMMA RY Date d1 (2006,11, 15); Date d2; II OK: initialization done by the constructor /I error: no initializers Date d3(11 ,15); /I error: bad initializers (three initia lizers required) Note thai data members can be initialized by using an initializer list in the con- structo r (a base and member initializer list). Me mbers will be read more..

  • Page - 1107

    A. 12 C LA SS ES TIlis S has an implicit constructor SO iliat initializes name and address, but not x. A.12 .3.1 Destructors YOll can define the meaning of an object being destroyed (e.g. , going out of scope) by defining a lieS/nic/or. TIle name of a destructor is - (the complement operator) followed by the class name: class Vector ( 1/ vector of doubles public read more..

  • Page - 1108

    1078 private: ); in! S1:; double- Pi void f(i nt 5S) ( Vector V(5); AP PENDIX A • LANG UAGE SUMMA RY Vector v2 = Vi II use co py constructor /I . .. v = v2 , /I. /I use copy assignment By d efault (that is, unless you d efine a copy constmcLOr and a copy assignment), the compiler will generate copy operations for you. The d efault meaning o f copy read more..

  • Page - 1109

    A. 12 CLASSES cess to members of its bases, so 00 docs not have access to the private members of 81 or 82. A class with mo re than o ne direct base class (such as 00) is said to usc mulli- pie illlu:riltlllcc. A pointer to a derived class, 0 , can be im pliciuy converted to a pointer to its base class, 8 , provided 8 is accessible and is unambiguo us read more..

  • Page - 1110

    ' 080 APPENDIX A • LANG UAGE SU MMA RY Basically, the virtual functions of a base class (here, Shape) define a calling inter- face for the d eri ved class (here, Circle ): void f(S hape& s) { ) II . . . s.draw(); vo id gO { C ircle c(Po in t(O,O). 4); fCc); II wi ll call Circle's draw ) Note that fO doesn't kn ow about Circles, o nl y about read more..

  • Page - 1111

    A.12 CLAS SES So, §14.3.5. '11e rarer, but equally effective, way of making a class abstract is to declare ail its constructors protected (§14_2.1 ). A.12.4.3 Generated operations When you define a class, it will by default have several operations defined for its objects: Default constructor Copy operations (copy assignment and copy initialization) Destructor E..1.ch is (again by read more..

  • Page - 1112

    '082 APPENDIX A • LANGUAGE SUMMARY A.12.5 Bilfields A bi!fold is a mechanism for packing many small values into a word o r to m atch an extcmally imposed bit-layout format (such as a device register). For example: slru ct PP N ( unsig n ed int PFN : 22; inl : 3; 1/ UI'uscd unsigned int CCAj bool no nrcacheablCj boo l dirt y; bool valid ; bool glo bal; ) read more..

  • Page - 1113

    A.1 3 TEMPLATE S int xl = a.x: /I OK a.d = 7.7: int xl = a .x: /I oops TIle ru[c rc([uiring consistent reads and writes is not checked by the compiler. You have been wamed. A.13 Templates A lem/Jltlle is a class or a function paraJl1elerized by a set of types andlor integers: template<class T > class vecto r { public: 1/ . . . int sizeO const: private: read more..

  • Page - 1114

    1084 APPENDIX A • LANGUAGE SU MMARY A.13 .1 Template arguments Arguments for a template class arc specified whenever its name is used: veclor<int> v1 ; vector v2 ; veclor<int,2> v3; ve ctor<2> v4; II OK II error: template argument missing 1/ error: too many templa te arguments II error: type template argument expec ted Arguments for template functions arc read more..

  • Page - 1115

    A . 1 ) TEMPLATE S finc a specific specialization. "Illis is usually done when a gcncrallcmplate is un- suitable for a particular sct of argumcnts. For examplc: template<class T > s tru et Compare { II general compare bool operatorO(const T& a, canst T& b) eonst { return a<b; ) ) ; template<> strucl Compar e<eonst c har· > { /I compare C-style strings read more..

  • Page - 1116

    '.86 AP P END IX A • LANG UAGE SUMMARY A.13.3 Template member types A template can have members that are types and members that are not types (such as data members a nd member functions ). This means that in general, it can be hard to tell whether a member name refers to a type or to a non-type. For language- technical reasons, the compiler has to kll0W, so read more..

  • Page - 1117

    A.14 EXCEPTIONS void f(int x) { try ( ) Vector v(x); /I may throw /I . .. catch (Bad_size bs) ( ) cerr« "Vector with bad size (" «bs.sz« ")\n "; /I . .. A <;catch a ll" cla use can be used to catch every exception: try { /I . ) catch (,',) ( /I catch all exceptions /I . .. ) Usually, the RAJ I ("Rcsource Acqui sition Is read more..

  • Page - 1118

    1088 AP P ENDIX A • LANGUAGE SUM MARY this search of a matching catch-clause and in each scope o n the way, dcstructors arc called to clean up. This process is called stacie unwinding. An o bject is considered constructed once its constructor has completed a nd will then be destroyed during unwinding or any other exit from its scope. TIus implies that partially read more..

  • Page - 1119

    A . 16 ALIA SES /I thaI's the global f (::f) } Names can be explicitly qualified by their names pace name (e.g. , Foo: :f(3») or b y :: (e.g., : :f(2»), indic.'l.ling the global scope. All names rrom a names pace (here, the standard library namespace, sid) can be made accessible by a single namcspace directive: using namespace sid; Be res trai ned in the lise or read more..

  • Page - 1120

    1090 APPENDIX A • LAN GUAGE SU MM ARY A.17 Preprocessor directives Every C++ implementation includes a prtproa.ssor. In principle, the preprocessor runs before the compiler proper and transforms the source code we wrotc into what the compiler sees. In reality, this action is integrated into the compiler a nd uninteresting except w hen it causes problems. Every line starting read more..

  • Page - 1121

    A.17 PREPROCE SSO R DIRECTIVES And we can use it like this: int xx = MAX(FOO+1 ,7); int yy = MAX(++xx,9)i This will expand to int xx = «( bar+1 »( 7))?(b a r+1 ): (7)) ; int yy = «(++xx»( 9))?(++xx) : (9)); Note how the parentheses were necessary to get the right result for FOO+ 1. Also note that xx was incremented twice in a very non-obvious way. Macros read more..

  • Page - 1122

    read more..

  • Page - 1123

    ' c!. r -· B Standard Library Summary "All compl exities should, if possible, be buried out of sight." -David J. Wheeler T his appendix su nunarizes key C++ standard library facili- ties. 111e summary is selective and geared to novices who want to gel an overview of the standard library facilities and ex- plon~ a bit beyond the sequence of topics in the book. read more..

  • Page - 1124

    1094 APPENDIX B • STANDARD LIBRARY SUMMARY B.l B.2 B.3 B.' Overview B.l .1 He~de,files B.l .2 N",mcspace sid 8.1 .3 Description styl e Error ha ndlin g B.2.1 Exceptions lIeralors B.3. 1 lIer;llor model B.3.2 lIerillo r ca tego ries Contai ners B.4. 1 Overview B.4.2 Member types B.4.3 Co nslru clo rs, deslruclors, and ass ignments B.4.4 lIeratars B.4.5 Element access read more..

  • Page - 1125

    3.1 OVE RV I EW mon operations are available. You may very well have to look elsewhere for a de- tailed explanation, bUl that's fine: now you have a due as to what to look for. Aiso, this summary contains cross-references to tutorial material in the chapters. 111is appendix provides a compact overview o f standard library facilities. Please do not try to melllOl;ze the read more..

  • Page - 1126

    1096 APPEND IX B • STANDARD LIBRARY SUMMARY The STL (co ntaine rs, ile ralors, and algo rithms) (continued ) <slack> <unordered_map> <unordered_set> <utilit y> stack hash maps (C++Ox) (§21.6.4) hash sets (C ++Ox ) operators and pair (§B.6.3) <vector> I/O streams <iostream> dstream> <sslream> <iosfwd> <ius> <streambU D <istream> read more..

  • Page - 1127

    3 . 1 OVERVIEW Utility and language support <exceptio n:> <slde xcept> <locale:> <typeinfo:> <new:> exception types (§B.2.1) exception hierarchy (§B.2. 1) culture-specific formatting standa rd type information (from typeid) allocation and deal location functions C standard libraries <cSlring> C-style string manipulatio n (§B. l 0.3) <csldio:> C-style 1/0 read more..

  • Page - 1128

    1098 AP P ENDIX B • STANDA RD LIBRARY SUMMARY B.1.2 Namespace sId The standard library facilities a rc defin ed in namcspacc Sid, so to usc them, you need an explicit qualification, a using declaration, or a using directive : sid : : slring s; using sid : : veclof; veclor<inl>v(7); using namespace sid ; map<string, double> m ; /I explicit qualifica tion II read more..

  • Page - 1129

    B.2 ERROR HANDLING Gstyle libraries consist of functions, many of which set e rmo to indicate that an error happened; see §24.8. M any algorithms operating on a sequence of clements return an iterator to the one-past-the-Iast clement to indicate "not found " or "fail ure." The 110 streams library relies on a state in each stream to reflect errors and may read more..

  • Page - 1130

    1100 APPEND IX B • STANDARD LI BR ARY SU MMARY }; cxceplio n(); exceplio n (con st exception&)i exceplio n& o perato r=(co nsl exceptio n&); vi rtua l -exceptionO; vi rtual const cha r· what() const ; The whatO fun ction can be used to obtain a string that is supposed to indicate something about the error that caused the exception. This hierarchy of read more..

  • Page - 1131

    B. 3 ITERATO RS sort, find , search, copy, . .. , my_very_own _algorithm, your_code, ... vector, list, map, array, ... , my_container, your_container, .. . B.3.1 Iterator model An iterator is akin to a poimer in tbat it provides operations for indirect access (e.g., • for dercferencing) and for moving to a new clement (e.g., ++ for moving to the next clement). A read more..

  • Page - 1132

    11 02 APPENDIX B • STANDARD llBRARY SUMMARY So< §20.3. Algorithms that write to a sequence orten arc given only an itcrator to its first clement. In that case, it is the programmer's responsibility not to write beyond the end of that sequence. Fo r example: template<c1ass Iter> void (Iter p, int nl { while (n>O)" p = --n; } veclor<inl> v (10); read more..

  • Page - 1133

    B.3 lTERATORS Iterator operations (continued) p<q p=q p>q p>=q p+=n p -=n q=p+n q=p-n advance(p,n) x=difference(p,q) Does p point to an element before what q points to? p<q II p==q Does P point to an element after what q points to? p>q II p==q Advance n : make p point to the nth element after the one it points to. Advance - n : make p poinl to read more..

  • Page - 1134

    1104 APPENDIX B • STANDARD LI BRARY SU MMARY lIerato, categories (continued ) bidirectional iteratar We can iterate fOl'\va rd (using ++) and backward (using --) and rea d and write (unless the elemen ts arc const) elements using *, This is the kind of iterator th at list, map. and set offer. randomaccess iteratar We can iterate forwa rd (using ++ or +=) and backwa read more..

  • Page - 1135

    11.'1 CONTA INERS set - bidirectional mulliset - bidirectional map - bidirectio nal multima p - bidirectional uno rde red _set - forward uno rde red multise t - forward unorde red_map - fonvard un ord e re d_multimap - fonvard B.4 Containers A container holds a sequence o f objects. The clements of the sequence are of the member type called value_t ype. The most read more..

  • Page - 1136

    1106 APPENDIX B • STA NDARD LIBRARY SUMMA RY Contai ne r adaptors prio rit y_que ue<T> queue<T> stack<T> priority queue queue with pushO and popO stack wi th pushO and popO 111csc containers arc defined in <vedo!'>, <liSI> , elc. (sec §B. l.l ). 111c sequence containers are contiguously allocated or linked lists of elements of their valu e_type (T read more..

  • Page - 1137

    BA CONTAINE RS 8.4.1 Overview 111e opera tions provided by the standard containers can be sUITUllanzed like lhis: Container: constructor, Copy constructor, de rault constructor, begin O, end(), rbegin O, rendO, ==, !=, <, < =, >, >=, =, swap(), size(), max....size(), empty(), insert(), eraseO, dear() Sequential container: assignO, frontO , back(), push_back() , pop_backO, resizeO read more..

  • Page - 1138

    1108 APPEND IX B • STAN DARD LIBRARY SUMMAR Y 8.4.2 Member types A container d efi nes a set o r member types: M ember types value_l ype size_type difference_t ype ite rato r consCite rato r reve rse_ite rato r consc , eversc_ile rato r refe rence cansl_reference po inter canst_po inter key_lype mapped_type key_compare a llocato f_type type of element type of read more..

  • Page - 1139

    6 .4 CONTAINER S ConstruClors, destructo rs, and assignme nt (co ntinued ) C c(c2); - CO cl=c2 c.assign(n,x) c.assign(b,e) c is a copy of c2. Destroy a C and all of its elements (usually invoked impl ici tl y). Copy assignment; copy all elements from c2 to cl ; after the aSSignment cl==c2 . Assign n copies of x (not for associative containers). Assign from [b read more..

  • Page - 1140

    1110 AP PEND IX B • STANDARD LIBRARY SU MMARY B.4.6 Stack and queue operations The standard vector and d eque provide efficient operations at the end (back) of their sequence of clements. In addition, list and dequ e provide the equivalent op- erations on the Start (front) of their sequences: Stack and queue operations c.push_back(x) c.pop_backO c.push_front{x) c.pop_frontO Add read more..

  • Page - 1141

    IJA CONTAINER S Size and capacity x=c.size() c.emptyO x=c. max_sizeO x=c.capacityO c. reserve(n) c.resize(n) x is the number of elements of c. Is c empty? x is the largesl possi ble number of elements of c. x is the space allocated for c (vector and siring only). Reserve space for n elements for c (vector and string only). Change size of c to n (vector, string, read more..

  • Page - 1142

    1112 APPENDIX B • STANDARD LIBRARY SUMMARY Associative container ope ralions (continued) p=c.lower_bound(k) p=c.upper_bound(k) pai rep 1 ,p2)=c.eq uaCrange(k) r=c.key_comp{) r=c.value_compO p points to the first element with key k. p points to the first element with key greater than k. [pl ,p2) are the elements with key k. r is a copy of the key·comp<"trison object. r read more..

  • Page - 1143

    B.5 ALGO RI THM S 1113 Many algorithms rollow the usual convention o r returning the end or a se· quence to re present "not round." We don' t mention that ror each algorithm. B.S.l Nonmodifying sequence algorithms A nonmO(:liryillg algolithm juSt reads the clements or a sequence; it does not re- arrange the sequence and docs nOt change the value o r the read more..

  • Page - 1144

    1114 APPEND IX B • STANDARD LIBRARY SUMMARY Note that nothing stops the operation passed to fO f_ea ch from modifyi ng cle- ments ; that's considered acceptable. Passing an operation that changes the cle- ments it examines to some other algorithm (e.g. , count or ==) is not acceptable. An example (of proper use): bool odd(int xl { fe turn x&l ; } int n_even(const read more..

  • Page - 1145

    B.5 ALGORIT HM S Modifying sequence algori thms (continued ) p=re place_copy(b.e.out.f.v2) p=re move(b,e.v) p=re move(b,e.v,f) Copy Ib :e) to lo ut : p), replacing clements *q in Ib:e) fOf which Wq ) with v2. Move elemenls *q in Ib :e) so Ihal lb : p) becomes the elements (Of" which W q ==v). Move elements *q in Ib :e) so that Ib : p) becomes the elements read more..

  • Page - 1146

    111 6 APPENDIX B • STANDARD liBRARY SUMMARY void ffO { ) int aU = { 1,1,1, 2,2, 3, 4,4,4, 3,3,3, 5,5,5,5, 1,1,1 }; vector<inl> v(a,a+sizeof{a )/sizeof(in I»; print_digits("all : ",v.beginO, v.e nd{»; vector<inl> : :iterator pp = unique(v.begin (),v.end{»; prinCdigits(" head : II ,v.beginO, pp) ; prinCdigits(" tail : ",pp,v.end()); Pl>= remove( v . read more..

  • Page - 1147

    (l .S ALGORIT HM S 111 7 Note that uninitialized sequences should occur only at the lowest level of pro- gramming, usually inside the implementation of containers. Elements that are targets of uninitialized_fill or uninitialized_copy must be of built-in type or uninitialil.ed. B.5.4 Sorting and searching Sorting and searching are fundamental and the needs of programmers arc quite read more..

  • Page - 1148

    1118 APPENDIX B • STANDARD LIBRARY SU MMARY Sorting and searching (continued ) pair{p1 ,p2)=equal_,ange{b,e, v,f) p=me rge{b,e,b2,e2,o ut) p=me rge{b,e,b2,e2,o ut, f) inplace_me rge(b, m,e) inplace_me rge{b,m,e,f) p=part it io n(b, c, f) p=stablc_part ition (b,e, f) Fo r exa mple: vecto r<i nt> V ; lisl<do uble> 1 51; Ip1 ,p2) is the subsequence of Ib :e) with the va read more..

  • Page - 1149

    B. 5 ALGO RITHM S Set algorithms includes(h,e,h2,e2) inciudes(b,e,b2,e2,O p=seLunion{b,e,b2,e2,Out) p=seLunion(b,e, b2,e2,out,O p=seLinle rsecl io n(b,e,b2,e2,oul) p=seLinte rsecl io n(b,e,b2,e2,out,O p=sel_diffe rence(b,e,b2,e2,oul) p=seLdiffe rence(b,e,b2,e2,out,(J p=seLsymme lric_diffe re nce(b,e,b2,e2,oul ) p=seLsymme lric_differe nce (b,e, b2,e2,o ul,f) B.5.6 Heaps 1119 Areall e lements of Ib2:e2) also read more..

  • Page - 1150

    11 20 APPENDIX B • STAND ARD LIBRARY SUMMARY Heap operations (continued ) pop_heap(b,e) pop_heap(b,e,O sorCheap(b,e) sorC heap(b,e ,O Remove largest (first) element from heap. Remove element from heap, using f for comparison. Sort the heap. Sort the heap, using f for comparison. 111e point of a heap is to provide fast addition of clements and fas t access to the clement read more..

  • Page - 1151

    8.6 STL UTI LITIE S min and max lI=max(a,b) lI=max(a,b,f) lI=min(a,b) lI=min(a,b,f) p= max_elemenl(b ,e) p=m~element ( b , e , f) p=min_element (b,e) p=min_element(b,e,f) lellicographical_compare(b, e, b2,e2) lexicographical_compare(b ,e, b2,e2,f) B.6 STL utilities x is the larger of a and b . x is the larger of a and b using f for comparison. x is the smaller of a and b read more..

  • Page - 1152

    11 22 Inse rte rs r=backj nserte r(c) r=fronUnserter(c) r=inserte r(c,p) APPEND IX B • STANDARD LIBRARY SUMMARY · r=x causes a c.p ush_back()!). ·r=x causes a c .pu sh_ho nt(x). · r=x causes a c, inserl(p,x). For inserte r(c, p), p must be a valid itcrator for the container c. Naturally, a con- tainer grows by one clcmelll each time a value is written to it through read more..

  • Page - 1153

    B.6 STL UT ILITIE S vector<inb v; 1/ . . . SO rt( v. begi n (),,,.e nd (), greater<i nbO ); II son v in decreasing order Note that logical_and and logicaCor always evaluate both their argumen ts (whereas && and II do not). Arithmetic ope rations f=plus<T>O f=minus<T>O f=multiplies<T>O f=divides<T>() (=modulus<T>() f=n egate<T>O Adaptors read more..

  • Page - 1154

    11 24 }; AP PENDIX B • STANDA RD LIBRARY SUMMARY pair() i /I default constructor pair(const T1& x , const T2& y) ; // copy operations: te mplate<class U , class V > p air(eonst pair<U , V>& P l; te mplate <class T1 , class T2> pair<T1 ,T2> m ake_pair(T1 x, T2 y) { return pai r<Tl ,T2>(x,yl; } 111e make_pair fun ction makes the usc of read more..

  • Page - 1155

    S.7 1/ 0 ST REAMS Valucs Or various types Charactcr scqucnccs "Somc\vhere" (12,34) ostream Buffer An islream converts a strcam or characters (bytcs) to typed objects: Valucs or various types Character scqucnces "Somcwhere" (12,34) istrum BulTer An ioslream is a strcam tha t can act as both an islream and an osl ream . The buffcrs in the diagrams arc read more..

  • Page - 1156

    11 26 APP ENDIX B • STA NDARD LIBRARY SUMMA RY B.7.1 1/0 51 reams hierarchy An IUr\!lUn can be connected to an input device (c. g., a keyboard), a [de, or a lit ring. Similarly, an oslre:un ca.n be con nected to an omplll device (c.g., a tcxt win- dow), a me, or a slrlns . 111C 1/0 stream facilities are organizcd in a class hierarchy: istream os ....... read more..

  • Page - 1157

    n .7 JlQ STR EAM S In each case, the exact effect of opening a me may depend on the operating sys- tem, and if an operating system cannot honor a request LO open a me in a certain way, the result will be a stream that is not in the 8oodO Slate. An exam ple: oi lrlng!ilrcant Oi; 1/ 0 for ~UU")lI, H of8lre:ul1 of(ltmy_tIIl! lt ); II (Iof) read more..

  • Page - 1158

    11 28 APPEND IX B • STANDARD LIBRARY SUMMARY B.7 .3 Input operations Input operations a rc found in <istream> except for the ones reading imo a si ring ; those arc found in <String>.: Formatted input in » . getline(in, s) Read from in into x acc()(ding to . 's Iype. Read a line from in into the siring s . Unless Olhcnvisc stated, an istrcam read more..

  • Page - 1159

    B. 7 IJO STR EAMS Output operat ions o ul « /I Write /I to oul accordin g to /I 'S type. out .pul(t) Write the character t to out . out .wrhtl(p,n) Write the characters pI0) .. pln- 11 to out. Unless otherwise statcd, an 6I1 ft!!u" operation returns a reference to its ollircam , so that we can "chain" operations, for example, Coui «x<<y; . read more..

  • Page - 1160

    1130 APPENDIX B • STANDARD LIBRARY SU MMARY VO manipulators (continued) s« no uppe rcase s<<i nterna l s« le(t s« right s« dec s« hex s«ocl s<<iixed s<<scie nlific s«end l s«ends s<<fIush P>W5 s« resetiosflags(O s<<se t ios flags(O s<<se tbase(b) s<<setfill(c) s<<setprecision (n) s<<se tw( n ) x and e rather than X read more..

  • Page - 1161

    B,B STRING MANIPULATION 1'0 explicitly set the general output fonnat for floatin g-point numbers use b.setf(ios_base: :fmtflags(O), ios_base : :floatfieldl See Chapter I I. B.B String manipulation 111e standard library offers character classification operations in <cctype>, strings with associated operations in <string>, regular expression matching in <regell> (C++Ox), and read more..

  • Page - 1162

    1132 APPEND IX B • STANDARD LIBRARY SU MMARY 0.0.2 String The standard library string class, siring, is a specialization of a general string tem- plate hi'!l I Irln8 for the character type ChAt ; that is, I Irl"8 is a sequence of t hars: Siring o pe ratio ns 1>-.2 ••• I:ttl() Ii. ltl nglh() I.C_IIfO li. beglnO l.tlnd O 8. ln.l.lrUpOI,II) 8.al,p,m d{p08,1I) read more..

  • Page - 1163

    B.8 STRING MAN I PULATION B.0.3 Rcgular c~prcll ion matching Thc rcgular cxprcssion library is not yct part or the standard library, but it will soon be and it is widely availablc, so wc list it hcrc. Sec Chapter 23 ror morc dc- tailed explanations. TI1C main c re8"I(> runctions arc Searchi1lg ror a string that matches a regular exprcssion in an (arbitrarily long) read more..

  • Page - 1164

    1134 AP PENDIX B • STANOARD LIBRARY SUMMARY Regular expression special characters (continued ) l $ Repetition ( n ) ( n , ) ( n ,m) + l optional (zero or one) ahernative (or) start of line; negation end of line exactly n times n or more times at least n and al most m times zero Of more, that is, to,} one or more, that is, {I ,} optional (zero or read more..

  • Page - 1165

    0 .9 NUMERI CS Several character classes are supported by shorthand notatio n : Charade r class a bbrevialio ns III a dec imal di gi t lI,dlglllll ~ a lowercase character II I lowtirt 11 " a space (space, lab, elc.) Ul8 paftli U Iu an uppercase character Ifl1lfJpa t ill Iw a letter, a decimal digit, 0( an underscore Cl II hlll1l1m lll III not \d 1' read more..

  • Page - 1166

    1136 ); APP ENDIX B • STANOARD LIBRARY SU MMARY static float minO { return 1.17549435E-38F; } static float maxO { return 3.40282347E+38F; } /I example value "example value static float epsilonO { relurn 1.19209290E-07F; } static float round_crrorO { re turn O.5F ; } 'I example value II example value static float inrinit yO { return , - some value -I; } slatic read more..

  • Page - 1167

    8.9 NUMERICS Limit macros (continued ) LONG_MIN LONG_MAX FLY_M I N FLY_M AX FLY_DIG FLT_MAX_10_EXP D8L_MIN DOL_MAX DBL_EPSILON smallest int value largest int va lue smallest positive float value (e.g., 1.175494351 e-38F) largest float value (e.g., 3.402823466e+38F) number of decimal digits of precision (e.g., 6) largest decimal exponent (e.g., 38) smallest d o uble value largest read more..

  • Page - 1168

    1138 APPENDIX B • STANDARD LIBRARY SUMMARY There are versions taking flO i't. doublQ. 10118 doubl e, a nd c:on1J)IQ. arguments. For each function , the retu rn type is t.he same as the argument type. If a standard mathematical fun ction cannot produce a mathematically valid result, it sets the variable errno. B.9.3 Complex The standard library provides complex number types read more..

  • Page - 1169

    B.9 NUMERICS Complex o pe rators (confi nued) imag(z) imaginary part abs(z) also known as rho arg(z) also known as theta o ut « z complex output in » z complex input TIle standa rd mathematical functions (see §B.9.2) arc also available for complex nu mbers. Note: com plex does not provide < or %; sec also §24.9. B.9.4 valarray TIle standard vala rray is a read more..

  • Page - 1170

    " 4<1 APPENDIX B • STANDARD LIBRARY SUMMARY B.10 C standard library functions ~nc standard library for the C language is with very minor modifications incor- porated into the C++ standard library. TIle C standard library provides quite a few functions that have proved lIsefu l over the years in a wide variety of contexts - especially for relatively low-level read more..

  • Page - 1171

    B.IO C STAN DARD LIBRARY FUNCTIONS '1lcrc may be (and usually are) more options on a specific system. Some options can be combined; for examplc, tnlnm("too" , "rb ") tries to open a file c:.-tllcd too for binary reading. TIle 110 modes should be the same for stdio and 100i tr~a lU S (§B.7.1 ) 0.10.2 The prln!lO (~mlly 111C most popular C standard read more..

  • Page - 1172

    1142 APPENDIX B • STANDARD LIBRARY SUMMARY In gene ral, the correspondence between a % conversion directive and the type to which it is applied cannot be checked, and w hen it c.'l.n, it usually is not. Fo r example: printf("the value of x is '%5' a nd th e value of s is '%d '\n",x,s); II oops The set o f conversion specifications is qui te large and read more..

  • Page - 1173

    6.10 C STANDARD LIBR ARY FUNCT I ONS c a character t.hat indicates the type of conversion LO be applied. l 11e con· version characters and their meanings are : d TIle integer argument is converted to decimal notation. "I1le integer argument is converted LO decimal notation. o The integer argument is converted to OCtal notatio n. x The integer argument is converted read more..

  • Page - 1174

    1144 APPENDIX 8 • STANDARD LIBRARY S UMMARY Because C docs not have user-dcHncd types in the sense that C++ has, there afC no provisions for dcfming Output fannats for user-defin ed types, such as cOlUplex, vector, or t iring. Tne C standard output, 8ldoul. corresponds to coul . The C standard inplll, , Id ln, corresponds to cl n. The C standard error output, ' read more..

  • Page - 1175

    B. 1 0 C STANDARD LIBRARY FUNCTIONS otherwise it is SCt to s. Ncver usc gets(s) or its rough equivalent (scanf(""Ios ",s))! For years, the y werc thc favoritcs of virus writers: by providing an in put that overflows thc input buffer (s in the example), a program can bc corrupted and a computer potcntially taken over by an attacker. Thc sprintfO function read more..

  • Page - 1176

    "46 APPENDIX B • STANDARD LIBR A RY SU MMARY C-style string operations • _,Irlan(,) p_' lrcpy(",:Z) p_' lrCIt(".:I) x.,lrCm,)(I, , 2) p.,lrncpy(t,t:Z, nJ p.,lrnc.I(M 2, n) •• , lrnc:mp(I,.2,n) p_'lrchr("c) p.,trrchr(l,c) p.,I,. 'r("iZ) p.'lrpbrk(",2) lI _alof(,) • _.101(.) ,,_alol(. ) 1I.,lrIOd (" p ) Coun t the characters (excluding the terminating read more..

  • Page - 1177

    IUO C STANDARD LIBRARY FUNCTIONS C-slyle memory operations q _m emmovc( p ,p2,n) lI_ mement pip, I):/:,n ) q_mcmehr(p ,(, n) I) _ea lloe(n,.) free( pl Copy n bytes from p2 to p (like f lrcpy); [p :p +n) and Ip2: p2+n) may not overlap; (I- P. Copy n bytes from p2 to p; (, _p. Compare n bytes from p2 to the equivalenl n bytes from I) (like I lremp). find read more..

  • Page - 1178

    1148 APPENDIX B • STAN OARO LIBR A RY SU MMAR Y slruct 1m is d efined like this: slruct 1m { J; int 1m_sec; 1/ second of minute [0:61 I; 60 and 61 represent leap seconds int 1m_min i /I minute of hour [0,591 int 1m_hour; 1/ hour of day 10,231 int Im _mda y; 1/ day o f mo nth 11,3 1 J int Im_mon ; /I month of year (0, 111; 0 means January read more..

  • Page - 1179

    B.IO C STANDARD LIBRARY FUNCTIONS ) for (int i = 0; i<n; i++) d o_some lhing(); /I timing loop clock_t 12 = clock(); II end time if (12 == clock_t{-1)) { cerr « "sorry, clock overflow\n"; e xiI(2); cout« "do_something() " « n « " times took " « double(t2-I1)1ClOCKS_PER_SEC« " seconds" « " (meas ure me nt granularity: " «CLOC read more..

  • Page - 1180

    11 50 APPENDIX B • STAN DARD LIBRARY SUMMARY TIle compmison function (emil) used by <IsoriO a nd btlca rch() must have the type In' (" Cnl,J )(cunlt void " p, ( ontl t void " q)i 111<lt is, 110 type infonnatioll is known to the sOrt funclion that simply "sees'" its array as a sequence of bytes. The integer returned is Negative if "Jl is read more..

  • Page - 1181

    · . t ,. C Getti ng Started with Visual Studio "The universe is not only queerer than we imagine, it's queerer than we can imagine." -J. B. S. Haldane T his appendix CXp11l i1l1l Ihe steps YOII have to go 1-hrough to tiller a pl'ogr:lm. compile it, and have it !'till using MicrOHort Visual Srudio. 1151 read more..

  • Page - 1182

    1152 A PPEND I X C • GETTING STARTED W IT H VI SUAL 5TUDIO C.l Gelting a program to run C.2 Installing Visual Studio C.3 Creating and running a program C l .1 Create a new project ( .l. 2 Use the std_lib_facilili es.h head er file Cl.l Add a C++ source file to the project C.l .4 Enter your source code Cl.S Build an executable program C l .6 b ecute read more..

  • Page - 1183

    C.3 CREATING AND RUNN I NG A PRO GRAM C.3 Creating and running a program The steps arc: 1. Create a new project. 2. Add a C++ source file to the project. 3. Enter your source code. 4. Build an executable fIle. 5. Execute the program. 6. Save the program. C.3.1 Cre~tc ~ new project In Visual Studio, a "project" is a collection of files that together provide read more..

  • Page - 1184

    1154 APPENDIX C • GETTING STARTED WITH VISUAL STU DIO Place a copy of it in the directory you chose in §C.3. 1, step 6. (Note: Save as text, IlOt HTML.) To usc il, you need the line #include " . .I. Js td_lib_faci lilies. h" in you r program. The " .J . . r tells the compiler that you placed the header in C:\Documents and Settings\Your Name\My read more..

  • Page - 1185

    C.4 LATER C.3.6 Execute the program Once al[ errors have been eliminated, execute the program by going to the Debug menu and selecting Start Wtthout Debugging. C.3.? Save the program U nder the File menu , dick Save All.lfyo Li forget and try to dose the IDE, the IDE will remind you . C.4 later TIle IDE has an apparent infinity of features and options. Don't worry read more..

  • Page - 1186

    read more..

  • Page - 1187

    \ t . r 0 Installing FLTK "If the c ode and the comments disagree, then both are probably wrong." -Norm Schryer T his appendix describes how 10 download. i", .. ll. and link to the FL1' K gl'ilphicl ond CU I toolki t. 1157 read more..

  • Page - 1188

    11 58 0.1 Introduction 0.2 Downloading FLTK D.) Installing FLTK 0.4 Using FLTK in Visual Studio 0.5 Testing if it all worke d D.1 Introduction APPENDIX 0 • IN STALLING FLTK We chose FLTK, the Fast Light Tool Kit (pronounced "full lick"), as the base for our presentation of graphics and CU I issues because it is portable, relatively sim- ple, relatively read more..

  • Page - 1189

    0.4 US IN G FlTK IN VI SUAL ST U DIO 0.3 Installing FLTK Your main problem in following our insouctions is likely to be one of two: some- thiJlg has changed since we wrote and tested them (it happens), or the tenmnol- ogy is alien to you (we can't help with that ; sorry). In the latter case, find a friend to translate. I. Unzip the downloaded file and open read more..

  • Page - 1190

    1164) APPEND I X D • I NSTAL LI NG FLT K 4. [Ths step may be unnecessary because I MDd is now the default.] In the left menu of the same Properties window, dick C/C++ to c.xpand a dif- ferent sub-menu. C lick the C ode Generation sub-menu item. In the right menu , change the Runtime Library drop-down to Multi-threaded Debug DLL (/ MDd ). C lick OK lO d read more..

  • Page - 1191

    CUI Implementation "When you finally understand what you are doing, things will go right." -Bill Fa irbank T his appendix presents implementatio n details of callbacks, Window, Widget, and Vector_ref. In Chapter 16, we couldn 't assume the knowledge of pointers and casts needed ror a more complete explanation , so we banished that explanation to tltis appendix. 1161 read more..

  • Page - 1192

    1162 E.1 Callback implementation E.2 Wldjl@1 implementation E.3 Window implementation E.4 Vector_' ll' E.5 An example : manipulating Wld8l!ls APPENDIX E • G U I IMPLEMENTAT ION E.l Callback implementation We implemcnted callbacks like this: \lo ld Slmpll!~wlndow ll cb_n Ci'.t(Addrcu . Addre" addr) II LLlll ~ltfil)lc_wlmluw:: IICXI() (Of IIII.' wln(tuw IOC,IIl'd ,II pw Once you read more..

  • Page - 1193

    E.2 WIDGET IMP LEMENTATI ON { re turn 'stalic cast<W">(pw); ) Here, we used a template fun ction to write ourselves an operation that aeLS as a cast from a void ' to a Simple_window&. Th e type conversion, staliccast, is de- scribed in §17.8. The compiler has no way of verifying our assertion tha t addr poinLS to a Simple_window, but the language rule read more..

  • Page - 1194

    "64 AP PEND I X E a CUI IMPLEMENTATION vl,lu. 1 void hldoO ( pw-.hldoO, ) vl,tual void iihowO ( pW->l howOI ) vlrtunl void iUHICh(Wlridow&) . 0, /I c,llh Wltl»cl dcflt'l'~ . 11 k"I~1 /1 (Jill! .KIIU!1 (ur ,I wlnduw POlnllo(a Ittl width , Inl holShl ' ! lrlns lablllJ Cillibiltk doJt / prOICC:I\l t! 1 ) , Window· own , ill_Wldget - (JW I IlllVt'ty read more..

  • Page - 1195

    E. 3 WINDOW IM PLEMEN TATION its implementatio n using FLTK requ ires free store. As found in Wlndow.h, here It IS: cl lI.5!I Window I public ill Whldow { I)ublle: Illct the !y~tl'm plLk the IUL.l tIOI1: Wlndow(hH w, Int Ii , ( Onl l llltlng& IltltI) , IIlupldt LOlller In xy: WlndowWolnl ky, It" WI Inl hi ( 0". 1111,1118& tlll el)1 VI,IUill ... Wlndown read more..

  • Page - 1196

    " 66 APPENDIX E • CUI IM PLEMENTATION void Window: :detach(S hape& s) /I guess that the last anached will be first released { for (unsign ed int i = shapes.sil-eO; (kij -- i) if (shapes[i-l l==&s) sh a pes.erase(&shapes[i- l U; T he eraseO member function removes ("crases") a value fro m a vector, decreas- ing the vector's size by one (§20.7. read more..

  • Page - 1197

    E.S AN EXAMPLE: MANIPULATING WIDGETS consl T& o perator(](int i) canst ( return ·v[i); } int size() consl { re turn v.sizeO; } } ; Vector_rer's dCSlnlC10r de letes every object passed to it as a pointer. E.S An example: manipulating Widgets H ere is a complete program. It exercises many o f the WidgetJWindow fea tures. It is only minimally commented . Unfortunately, read more..

  • Page - 1198

    1168 } ; APPEND IX E • CUI IM PLEMENTATION Iitali c void cb~!ih(Atldrc8l, Addre.! add,) II c.lllb.ltks ( rctc rllnctUo<W7>(addr).lhOI ) I tAli c volll cb~n1V (Addrcjl, Addreu add,) ( fefcrtln CC_loc W 7>(addr). mv(); ) , Mtle void cb_cd (AddrciII, Addre" :uJdr ) «rdere" c_loc W7>(adtlr) .cd() ; ) j llltle void cb_nd(Addrc:u, AddrciJII :uldr) ( read more..

  • Page - 1199

    E.5 AN EXAMPLE : MAN IPULATING WIDG ET S } e lse ( pl->s hOWOj p2->hide(); } shJeft = !shJeft ; void W7:: mvO II move the button { } if (mv_le fO ( m vp ->mo ve(l oo,O); } e lse { mvp ->move(- loo,O); } mv_left = !mvJeft j void W7: :cd O /I de lete the button and create a new one { } cdp- >hide(); d e le te cdp j string la b = read more..

  • Page - 1200

    11 70 ad lell - lldJelll Inl maln O i W7 w(400,800, lI mulell); rei urn gul_ntaln OJ APPEN DI X E • CUI IMPLEMENTATION 111is program dcmonstrales the fundamental ways of adding and subtracting widgcLS lolfrom a window - or just appearing to. read more..

  • Page - 1201

    Glossary "Often, a f ew well-chosen words ar worth a thousand pictures." -Anonymous A glOJJdry is a brief explanation of words used in a text. TIlls is a rather shon glos- sary of the tenns we thought most essential, especially in lhe earlier stages of lcaming programming. The index and lhe "Terms" sections of the chapters might also help. A morc extensive read more..

  • Page - 1202

    1172 GLOSSARY application a program or a collection of program s that is considered an emily by its users. approximation something (e.g., a value or a design) tha t is d ose to the perfecl or ideal (val ue or design). Often an approximation is a resuit of trade-offs among ideals. argument a val ue passed to a function or a tem plate, in which it is accessed read more..

  • Page - 1203

    GLOSSARY declaratio n the specification of a name with its type in a program. d efinition a declaration of an emity that supplies all infomlation necessary to complete a program using the emilY. Simplified definition: a declaration that allocates memory. d erived class a class derived from one or more base classes. d esign an overall description of how a piece of software read more..

  • Page - 1204

    1174 GLOS SARY integer a whole number, such as 42 and - 99. interface a declaration or a set of declaratio ns specifying how a piece of code (such as a function or a class) can be called. invariant something that must be always tn le at a given point (or points) of a program; typically used to describe the state (SC I of values) of an object or t.he state read more..

  • Page - 1205

    GLOSSARY pointer (I) a value used to identify a typed object in memory ; (2) a variable holding such a value. post-condition a condition that must hold upon exit from a piece of codc, such as a function or a loop. pre-condition a condilion that must hold upon elllry into a piece of codc, such as a function or a loop. program code (possibly with associatcd data) read more..

  • Page - 1206

    1176 GLOSSARY style a set of techniques for programming leading to a consistent use of language features; sometimes used in a very restricted sense to refe r just to low-level rules for naming and appearance of code. subtype derived type; a type that has alIlhe propenies of a type and possibly more. supertype base type ; a type t.hat has a subset of the propertics o read more..

  • Page - 1207

    Bibliography Aho, Alfred v., Monica S. Lam, Ravi Sethi, an d J effrey D. Ullman. Compilers: P'll1cip/~J, 7'edllllf/UCS, {/lui roots, Second £Iilioll (usually called "TIle Dragon Book") . Addiso n-\Vcs]cy, 2007. ISBN 032 1547985. Andrews, Mike, and Jruncs A. Whittaker. How to Brmfl. Siftware: Fundional mul Srom"ty Test- ingo/"mh Applim/iQ1/J IIl1d fffb Servias. read more..

  • Page - 1208

    1178 81BlIOGRAPHY Hcnricson, Mats. and Erik Nyquist. huiustnal Sirmgth C++: Ruffs oml &rommnuulhans. Prentice Hall, 1996. ISBN 0 13 1209655. ISO/ lEG 9899: 1999. ProgrammuJg ulI/guagtJ - C. -nlc C standard. ISOIIEC 14 882:2003. Programming IAI'guogc; - C++. ll1c C++ standard. Kernighan, Brian W .. and DClUlis M. Ritchie. 'rnc C Programming Lallgtlagt. Premiec Hall. first edition, read more..

  • Page - 1209

    BIBLIOGRAP H Y Schwanz, Rand:al L., Tom Phoenix, :and Bria n D. Fay: Leamjllg Perl, roUl'II, Etlilion. O 'Reilly, 2005 . ISBN 0596 101058. ScOH. ~'Iiehacl L. Progrmnmjllg Lal/g/lagt Pragllwlia . Morgan Kaufmanll. 2000. ISBN 155860442 1. Sebesta. Robert W. O)//(('I"S 0/ /togrml/lI/jllg Languages, Sixth Et/j/jl)ll. Addison·\Veslc y, 2003. ISBN 032 1 193628. Shcphcrd, Simon. read more..

  • Page - 1210

    read more..

  • Page - 1211

    !. &t Not, 1050 I::. StY Not equal (inequality), 67, 1052, 1064 M ••• " . &tStri ng literal, 62 ::. &t Preprocessor dirccti,'es, 1090- 1091 S. &t End of line, 837, 1134 % . &. Output fonnat specifier, 1141 Remainder (modulo); 68 'Yo::. Sa Remainder and assign, 1053 &.&. Address of, 574, 1050 Bitwise logical opera tions (a nd), 917, 1052,1057 read more..

  • Page - 1212

    '182 -=. Set Move b;lekward, 1064 Subtract alld ass ib'll. 67, 1053, 1103 . (dot). &e Member access. 302, 592-593, 1050-1051 Reb'lJlar expression, 837, 11 33 ... (ellipsis). Sa Argumen ts (unchecked), 1068- 1069 Catch all exceptions, 150 I. Se .. Divide, 66, 1051 II. Sa Line comment, 45 / •... • ,. &e Block commcnt, 237 1=. & .. Di vide and assib'll, 67, read more..

  • Page - 1213

    INDEX A ii , append ftle mode, 11 40 \ a alen, charnclcr lilcral. 1043 a OOrl(), 11 49 ab$ (), absolUiC valuc, 879, 1137 compl ex. 88 1, 11 39 AbslrnCI classes. 487. 11 71 class hiernrchies, 503 creating. 487. 503- 50'1, 1080- 1081 Shape exa mple, 487-488 Abstracl·fir.it approadl to progranuning, 10 Abstraclion, 92-93. 11 71 level, ideals, 778-779 Access cOlllrol. 302, read more..

  • Page - 1214

    1184 Algorithms, ST1. (tOIl/iliUM ) mergeO, 728 merging sOl'lcd sequences, 728 mi n, 11 2 1 modifying sequence, 1114- 11 16 mutating sequence, 11 14- 1116 no nmodifying sequ ence, 1113- 1114 numerical. &t Algorithms, !lumeri- aU. pc mlll talions, 11 20 searchO. 763- 76,1 searching, 111 7- 111 8. &to (UJo fi nd O; fi ndjfO. sct, 111 8- 11 19 shumc. 111 5- IIJ 6 read more..

  • Page - 1215

    INDEX accessing clements, 628. 863-865 assignment, 633 associative. &1: Associative contain· ers. built-in, 718- 719 C -style strings, 633-634 copying, 632 dereferencing. 628 clement numbering, 627 initializ.ing, 582-583, 633-634 multidimensional, 859-861. 1065 palindrome example, 638-640 passing pointers to arrays, 905- 912 pointers to clements, 628-631 range checking, 628 subscripting II . read more..

  • Page - 1216

    1186 bad_aUoc exce ption. 1058 B.1lanced trees, 748-750 Base-2 number system (binary), 1042 Base-8 nu mber system (octal). 1041 - 1042 Base-IO logarithms, 879 number system (deci mal), 104 1- 1042 Base-I 6 number system (hexadecimal), 104 1- 1042 Base and member inilial izers, 3 10, 471, 543 Base classes, 485- 488, 496-499, 11 72 abstract classes, 487, 503-504, 1080-108 1 read more..

  • Page - 1217

    INDEX Block comment /* ... */, 237 Blue marginal alerts, 3 BNF (Backus-Naur) Fonn, 788, 793 Body, functions, 113 bool, 63 , 66-67, 1062 bit space, 917 biLS in memory, 78 C++ and C. 992, 1003, 1004 silt, 78 boolalpha. manipulator, 1129 Boolean conversions, 1055 Borland, 796 Bottom·up approach, 9, 776-777 Bounds error, 147 Branching, tes ting, 966- 968. See abo Conditional read more..

  • Page - 1218

    1188 C language (amlinlltd ) K&R. 802, 988- 989 linkage collventio n, 999 missing features. 99 1-993 C standard library C -s tylc st rings. 1145- 1146 header files, 1097 input/output. See C -stylc liD (sldio). memory, 1146- 11 47 C-sly le caSts, 1006-1007, 1051. 1058 C-sty lc: 110 (sidio) % , conversion specification, 11 4 1 conversion sf)(:cifiI:3tions, 1141 - 1143 file read more..

  • Page - 1219

    INDEX lexicaCcast example, 8 19 narrow_cast example. 15 1 reinterpre,-casl. 594 static cas!, 594 , 905, 1058 unrelated types, 594 CAT scans, 30 catch. 145, 1003 Catch all exceptions ... , 150 Catching exccptions, 144-150, 238- 240. 1087 cb_nexiO example. 544- 546 <cctype>, 1097. 11 3 1 edIO.879, 11 37 cerr, 149, 11 25, 114'1 <cerrno>, 1097 <dioal>, 1097 read more..

  • Page - 1220

    1190 co nst me mber functions, 325-326 constan ts , 325-326. &e abo const. copying, 321-322 helpe r functions , 326-328 imm u ta ble: vaiues, 325, 326 initial izing objects, 322-325 members. 326-328 mutable values, 326-328 public w. private, 302-304 sym bolic constants, d efi n ing, 32 1 uninitializcd variables. 322-325 C lass mem be rs, 30 1, 107 1 -> ( arrow), read more..

  • Page - 1221

    INDEX lexicogra phicaCcompare(), 1121 minimax algori t.luns. 11 20-1121 string. 8 15 three-way. 10 12 Compatibility. &e C++ and C. Compile-time errors. &e Errors, compile-time. Compiled languagcs, 47-48 Compilers. 48. 1172 compile· time errors. 51 conditional compilation, 1024- 1025 syllla.'I: checki.ng. 48-50 comp l, synonym for - , 1003, 1045 complex !=, nO( equal (inequality). read more..

  • Page - 1222

    1192 Consistency. ideals, 780 Console, as user interface, 540 Console inpu t/output, 540 Console window, displaying. 160 COoSI, 95-96 Sa also Constant ; SL1tic storage, sialic coosl. C++ and C , 992, 1020- 1021 C -sty le Strlngs, 1013-1014 class intcrfaces, 325-326 declarations, 260-261 initializing, 260 member fun ctions. 325-326. 1073 overloading o n, 626-627 passing arguments by, read more..

  • Page - 1223

    INDEX Co py constructors. 614-616, 620-624 copy_backward O, 1114 copy_if 0 .757 Copying, 6 13-6 19 arrays, 632 Cstyle strings, 1012-10 13, 101 5 class interfaces, 32 I -322 con t.tiners. I I I I I/O streams. 758-761 o bjects, 494-496 seque nces, 728, 757- 762 vector. 6 13-6 18, 1108- 1109 Correctness definition, 1172 ideals, 92-94, 775 importance:: of, 891-892 software, 34 read more..

  • Page - 1224

    1194 Debugging ((I}I!tillutd) CUb, 562-564 input data, J 64 invariants, 160-16 1 keeping it simple, 158 logic errors, 152- 154 matchin g paren theses, 159 nanlin g convc ntions, 158 post-conditio ns, 163- 164 pre-conditions. 161 - 163 process description, 156- 157 reporting errors, 157 stepping through code, 160 strin g literal tcnnination, 159 sys tema tic approach, 164- 165 read more..

  • Page - 1225

    INDEX Deri ved classes, 496. 1173 access conlfOL 501-502 base classes, 1078- 1079 inhelilll.nce, 1078- 1079 multiple inheritance, 1079 object layo ut, '~97-499 overview, 496-497, 1078-1079 priva te bases and membe rs, 50 1- 502 protected bases and members, 502 public bases and members, 502 specifying, 499 virtual functions , 1079- 1080 Design , 35. 174, 177, 1173 Design for read more..

  • Page - 1226

    ,,% Embedded systems (wlllillued) dynamiccasl, 894 error handling, 895-897 examples of. 888-890 exceptions, 894 fault tolerance, 892 fragmentation , 898, 899 free-store, 898-902 hard real time, 893 ideals, 894- 895 mainte nance, 891 mcmOly management, 902- 904 new operato r, 894 predictability, 893, 894 real-time constraints, 893 real-time response, 890 reliability, 890 resource leaks, read more..

  • Page - 1227

    INDEX SllJ (St:Uldard Template Library), 1098- 1100 tcsting for errors, 224-227 transiclll errors, 895-896 vector resource exceptions, 677 Error messages Sa a/.w I.'rroro ; Reponing errors; runtim e_error. exceptions, printing, 148- 149 templates, 661 writing your OWI\, 140 Errors, 1173 oS« al.w D<:bugging; T csting. classifying, 132 co mpile-time, 48-50, 132, 134- 135 detection ideal. read more..

  • Page - 1228

    11 98 Examples (continual) writing rues, 346-348 Z I P code detection, 828-836 c c)(ception>, 1097 Exceptions, 144- 148, 1086 Sa abc Error handl ing: Errors. bounds error, 147 C++ and C, 992 c .. tch, 145,238-240, 1087 cerr, 14 9 cou t, 149 d CSlniClors, 1088 embedded systems, 894 error messages, printing, 148- 149 exception, 150, 1099- 11 00 failure to catch, 15 1 read more..

  • Page - 1229

    IN DEX open(), 346 opening flies. Su Opening files. positioning in flies, 389 read ing. Su Reading fIIcs. writing. Sa Writing flies. Eles, 11 73 &ealJo Et c 110 . C++ and C , 1019-1020 opening and closing, C·sty[c lIO, 11 40-1 14 1 fi llO, 1116 Ell color cxamplc, 456-459, 492 fil CnO, 111 6 find O, 728-731 associativc containcr ol>cr,lIions, 1111 finding links, read more..

  • Page - 1230

    1200 Fortran language, 786-788 array indexing, 863 comp lel, 882 subscripting, 863 Forward declarations, 259 For-vard ilcrawrs, 722-723, 1103 fprintf() , 1017, 1141 Fragmclll.1Iion, embedded systems, 898, 899 free(), deallocate, 1009-1010, 1147 Free store (heap slOrage) allocltion, 578-579 C++ and C, 1009- 10 II deallocation, 584--586 delete, 584-586, 586-590 and dCSlruCIOf'S. Sa destructors. read more..

  • Page - 1231

    IND EX C<1.11 stack, 287 c:cpression() call exam ple, 284-287 function acti va tion record, 284 history of, 785 memory for. 577 pass by consl rdere nce, 273-276, 279-281 pass by lIon·consl reference, 279- 28 1 pass by rderence, 276-28 1 pass by value, 273, 279-28 1 recurs ive. 286 stack growth, 284-287. ~alJo Functio n activation record. temporary objects, 280 read more..

  • Page - 1232

    1202 Graphics (col/HI/ued ) See also Color; Graphics example ; Shape. display modeL 409-410 displaying, 472-475 drawing on screen, 419-420 encoding, 473 fIlling shapes, 427 fonnaLS, 473 geometric shapes, 423 G I F, 473-475 graphics libraries, 474-475 graphs, 422-423 images from files , 429-430 importance of, 408-409 j PEG, 473~475 line style, 427 loading from files, 429-430 screcn read more..

  • Page - 1233

    IND EX Graph example See also Grids. Ax is, 420--422 coordi nates, 422--423 drawing, 422- 123 points. labeling. 468- 469 grealer O, 1122 G reater thilll >, 67, 1052 Greater than or equal >=. 1052 greater_equaIO, 11 22 Green margi nal alerts, 3 Grids, drawing, 444- 445, 448-450 Grol'ping reglllar expressions, 831, 837, 840 Guaramees, 676- 678 GU I system, giving control read more..

  • Page - 1234

    1204 Hexadecimal numbe r system. 3 77- 379, 1041 - 1042 Hiding info rmation, 1173 Hopper. Grace Murray, 789- 790 Hyperbolic cosi ne, cosh(), 879 Hyperbolic sine, sinhO, 879 Hyperbolic tangent, lanh (), 879 I 1/0 errors badO stream state, 349 dear O, 349-352 end of file, 349 eoiO strea m state, 3 49 eITO r han dling. 1127 fai tO strea m state, 349 goodO stream read more..

  • Page - 1235

    INDEX ifslream type, 344-346 imagO , imaginary pan, 881 , 1139 Image example, 439, 472-475 Images. Set Graphics. Imaginary pan, 881 Immutable values, class interfaces, 325- 326 Implementation, 1173 class, 302-304 inheritance, 504-505 programs, 35 lmplementation·defined feature, 1039 Implicit conversions, 62 1-622 In·class member definition, 1074- 1075 in mode, 385, 11 26 In_box example, read more..

  • Page - 1236

    1206 Input (rontinud) a series o f values, 350-352 a si.ngle value, 352-357 source of exceptions, 148- 151 Slringslream, 390-39 1 tab character \ 1, 64 terminaring, 61 -62 type sensitivity, 64- 65 whi tespacc, 64 Input » , 6 1 case sensitivity, 64 complex, 881, 11 39 formatted input, 11 28 multiple valu es per statement, 65 strings, 815, 11 32 text input, 8 15, read more..

  • Page - 1237

    INDEX In variants, 309, 1174 Su abo PosHonditions; Pre-condi- tions. assert ions, 161 debugging, 160-161 dcCault construclOrs, 620 documenting, 780 Dale example, 309 invention of. 793 Polygon example, 455 Invisible. See Tra nsparency. <iomanip>, 1096, 1129 <ios> , 1096, 1129 <iosfwd >, 1096 iosl ream butTers, 402 C++ and C. 1016 exceptions, 1099 library, 341-343 read more..

  • Page - 1238

    1208 ker_type. 11 08 Key,value p.1 irs, cO lilainers fo r, 744 Keywo rds, 1003-1004, 1045- \046 KISS, 780 Knut h, Don, 774-775 K&R , 802, 988 l III suffix, 104 1 \ 1, " lowercase characte r," rege)(, 837, 11 35 \ l , " not lowe rc.1se.~ rege)(, 939, 1135 Label access control, 302, 502 caSC'. 104- \07 graph ex ample. 5 18-521 o f sta tement, read more..

  • Page - 1239

    INDEX inse rl O, 600~602 , 713-7 15 opera tions, 600-602 properties, 712-7 13 referencing last element, 708 sequence co ntaine rs, 1105 subscripting, 700 di sl>, 1095 Lists containers, 111 0 doubly linked. 598, 698 empty, 702 erasing clements, 713-715 examples, 598-600, 704-7 11 lindillg links, 600-602 getting the nth clemem, 600-602 inserting clements, 600-602, 713- 71 5 read more..

  • Page - 1240

    1210 Macros (continI/ell) naming conventions, 102 1 syntax, 1023-1024 uses for, 1021 Maddoc.J o h n, 830 Magic constan ts, 96, 141 ,23 1-233, 697 Magical appro.leh 10 programming. 10 ma inO, 46-47 arguments to, 1040 glo bal objects, 1040 return values. 47, 1039-1040 starling a p rogram , 103 9- 1040 Mailllainability, sofnvare, 34, 775 Ma intenance. 891 make_heap O. 11 19 read more..

  • Page - 1241

    IND EX Matriccs, 863- 865, 869 Malri x library cxample. 863-865, 869 0 , subscripting (Fonran style), 863 II , su bscripting (C style), 860, 863 accessing array clemcllls, 863- 865 appl yD, 867 broadcast functions, 867 dea rJow, 870 columns, 864-865, 870 dimensions, 862-865 dot product, 868 fused multiply-ad d, 868 initializing, 870 inner_product, 868 inputloUlpUl, 870-871 linear read more..

  • Page - 1242

    121 2 Menu example, 439, 55 1, 557-562 mcrgeO, 728, 1118 Messages to the user, 55 1 min O, 11 20- 11 2 1 min_clementO, 11 21 M inimalism, ideals, 780 Minus - . Sa Subu<{ction. minusO, 1123 Missi ng copies, 624 Mn~ 791 , 803 Modifying sequence algorithms, 1114- 1116 M odular systems, error hand ling, 896- 897 Modularity, ideals, 779- 780 Modulo (remainder) %, 66. read more..

  • Page - 1243

    INDEX Nested functions, 268 Nesting blocks within functions, 268-269 classes within classes, 268 classes within funcLions , 268 functions within classcs, 267 functions within functions, 268 indenting nested codc, 269 local classes, 268 local func tions, 268 member classes, 268 member funcLions , 267 slrucls, 1003 new, 578, 582 C ++ and C, 992 , 1003 and delete, 1057- 1058 read more..

  • Page - 1244

    1214 Numerics (amnll/I(ll ) ran dom numbers, 877- 879 real numbers, 855. Sa a1.w Hoating- poim. resul ts, plausibility checking, 855 rounding errors, 855 rows, 859 size, 854-858 sizeof{), 856 smallest imeb'C r, fmding, 879 srand{), seed random number gen· erato r, 878 standard mathematical fu nctions, 879- 880, 11 37- 11 38 lnlllcation, 857 vaiarray, 11 39 whole nu mbers. Sa read more..

  • Page - 1245

    INDEX & (binary) bilwiS(: and, 917, \05 2, 1057 && logical and, \052, \057 &= and and ass ign, 1053 % remainder (modu lo), 105 1 %= rema inder (modulo) and as - sign, \053 ° (binary) multiply, 105 1 ° ( unary) object COlllenlS, poillling to, \050 0= mul tiply and assign. 1053 + add (plus), 1051 ++ incn: melll, \050 += add and assign, \053 - subtract read more..

  • Page - 1246

    1216 Output « , 47, 67, 11 29 complex, 881 , 11 39 sIring, 81 5 text output, 8 15, 819 user-defined,357-359 Overflow, 854-858, 1174 Overloading, 1067- 1068, 1174 alterna ti ve to, 5 16 C++ and C , 992 on eo nsl, 626- 627 linkage, 138 operators. Set OperatOr overloading. and overriding 500 resolution, 1067-1068 Override, 500-50 1, 11 74 p Padding, C-style 110, 11 read more..

  • Page - 1247

    INDEX decrementing, 630 definition, 573- 574, 1175 dcleted, 636 ex plicit type conversion. Set Typc co nversion. to functions , 1000- 1002 incrementing, 630 initializing, 582-583, 635 !M. ilel'3tors, 110 1 literal (0),1044- 1045 10 local variables, 636- 637 moving around, 630 to nonexistent elcmellts, 635-636 null, 0, 583- 584, 634-635, 1044- 1045 NULL macro, 1144 lJJ. objects read more..

  • Page - 1248

    1218 Preprocessor din.:ctivcs : define, macro substitution, 1090- 109 1 :ifdef, 1024 :ifndef, 1025 tinclude, including headers, 1090- 1091 Pn::: proccsso r, 1090 codi ng standa rds, 939 prev_permutation(), 11 20 Princeton U niversity, 803 print, chamcter class, 842, 1134 Pri ntable chamcters, idemifying. 393 printfO family % , conversion spc:cific.ation, 1141 conversion spc:cificatlons, 11 read more..

  • Page - 1249

    INDE X COBOL, 788-790 Commo n Lisp, 790 Delphi. 796 Fo rtran , 786- 788 Lisp. 790-791 Pascal, 794-796 Scheme, 790 Simula. 798-800 Turbo Pascal. 796 Programming philosophy, 772- 773, 1175. Set aLso C++ programs; Program- ming idcals; Programming lan- guages. Programmin g ideals abstraClion level, 778- 779 aims_ 772- 774 bOllom-up approach, 776-777 code structure, 776 consistency, 780 read more..

  • Page - 1250

    1220 Promotions, 98-99, 1054-1055 Prompting ror input, 6 1 >, input prompt, 221 calculator example, 177 sample code, 220-223 Proofs, testing, 952 protec ted, 484-485, 496, 502, 1003 Prototyping, 176 Pseudo code, 177, 1175 Public, 302, 1003 base class, 500-501 interface, 208, 488-49 1 membe r, 302 public by default, shu et, 303 public: label, 302 punc t, punctuation character read more..

  • Page - 1251

    INDEX <I se ries of values, 350-352 a single value, 352- 357 into Slrings, 815 tokens, 183- 184 Reading flies binary 110, 387 convening n:presentalions, 368- 370 to end of file, 360 exa mple. 34 6-348 fstrea m type. 344-346 ifstream typ<:, 344- 346 in-memory reprcsema tion, 362- 364 input loops, 359- 361 iSlream type. 343-348, 387 oslrea m type, 387 process steps, read more..

  • Page - 1252

    222 regcx pattem matching «(()1!tilUl((I) pattem matching, 836-837 ranges, 841 - 842 regcl_rnatchO, 1133 regex_scarchO, 11 33 repe aling patterns, 838-840 searchin g with, 833-836. 844 smatch,834 special characters . ..s:a- regc .. ope ra· tors. sub'paucms. 83 1, 834 regex operators, 837, 11 33- 1134 regex characte r classes, 84 1-842 alnum, 842 alpha. 842 blank, 842 enlrl, read more..

  • Page - 1253

    INDEX guarantees, 676-678 make_vecO, 677 no·throw b'u:tr.tntee, 677 problems, 673- 675 RAi l, 675-676, 678- 680 resources, examples, 672-673 strong guarantee, 677 tcsting, 964- 965 Results, 91 . Sn flUo Return valucs. rl.'t urn statemem, 271 - 272 Return types, functions, 47, 270- 27 1 Return values, 11 2 fUlletions, 1066 110 return value, voi d, 2 10 omitting. 11 3 read more..

  • Page - 1254

    122' Screens Sa abo GU ls (graphical user inter· faces). data graph layout. 530-531 drawing on, 419-420 labeling, 421 searrn O. 763-764 , 111 3 Searching Sa also find O; find_if 0 ; Hnding; Matching. algorithms for, 11 17- 111 8 b inary searches, 747, 763-764 in C , 1149 fo r characters, 711 (kcy, valuc) pairs. by key. & ( Asso- ciativc containers. for links, read more..

  • Page - 1255

    INDEX Simula language, 798-800 sin O, sine, 879, 11 37 Singly-linked lists, 598, 698 sinhO, hyperbolic sine, 879, 11 37 Size bit stri ngs, 916- 917 contai ners, litO- III I getting, sizeofO, 576-577 of numbers, 854-858 veclors, gc ttin g, 11 8- 1 I9 sizeO containcr capacity, IIII number of clcments, 118, 815 stringlcngth, 815, 11 32 veclors, 118, 121 sizeofO, 576-577, read more..

  • Page - 1256

    1226 Standard library (col/tinlled ) function objects. See Function ob- jccts. 110 strmlllS. St:t Input; Input/output; Output. ilcrators. See lter-HOrs. mathematical functions . .S« Mathe· matical fu nctio ns (s tandard). nume rical algorithms. Sa Algo- rillullS (numerical); Numerics. stri ng. Sa string. lime, 982-983, 1147-1149 valarray. &e va la rray. Standard library header files , read more..

  • Page - 1257

    INDEX iterators. Set STL iterators. names p:lce, sid, 1098 STL algorithms, 11 12-1121 &e Al gorithms (STL). alternati\'es to, 1150 built·in arrays, 718-7 19 computation UJ. data, 691 - 693 heap, 111 9- 11 20 max O. 1120- 11 21 min O, 1120- 1121 modifying sequence. 1114- 1116 mutating SC(llience, 1114- 1116 nonmodifying sequence. 111 3- 11 14 pcnnutations, 11 20 searching, read more..

  • Page - 1258

    1228 string (amtinutd) C++ to C Slyle conversion, 815 c_slrO. C++ to Cstylc COllversion. 345, S15 eraseO, removi ng characters, SIS exceptions, 1099 findO . SIS from_s lringO, S17-S18 ge tlineO. SIS input temlinator (whitesp.lce), 65 InserlO, adding characters, SIS lenglhO, number of characters, SIS lexicaCcast example, S I9 literals, debugging, 159 operations, SIS, 11 32 operators, read more..

  • Page - 1259

    IND EX nse labels, 104-107 most comlllon erro r, 107 Uf. str ing·based s election, 105 Symbol tables, 246 Symbolic COnStantS 5« also Enumcrations. clcaning up, 23 1- 233 defining, wiLh slatic consl, 32 1 Symbolic names, tokens, 232 S),mbolic rcpresentations, read ing, 368- 370 Syntax analyzers, 188 Syntax checking, 48-50 Syntax errors examples, 48-50 overview, 135-136 repo ning. read more..

  • Page - 1260

    '23{) Testing (conhium:l) ~grcss ion tests, 953 rcsoura: manageme nt, 964-965 reso urces, 962 stage of programming, 35 Slate, 96 1 system tests, 969- 973 tCSt cases, definitio n, 164 leSt ha rness, 957-959 liming, 98 1-983 wh ite box, 952-953 l ating units fomlai specification, 954-955 ran dom sequences, 959-96 1 stra tegy for, 955- 957 sys tematic tcsting, 954- 955 test read more..

  • Page - 1261

    INDEX siring to valuc, 817-818 tnlllcation, 82 valuc to string, 816 -rypc conversion, implicit, 621-622 bool, 1055 compiler warnings, 1055- 1056 fioating-poilll and illlcgral, 1055 illlegral promotion, 1054- 1055 pointcr and refcrcncc, 1055 preserving values, 1054- 1055 prolllOlions, 1054- 1055 user-dcfincd, 1056 usual arithmetic, 1056 "lyPc safety, 78- 79 implicit convcrsions, 80-83 read more..

  • Page - 1262

    1232 Unsafe conve rsio ns, 80-83 un5elfO, 380 Unsigned and signed, 922-926 unsigned type , 1062 Unspecified co nstructs, 1039 upper, character class, 842, 11 34 upper_boundO, 764,1112, 1117 U ppercase. S« Case. uppercaS4', 1129 U.S. Depa rtment of Defense, 796 U.S. Navy, 789-790 Usc cases, 177, 1176 User-defined conversions, 1056 User·defined ope rators, 1054 U ser·defi ned types read more..

  • Page - 1263

    IND EX insertO (addingcleme ms), 715-7 18 ovcrloadin g on consl, 626- 627 push_bacKO , 652- 653, 667 representa tion, 650-65 1 reset'\-'e(), 65 1, 667, 679- 680 resizeO, 652, 668 subscri pti ng, 579- 580, 592- 593, 625-626 veclor, stan dard library, 1107- 1111 < l css than, I I 1 1 = assign ment, 1109 == c(lualit}', 1111 II subscripting, 1109 assignO, 1109 al O, read more..

  • Page - 1264

    234 vVhitcspacc (contilllled) idcmifying, 393 in inpUl, 64 Siring, 8 18-819 ws, manipulator, 1130 Widget example, 548-549 Bullon, 4 18-420, 54 1-550 contTOI inversio n , 556-557 debugging, 563-564 hideO,549 implementation, 1163- 1164 In_box-O,550-55 1 line drawing example, 552-556 Menu , 55 1, 557-562 move O, 549 OU I_boxO, 550-55 1 put_on_topO,1165 showo,549 technical example, 1167- read more..

  • Page - 1265

    Page 14. Page 15. Page 26. Page 26. Page 26. Page 26. Page 28. Page 28. Page 29. Page 29. Page 30. Page 30. I~ ge 3 1. I~ge 31. I~ge 33. I~ge 785. Page 785. Photo Citations and Credits Photo of Bjame StrouStrup, 2005. Source : Bja m e StrouStrup. Photo of Lawrence '" Pete" Petersen, 2006. Source: Dept. of Computer Science, Texas A&1I'1 University. read more..

  • Page - 1266

    1236 Page 787. P-J.gc 789. Page 790. Page 791. Page 79 1. Page 792. Page 792. P"dgC 793. Page 795. Page 795. P"dgC 797. Page 797. Page 799. Page 800. Page 800. Page 80 1. Page 80 1. Page 802. P"dgC 802. Page 804. Page 805. P-dgC 989. PHOTO CI TATION S AND CREDITS John Backus 1996. Copyright: Louis Fabian Bachrach. For a collection orpha- togra phs read more..

  • Page - 1267

    read more..

  • Page - 1268

    An Introduction to Programming by the Irwentor oj C++ .:. Pre/)(lralion for Programming ill the Real fYorLd T ne book assumes th at you ai m c\'c ntu<l Uy co ",rill: non- tr ivia l program$, whether for work in ~fIW.ln· no'dopn~nl Or ill $OfTlC oth er lcdlll ica l field . . :. Focus on FundamentaL Concepts and Techlliques 'f he book expla in s read more..

Write Your Review