CS106BX Reader

Download CS106BX Reader

Post on 20-Nov-2014




1 download

Embed Size (px)


<p>Programming Abstractions in C++Eric S. Roberts and Julie ZelenskiThis course reader has had an interesting evolutionary history that in some ways mirrors the genesis of the C++ language itself. Just as Bjarne Stroustups first version of C++ was implemented on top of a C language base, this reader began its life as Eric Robertss textbook Programming Abstractions in C (Addison-Wesley, 1998). In 2002-03, Julie Zelenski updated it for use with the C++ programming language, which we began using in CS106B and CS106X during that year. Although the revised text worked fairly well at the outset, CS106B and CS106X have evolved in recent years so that their structure no longer tracks the organization of the book. This year, were engaged in the process of rewriting the book so that students in these courses can use it as both a tutorial and a reference. As always, that process takes a considerable amount to time, and there are likely to be some problems as we update the reader. At the same time, were convinced that the material in CS106B and CS106X is tremendously exciting and will be able to carry us through a quarter or two of instability, and we will end up with an even better course in the future. We want to thank our colleagues at Stanford, several generations of section leaders (with special thanks to Dan Bentley and Keith Schwarz), and so many students over the yearsall of whom have helped make it so exciting to teach this wonderful material.</p> <p>Programming Abstractions in C++Chapter 1. An Overview of C++ 11.1 What is C++? 2 The object-oriented paradigm; The compilation process 1.2 The structure of a C++ program 5 Comments; Library inclusions; Program-level definitions; Function prototypes; The main program; Function definitions 1.3 Variables, values, and types 9 Naming conventions; Local and global variables; The concept of a data type; Integer types; Floating-point types; Text types; Boolean type; Simple input and output 1.4 Expressions 16 Precedence and associativity; Mixing types in an expression; Integer division and the remainder operator; Type casts; The assignment operator; Increment and decrement operators; Boolean operators 1.5 Statements 24 Simple statements; Blocks; The if statement; The switch statement; The while statement; The for statement 1.6 Functions 32 Returning results from functions; Function definitions and prototypes; The mechanics of the function-calling process; Passing parameters by reference Summary 38 Review questions 39 Programming exercises 41</p> <p>Chapter 2. Data Types in C++ 452.1 Enumeration types 46 Internal representation of enumeration types; Scalar types 2.2 Data and memory 49 Bits; bytes; and words; Memory addresses 2.3 Pointers 51 Using addresses as data values; Declaring pointer variables; The fundamental pointer operations 2.4 Arrays 56 Array declaration; Array selection; Effective and allocated sizes; Initialization of arrays; Multidimensional arrays 2.5 Pointers and arrays 64 The relationship between pointers and arrays 2.6 Records 67 Defining a new structure type; Declaring structure variables; Record selection; Initializing records; Pointers to records 2.7 Dynamic allocation 71 Coping with memory limitations; Dynamic arrays; Dynamic records ii</p> <p>Summary 74 Review questions 74 Programming exercises 77</p> <p>Chapter 3. Libraries and Interfaces 853.1 The concept of an interface 86 Interfaces and implementations; Packages and abstractions; Principles of good interface design 3.2 A random number interface 89 The structure of the random.h interface; Constructing a client program; The ANSI functions for random numbers; The random.cpp implementation 3.3 Strings 98 The data type string; Operations on the string type ; The strutils.h interface; An aside about C-style strings 3.4 Standard I/O and file streams 105 Data files; Using file streams in C++; Standard streams; Formatted stream output; Formatted stream input; Single character I/O; Rereading characters from an input file; Line-oriented I/O 3.5 Other ANSI libraries 112 Summary 113 Review questions 113 Programming exercises 116</p> <p>Chapter 4. Using Abstract Data Types 1234.1 The Vector class 125 Specifying the base type of a Vector; Declaring a new Vector object; Operations on the Vector class; Iterating through the elements of a Vector; Passing a Vector as a parameter 4.2 The Grid class 131 4.3 The Stack class 133 The structure of the Stack class 4.4 The Queue class 136 Simulations and models; The waiting-line model; Discrete time; Events in simulated time; Implementing the simulation 4.5 The Map class 146 The structure of the Map class; Using maps in an application; Maps as associative arrays 4.6 The Lexicon class 151 The structure of the Lexicon class; A simple application of the Lexicon class; Why are lexicons useful if maps already exist 4.7 The Scanner class 154 Setting scanner options 4.8 Iterators 156 The standard iterator pattern; Iteration order; A simple iterator example; Computing word frequencies iii</p> <p>Summary 163 Review questions 164 Programming exercises 165</p> <p>Chapter 5. Introduction to recursion 1735.1 A simple example of recursion 174 5.2 The factorial function 176 The recursive formulation of Fact; Tracing the recursive process; The recursive leap of faith 5.3 The Fibonacci function 181 Computing terms in the Fibonacci sequence; Gaining confidence in the recursive implementation; Recursion is not to blame 5.4 Other examples of recursion 187 Detecting palindromes; Binary search; Mutual recursion 5.5 Thinking recursively 192 Maintaining a holistic perspective; Avoiding the common pitfalls Summary 194 Review questions 195 Programming exercises 197</p> <p>Chapter 6. Recursive procedures 2016.1 The Tower of Hanoi 202 Framing the problem; Finding a recursive strategy; Validating the strategy; Coding the solution; Tracing the recursive process 6.2 Generating permutations 211 The recursive insight 6.3 Graphical applications of recursion 213 The graphics library; An example from computer art; Fractals Summary 224 Review questions 225 Programming exercises 226</p> <p>Chapter 7. Backtracking algorithms 2357.1 Solving a maze by recursive backtracking 236 The right-hand rule; Finding a recursive approach; Identifying the simple cases; Coding the maze solution algorithm; Convincing yourself that the solution works 7.2 Backtracking and games 245 The game of nim; A generalized program for two-player games; The minimax strategy; Implementing the minimax algorithm; Using the general strategy to solve a specific game Summary 269 Review questions 270 Programming exercises 271</p> <p>iv</p> <p>Chapter 8. Algorithmic analysis 2778.1 The sorting problem 278 The selection sort algorithm; Empirical measurements of performance; Analyzing the performance of selection sort 8.2 Computational complexity and big-O notation 282 Big-O notation; Standard simplifications of big-O; Predicting computational complexity from code structure; Worst-case versus average-case complexity; A formal definition of big-O 8.3 Recursion to the rescue 288 The power of divide-and-conquer strategies; Merging two vectors; The merge sort algorithm; The computational complexity of merge sort; Comparing N 2 and N log N performance 8.4 Standard complexity classes 294 8.5 The Quicksort algorithm 296 Partitioning the vector; Analyzing the performance of Quicksort 8.6 Mathematical induction 301 Summary 304 Review questions 305 Programming exercises 307</p> <p>Chapter 9. Classes and objects 3139.1 A simple example of a class definition 314 Defining a Point class; Implementing methods in a class; Constructors and destructors; The keyword this 9.2 Implementing a specialized version of the Stack class 319 Defining the CharStack interface; Representing the stack data; The advantages of object encapsulation; Removing the maximum size limitation; Object copying 9.3 Implementing the Scanner class 328 Summary 328 Review questions 334 Programming exercises 335</p> <p>Chapter 10. Efficiency and Data Representation 33910.1 The concept of an editor buffer 340 10.2 Defining the buffer abstraction 341 The public interface of the EditorBuffer class; Coding the editor application 10.3 Implementing the editor using arrays 345 Defining the private data representation; Implementing the buffer operations; Assessing the computational complexity of the array implementation 10.4 Implementing the editor using stacks 352 Defining the private data representation for the stack-based buffer; Implementing the buffer operations; Comparing computational complexities</p> <p>v</p> <p>10.5 Implementing the editor using linked lists 357 The concept of a linked list; Designing a linked-list data structure; Using a linked list to represent the buffer; Insertion into a linked-list buffer; Deletion in a linkedlist buffer; Cursor motion in the linked-list representation; Linked-list idioms; Completing the buffer implementation; Computational complexity of the linkedlist buffer; Doubly linked lists; Time-space tradeoffs Summary 371 Review questions 372 Programming exercises 373</p> <p>Chapter 11. Linear Structures 38111.1 Reimplementing stacks as a template class 382 The interface of a class template 11.2 Reimplementing stacks using linked lists 383 11.3 Implementing queues 391 An array-based implementation of queues; Linked-list representation of queues 11.4 Implementing vectors 404 Supporting insertion and deletion at arbitrary index positions; Implementing selection brackets; Implementing iterators Summary 414 Review questions 415 Programming exercises 416</p> <p>Chapter 12. Implementing Maps 41912.1 An array-based implementation of the map interface 420 12.2 The advantage of knowing where to look 427 12.3 Hashing 429 Implementing the hash table strategy; Choosing a hash function; Determining the number of buckets; Using the typename keyword 12.4 Functions as data 438 A general plotting function; Declaring pointers to functions and function typedefs; Implementing Plot; A generic sorting function 12.5 Mapping functions 444 Mapping over entries in a map; Implementing mapAll; Passing client information to a callback function; A note on function types and methods Summary 448 Review questions 449 Programming exercises 450</p> <p>Chapter 13. Trees 45513.1 Family trees 456 Terminology used to describe trees; The recursive nature of a tree; Representing family trees in C++</p> <p>vi</p> <p>13.2 Binary search trees 459 The underlying motivation for using binary search trees; Finding nodes in a binary search tree; Inserting new nodes in a binary search tree; Tree traversals 13.3 Balanced trees 466 Tree-balancing strategies; Illustrating the AVL idea; Single rotations; Double rotations; Implementing the AVL algorithm 13.4 Defining a general interface for binary search trees 477 Allowing the client to define the node data; Generalizing the types used for keys; Removing nodes; Implementing the binary search tree package; Implementing the map.h interface using binary trees; Using the static keyword Summary 488 Review questions 489 Programming exercises 492</p> <p>Chapter 14. Expression Trees 49914.1 Overview of the interpreter 500 14.2 Understanding the abstract structure of expressions 505 A recursive definition of expressions; Expression trees 14.3 Class hierarchies and inheritance 509 14.4 Defining an inheritance hierarchy for expressions 510 Defining the interface for the expression subclasses 14.5 Implementing the node classes 518 Implementing the methods 14.6 Parsing an expression 522 Parsing and grammars; Parsing without precedence; Adding precedence to the parser Summary 528 Review questions 528 Programming exercises 530</p> <p>Chapter 15. Sets 53515.1 Sets as a mathematical abstraction 536 Membership; Set operations; Identities on sets 15.2 Designing a set interface 539 Defining the element type; Writing the set interface; Character sets; Using sets to avoid duplication 15.3 Implementing the set class 544 15.4 Enhancing the efficiency of integer sets 548 Characteristic vectors; Packed arrays of bits; Bitwise operators; Implementing characteristic vectors using the bitwise operators; Implementing the high-level set operations; Using a hybrid implementation Summary 555 Review questions 556 Programming exercises 558</p> <p>vii</p> <p>Chapter 16. Graphs 56316.1 The structure of a graph 564 Directed and undirected graphs; Paths and cycles; Connectivity 16.2 Implementation strategies for graphs 568 Representing connections using an adjacency list; Representing connections using an adjacency matrix; Representing connections using a set of arcs 16.3 Designing a low-level graph abstraction 571 Using the low-level graph.h interface 16.4 Graph traversals 575 Depth-first search; Breadth-first search 16.5 Defining a Graph class 580 Using classes for graphs, nodes, and arcs; Adopting an intermediate strategy 16.6 Finding minimum paths 589 16.7 An efficient implementation of priority queues 593 Summary 596 Review questions 597 Programming exercises 599</p> <p>Appendix A. Library Interfaces 607bst.h cmpfn.h extgraph.h genlib.h graph.h graphics.h grid.h lexicon.h map.h queue.h random.h scanner.h set.h simpio.h sound.h stack.h strutils.h vector.h</p> <p>608 611 612 622 623 627 630 634 638 642 644 646 652 656 657 658 660 662</p> <p>Index 657</p> <p>viii</p> <p>Chapter 1 An Overview of C++</p> <p>Out of these various experiments come programs. This is our experience: programs do not come out of the minds of one person or two people such as ourselves, but out of dayto-day work. Stokely Carmichael and Charles V. Hamilton, Black Power, 1967</p> <p>An Overview of C++</p> <p>2</p> <p>In Lewis Carrolls Alices Adventures in Wonderland, the King asks the White Rabbit to begin at the beginning and go on till you come to the end: then stop. Good advice, but only if youre starting from the beginning. This book is designed for a second course in computer science and therefore assumes that you have already begun your study of programming. At the same time, because first courses vary considerably in what they cover, it is difficult to rely on any specific material. Some of you, for example, will already have experience programming in C or C++. Many of you, however, are coming from a first course taught in some other language. Because of this wide disparity in background, the best approach is to adopt the Kings advice and begin at the beginning. The first three chapters in this text therefore move quickly through the material I consider to be essential background for the later chapters. Chapters 1 and 2 discuss C++ in general and may be skimmed if youve had experience with C++. Chapter 3 discusses standard interfaces and some interfaces particular to this text. By the end of these three chapters, you will be up to speed on the fundamentals of C++ programming. In the early days of computing, programs were written in machine language, which consists of the primitive instructions that can be executed directly by the machine. Machine-language programs are difficult to understand, mostly because the structure of machine language reflects the design of the...</p>