Sunday, May 18, 2008

C++ - How To Program, 5th Edition (2005)

Tour of the Book


In this section, we take a tour of the many capabilities of C++ you will study in C++ How to Program, 5/e. Figure 1 illustrates the dependencies among the chapters. We recommend studying these topics in the order indicated by the arrows, though other orders are possible. This book is widely used in all levels of C++ programming courses. Search the Web for "syllabus," "C++" and "Deitel" to find syllabi used with recent editions of this book.

Chapter 1
Introduction to Computers, the Internet and World Wide Webdiscusses what computers are, how they work and how they are programmed. The chapter gives a brief history of the development of programming languages from machine languages to assembly languages and high-level languages. The origin of the C++ programming language is discussed. Our free Dive-Into™ Series publications for other platforms are available at www.deitel.com/books/downloads.html. The chapter includes an introduction to a typical C++ programming environment. We walk readers through a "test drive" of a typical C++ application on Windows and Linux platforms. This chapter also introduces basic object technology concepts and terminology and the Unified Modeling Language.

Chapter 2
Introduction to C++ Programmingprovides a lightweight introduction to programming applications in the C++ programming language. The chapter introduces nonprogrammers to basic programming concepts and constructs. The programs in this chapter illustrate how to display data on the screen and how to obtain data from the user at the keyboard. Chapter 2 ends with detailed treatments of decision making and arithmetic operations.

Chapter 3
Introduction to Classes and Objectsis the "featured" chapter for the new edition. It provides a friendly early introduction to classes and objects. Carefully developed and completely new in this edition, Chapter 3 gets students working with object orientation comfortably from the start. It was developed with the guidance of a distinguished team of industry and academic reviewers. We introduce classes, objects, member functions, constructors and data members using a series of simple real-world examples. We develop a well-engineered framework for organizing object-oriented programs in C++. First, we motivate the notion of classes with a simple example. Then we present a carefully paced sequence of seven complete working programs to demonstrate creating and using your own classes. These examples begin our integrated case study on developing a grade-book class that instructors can use to maintain student test scores. This case study is enhanced over the next several chapters, culminating with the version presented in Chapter 7, Arrays and Vectors. The GradeBook class case study describes how to define a class and how to use it to create an object. The case study discusses how to declare and define member functions to implement the class's behaviors, how to declare data members to implement the class's attributes and how to call an object's member functions to make them perform their tasks. We introduce C++ Standard Library class string and create string objects to store the name of the course that a GradeBook object represents. Chapter 3 explains the differences between data members of a class and local variables of a function and how to use a constructor to ensure that an object's data is initialized when the object is created. We show how to promote software reusability by separating a class definition from the client code (e.g., function main) that uses the class. We also introduce another fundamental principle of good software engineeringseparating interface from implementation. The chapter includes a detailed diagram and discussion explaining the compilation and linking process that produces an executable application.


Chapter 4
Control Statements: Part 1focuses on the program-development process involved in creating useful classes. The chapter discusses how to take a problem statement and develop a working C++ program from it, including performing intermediate steps in pseudocode. The chapter introduces some simple control statements for decision making (if and if...else) and repetition (while). We examine counter-controlled and sentinel-controlled repetition using the GradeBook class from Chapter 3, and introduce C++'s increment, decrement and assignment operators. The chapter includes two enhanced versions of the GradeBook class, each based on Chapter 3's final version. These versions each include a member function that uses control statements to calculate the average of a set of student grades. In the first version, the member function uses counter-controlled repetition to input 10 student grades from the user, then determines the average grade. In the second version, the member function uses sentinel-controlled repetition to input an arbitrary number of grades from the user, then calculates the average of the grades that were entered. The chapter uses simple UML activity diagrams to show the flow of control through each of the control statements.

Chapter 5
Control Statements: Part 2continues the discussion of C++ control statements with examples of the for repetition statement, the do...while repetition statement, the switch selection statement, the break statement and the continue statement. We create an enhanced version of class GradeBook that uses a switch statement to count the number of A, B, C, D and F grades entered by the user. This version uses sentinel-controlled repetition to input the grades. While reading the grades from the user, a member function modifies data members that keep track of the count of grades in each letter grade category. Another member function of the class then uses these data members to display a summary report based on the grades entered. The chapter includes a discussion of logical operators.

Chapter 6
Functions and an Introduction to Recursiontakes a deeper look inside objects and their member functions. We discuss C++ Standard-Library functions and examine more closely how students can build their own functions. The techniques presented in Chapter 6 are essential to the production of properly organized programs, especially the kinds of larger programs and software that system programmers and application programmers are likely to develop in real-world applications. The "divide and conquer" strategy is presented as an effective means for solving complex problems by dividing them into simpler interacting components. The chapter's first example continues the GradeBook class case study with an example of a function with multiple parameters. Students will enjoy the chapter's treatment of random numbers and simulation, and the discussion of the dice game of craps, which makes elegant use of control statements. The chapter discusses the so-called "C++ enhancements to C," including inline functions, reference parameters, default arguments, the unary scope resolution operator, function overloading and function templates. We also present C++'s call-by-value and call-by-reference capabilities. The header files table introduces many of the header files that the reader will use throughout the book. In this new edition, we provide a detailed discussion (with illustrations) of the function call stack and activation records to explain how C++ is able to keep track of which function is currently executing, how automatic variables of functions are maintained in memory and how a function knows where to return after it completes execution. The chapter then offers a solid introduction to recursion and includes a table summarizing the recursion examples and exercises distributed throughout the remainder of the book. Some texts leave recursion for a chapter late in the book; we feel this topic is best covered gradually throughout the text. The extensive collection of exercises at the end of the chapter includes several classic recursion problems, including the Towers of Hanoi.


Chapter 7
Arrays and Vectorsexplains how to process lists and tables of values. We discuss the structuring of data in arrays of data items of the same type and demonstrate how arrays facilitate the tasks performed by objects. The early parts of this chapter use C-style, pointer-based arrays, which, as you will see in Chapter 8, are really pointers to the array contents in memory. We then present arrays as full-fledged objects in the last section of the chapter, where we introduce the C++ Standard Library vector class templatea robust array data structure. The chapter presents numerous examples of both one-dimensional arrays and two-dimensional arrays. Examples in the chapter investigate various common array manipulations, printing bar charts, sorting data and passing arrays to functions. The chapter includes the final two GradeBook case study sections, in which we use arrays to store student grades for the duration of a program's execution. Previous versions of the class process a set of grades entered by the user, but do not maintain the individual grade values in data members of the class. In this chapter, we use arrays to enable an object of the GradeBook class to maintain a set of grades in memory, thus eliminating the need to repeatedly input the same set of grades. The first version of the class stores the grades in a one-dimensional array and can produce a report containing the average of the grades, the minimum and maximum grades and a bar chart representing the grade distribution. The second version (i.e., the final version in the case study) uses a two-dimensional array to store the grades of a number of students on multiple exams in a semester. This version can calculate each student's semester average, as well as the minimum and maximum grades across all grades received for the semester. The class also produces a bar chart displaying the overall grade distribution for the semester. Another key feature of this chapter is the discussion of elementary sorting and searching techniques. The end-of-chapter exercises include a variety of interesting and challenging problems, such as improved sorting techniques, the design of a simple airline reservations system, an introduction to the concept of turtle graphics (made famous in the LOGO language) and the Knight's Tour and Eight Queens problems that introduce the notion of heuristic programming widely employed in the field of artificial intelligence. The exercises conclude with many recursion problems including selection sort, palindromes, linear search, the Eight Queens, printing an array, printing a string backwards and finding the minimum value in an array.

Chapter 8
Pointers and Pointer-Based Stringspresents one of the most powerful features of the C++ languagepointers. The chapter provides detailed explanations of pointer operators, call by reference, pointer expressions, pointer arithmetic, the relationship between pointers and arrays, arrays of pointers and pointers to functions. We demonstrate how to use const with pointers to enforce the principle of least privilege to build more robust software. We also introduce and using the sizeof operator to determine the size of a data type or data items in bytes during program compilation. There is an intimate relationship between pointers, arrays and C-style strings in C++, so we introduce basic C-style string-manipulation concepts and discuss some of the most popular C-style string-handling functions, such as getline (input a line of text), strcpy and strncpy (copy a string), strcat and strncat (concatenate two strings), strcmp and strncmp (compare two strings), strtok ("tokenize" a string into its pieces) and strlen (return the length of a string). In this new edition, we use string objects (introduced in Chapter 3) in place of C-style, char * pointer-based strings wherever possible. However, we include char * strings in Chapter 8 to help the reader master pointers and prepare for the professional world in which the reader will see a great deal of C legacy code that has been implemented over the last three decades. Thus, the reader will become familiar with the two most prevalent methods of creating and manipulating strings in C++. Many people find that the topic of pointers is, by far, the most difficult part of an introductory programming course. In C and "raw C++" arrays and strings are pointers to array and string contents in memory (even function names are pointers). Studying this chapter carefully should reward you with a deep understanding of pointers. The chapter is loaded with challenging exercises. The chapter exercises include a simulation of the classic race between the tortoise and the hare, card-shuffling and dealing algorithms, recursive quicksort and recursive maze traversals. A special section entitled Building Your Own Computer also is included. This section explains machine-language programming and proceeds with a project involving the design and implementation of a computer simulator that leads the student to write and run machine-language programs. This unique feature of the text will be especially useful to the reader who wants to understand how computers really work. Our students enjoy this project and often implement substantial enhancements, many of which are suggested in the exercises. A second special section includes challenging string-manipulation exercises related to text analysis, word processing, printing dates in various formats, check protection, writing the word equivalent of a check amount, Morse Code and metric-to-English conversions.

Chapter 9
Classes: A Deeper Look, Part 1continues our discussion of object-oriented programming. This chapter uses a rich Time class case study to illustrate accessing class members, separating interface from implementation, using access functions and utility functions, initializing objects with constructors, destroying objects with destructors, assignment by default memberwise copy and software reusability. Students learn the order in which constructors and destructors are called during the lifetime of an object. A modification of the Time case study demonstrates the problems that can occur when a member function returns a reference to a private data member, which breaks the encapsulation of the class. The chapter exercises challenge the student to develop classes for times, dates, rectangles and playing tic-tac-toe. Students generally enjoy game-playing programs. Mathematically inclined readers will enjoy the exercises on creating class Complex (for complex numbers), class Rational (for rational numbers) and class HugeInteger (for arbitrarily large integers).

Chapter 10
Classes: A Deeper Look, Part 2continues the study of classes and presents additional object-oriented programming concepts. The chapter discusses declaring and using constant objects, constant member functions, compositionthe process of building classes that have objects of other classes as members, friend functions and friend classes that have special access rights to the private and protected members of classes, the this pointer, which enables an object to know its own address, dynamic memory allocation, static class members for containing and manipulating class-wide data, examples of popular abstract data types (arrays, strings and queues), container classes and iterators. In our discussion of const objects, we mention keyword mutable which is used in a subtle manner to enable modification of "non-visible" implementation in const objects. We discuss dynamic memory allocation using new and delete. When new fails, the program terminates by default because new "throws an exception" in standard C++. We motivate the discussion of static class members with a video-game-based example. We emphasize how important it is to hide implementation details from clients of a class; then, we discuss proxy classes, which provide a means of hiding implementation (including the private data in class headers) from clients of a class. The chapter exercises include developing a savings-account class and a class for holding sets of integers.

Chapter 11
Operator Overloading; String and Array Objectspresents one of the most popular topics in our C++ courses. Students really enjoy this material. They find it a perfect match with the detailed discussion of crafting valuable classes in Chapters 9 and 10. Operator overloading enables the programmer to tell the compiler how to use existing operators with objects of new types. C++ already knows how to use these operators with objects of built-in types, such as integers, floats and characters. But suppose that we create a new String classwhat would the plus sign mean when used between String objects? Many programmers use plus (+) with strings to mean concatenation. In Chapter 11, the programmer will learn how to "overload" the plus sign, so when it is written between two String objects in an expression, the compiler will generate a function call to an "operator function" that will concatenate the two Strings. The chapter discusses the fundamentals of operator overloading, restrictions in operator overloading, overloading with class member functions vs. with nonmember functions, overloading unary and binary operators and converting between types. Chapter 11 features the collection of substantial case studies including an array class, a String class, a date class, a huge integer class and a complex numbers class (the last two appear with full source code in the exercises). Mathematically inclined students will enjoy creating the polynomial class in the exercises. This material is different from most programming languages and courses. Operator overloading is a complex topic, but an enriching one. Using operator overloading wisely helps you add extra "polish" to your classes. The discussions of class Array and class String are particularly valuable to students who have already used the C++ Standard Library string class and vector class template that provide similar capabilities. The exercises encourage the student to add operator overloading to classes Complex, Rational and HugeInteger to enable convenient manipulation of objects of these classes with operator symbolsas in mathematicsrather than with function calls as the student did in the Chapter 10 exercises.

Chapter 12
Object-Oriented Programming: Inheritanceintroduces one of the most fundamental capabilities of object-oriented programming languagesinheritance: a form of software reusability in which new classes are developed quickly and easily by absorbing the capabilities of existing classes and adding appropriate new capabilities. In the context of an Employee hierarchy case study, this substantially revised chapter presents a five-example sequence demonstrating private data, protected data and good software engineering with inheritance. We begin by demonstrating a class with private data members and public member functions to manipulate that data. Next, we implement a second class with additional capabilities, intentionally and tediously duplicating much of the first example's code. The third example begins our discussion of inheritance and software reusewe use the class from the first example as a base class and quickly and simply inherit its data and functionality into a new derived class. This example introduces the inheritance mechanism and demonstrates that a derived class cannot access its base class's private members directly. This motivates our fourth example, in which we introduce protected data in the base class and demonstrate that the derived class can indeed access the protected data inherited from the base class. The last example in the sequence demonstrates proper software engineering by defining the base class's data as private and using the base class's public member functions (that were inherited by the derived class) to manipulate the base class's private data in the derived class. The chapter discusses the notions of base classes and derived classes, protected members, public inheritance, protected inheritance, private inheritance, direct base classes, indirect base classes, constructors and destructors in base classes and derived classes, and software engineering with inheritance. The chapter also compares inheritance (the "is-a" relationship) with composition (the "has-a" relationship) and introduces the "uses-a" and "knows-a" relationships.

Chapter 13
Object-Oriented Programming: Polymorphismdeals with another fundamental capability of object-oriented programming: polymorphic behavior. The completely revised Chapter 13 builds on the inheritance concepts presented in Chapter 12 and focuses on the relationships among classes in a class hierarchy and the powerful processing capabilities that these relationships enable. When many classes are related to a common base class through inheritance, each derived-class object may be treated as a base-class object. This enables programs to be written in a simple and general manner independent of the specific types of the derived-class objects. New kinds of objects can be handled by the same program, thus making systems more extensible. Polymorphism enables programs to eliminate complex switch logic in favor of simpler "straight-line" logic. A screen manager of a video game, for example, can send a draw message to every object in a linked list of objects to be drawn. Each object knows how to draw itself. An object of a new class can be added to the program without modifying that program (as long as that new object also knows how to draw itself). The chapter discusses the mechanics of achieving polymorphic behavior via virtual functions. It distinguishes between abstract classes (from which objects cannot be instantiated) and concrete classes (from which objects can be instantiated). Abstract classes are useful for providing an inheritable interface to classes throughout the hierarchy. We demonstrate abstract classes and polymorphic behavior by revisiting the Employee hierarchy of Chapter 12. We introduce an abstract Employee base class, from which classes CommissionEmployee, HourlyEmployee and SalariedEmployee inherit directly and class BasePlusCommissionEmployee inherits indirectly. In the past, our professional clients have insisted that we provide a deeper explanation that shows precisely how polymorphism is implemented in C++, and hence, precisely what execution time and memory "costs" are incurred when programming with this powerful capability. We responded by developing an illustration and a precise explanation of the vtables (virtual function tables) that the C++ compiler builds automatically to support polymorphism. To conclude, we introduce run-time type information (RTTI) and dynamic casting, which enable a program to determine an object's type at execution time, then act on that object accordingly. Using RTTI and dynamic casting, we give a 10% pay increase to employees of a specific type, then calculate the earnings for such employees. For all other employee types, we calculate their earnings polymorphically.

Chapter 14
Templatesdiscusses one of C++'s more powerful software reuse features, namely templates. Function templates and class templates enable programmers to specify, with a single code segment, an entire range of related overloaded functions (called function template specializations) or an entire range of related classes (called class-template specializations). This technique is called generic programming. Function templates were introduced in Chapter 6. This chapter presents additional discussions and examples on function template. We might write a single class template for a stack class, then have C++ generate separate class-template specializations, such as a "stack-of-int" class, a "stack-of-float" class, a "stack-of-string" class and so on. The chapter discusses using type parameters, nontype parameters and default types for class templates. We also discuss the relationships between templates and other C++ features, such as overloading, inheritance, friends and static members. The exercises challenge the student to write a variety of function templates and class templates and to employ these in complete programs. We greatly enhance the treatment of templates in our discussion of the Standard Template Library (STL) containers, iterators and algorithms in Chapter 23.

Chapter 15
C++ Stream Input/Outputcontains a comprehensive treatment of standard C++ input/output capabilities. This chapter discusses a range of capabilities sufficient for performing most common I/O operations and overviews the remaining capabilities. Many of the I/O features are object oriented. This style of I/O makes use of other C++ features, such as references, function overloading and operator overloading. The various I/O capabilities of C++, including output with the stream insertion operator, input with the stream extraction operator, type-safe I/O, formatted I/O, unformatted I/O (for performance). Users can specify how to perform I/O for objects of user-defined types by overloading the stream insertion operator (<<) and the stream extraction operator (>>). This extensibility is one of C++'s most valuable features. C++ provides various stream manipulators that perform formatting tasks. This chapter discusses stream manipulators that provide capabilities such as displaying integers in various bases, controlling floating-point precision, setting field widths, displaying decimal point and trailing zeros, justifying output, setting and unsetting format state, setting the fill character in fields. We also present an example that creates user-defined output stream manipulators.

Chapter 16
Exception Handlingdiscusses how exception handling enables programmers to write programs that are robust, fault tolerant and appropriate for business-critical and mission-critical environments. The chapter discusses when exception handling is appropriate; introduces the basic capabilities of exception handling with try blocks, throw statements and catch handlers; indicates how and when to rethrow an exception; explains how to write an exception specification and process unexpected exceptions; and discusses the important ties between exceptions and constructors, destructors and inheritance. The exercises in this chapter show the student the diversity and power of C++'s exception-handling capabilities. We discuss rethrowing an exception, and we illustrate how new can fail when memory is exhausted. Many older C++ compilers return 0 by default when new fails. We show the new style of new failing by throwing a bad_alloc (bad allocation) exception. We illustrate how to use function set_new_handler to specify a custom function to be called to deal with memory-exhaustion situations. We discuss how to use the auto_ptr class template to delete dynamically allocated memory implicitly, thus avoiding memory leaks. To conclude this chapter, we present the Standard Library exception hierarchy.

Chapter 17
File Processingdiscusses techniques for creating and processing both sequential files and random-access files. The chapter begins with an introduction to the data hierarchy from bits, to bytes, to fields, to records and to files. Next, we present the C++ view of files and streams. We discuss sequential files and build programs that show how to open and close files, how to store data sequentially in a file and how to read data sequentially from a file. We then discuss random-access files and build programs that show how to create a file for random access, how to read and write data to a file with random access and how to read data sequentially from a randomly accessed file. The case study combines the techniques of accessing files both sequentially and randomly into a complete transaction-processing program. Students in our industry seminars have mentioned that, after studying the material on file processing, they were able to produce substantial file-processing programs that were immediately useful in their organizations. The exercises ask the student to implement a variety of programs that build and process both sequential files and random-access files.

Chapter 18
Class string and String Stream ProcessingThe chapter discusses C++'s capabilities for inputting data from strings in memory and outputting data to strings in memory; these capabilities often are referred to as in-core formatting or string-stream processing. Class string is a required component of the Standard Library. We preserved the treatment of C-like, pointer-based strings in Chapter 8 and later for several reasons. First, it strengthens the reader's understanding of pointers. Second, for the next decade or so, C++ programmers will need to be able to read and modify the enormous amounts of C legacy code that has accumulated over the last quarter of a centurythis code processes strings as pointers, as does a large portion of the C++ code that has been written in industry over the last many years. In Chapter 18 we discuss string assignment, concatenation and comparison. We show how to determine various string characteristics such as a string's size, capacity and whether or not it is empty. We discuss how to resize a string. We consider the various "find" functions that enable us to find a substring in a string (searching the string either forwards or backwards), and we show how to find either the first occurrence or last occurrence of a character selected from a string of characters, and how to find the first occurrence or last occurrence of a character that is not in a selected string of characters. We show how to replace, erase and insert characters in a string and how to convert a string object to a C-style char * string.

Chapter 19
Web ProgrammingThis optional chapter has everything you need to begin developing your own Web-based applications that will really run on the Internet! You will learn how to build so-called n-tier applications, in which the functionality provided by each tier can be distributed to separate computers across the Internet or executed on the same computer. In particular, we build a three-tier online bookstore application. The bookstore's information is stored in the application's bottom tier, also called the data tier. In industrial-strength applications, the data tier is typically a database such as Oracle, Microsoft® SQL Server or MySQL. For simplicity, we use text files and employ the file-processing techniques of Chapter 17 to access and modify these files. The user enters requests and receives responses at the application's top tier, also called the user-interface tier or the client tier, which is typically a computer running a popular Web browser such as Microsoft Internet Explorer, Mac® OS X Safari™, Mozilla Firefox, Opera or Netscape®. Web browsers, of course, know how to communicate with Web sites throughout the Internet. The middle tier, also called the business-logic tier, contains both a Web server and an application-specific C++ program (e.g., our bookstore application). The Web server communicates with the C++ program (and vice versa) via the CGI (Common Gateway Interface) protocol. This program is referred to as a CGI script. We use the popular Apache HTTP server, which is available free for download from the Apache Web site, www.apache.org. Apache installation instructions for many popular platforms, including Linux and Windows systems, are available at that site and at www.deitel.com and www.prenhall.com/deitel. The Web server knows how to talk to the client tier across the Internet using a protocol called HTTP (Hypertext Transfer Protocol). We discuss the two most popular HTTP methods for sending data to a Web serverGET and POST. We then discuss the crucial role of the Web server in Web programming and provide a simple example that requests an Extensible HyperText Markup Language (XHTML)[1] document from a Web server. We discuss CGI and how it allows a Web server to communicate with the top tier and CGI applications. We provide a simple example that gets the server's time and renders it in a browser. Other examples demonstrate how to process form-based user input via the string processing techniques introduced in Chapter 18. In our forms-based examples we use buttons, password fields, check boxes and text fields. We present an example of an interactive portal for a travel company that displays airfares to various cities. Travel-club members can log in and view discounted airfares. We also discuss various methods of storing client-specific data, which include hidden fields (i.e., information stored in a Web page but not rendered by the Web browser) and cookiessmall text files that the browser stores on the client's machine. The chapter examples conclude with a case study of an online book store that allows users to add books to a shopping cart. This case study contains several CGI scripts that interact to form a complete application. The online book store is password protected, so users first must log in to gain access. The chapter's Web resources include information about the CGI specification, C++ CGI libraries and Web sites related to the Apache HTTP server.

Chapter 20
Searching and Sortingdiscusses two of the most important classes of algorithms in computer science. We consider a variety of specific algorithms for each and compare them with regard to their memory consumption and processor consumption (introducing Big O notation, which indicates how hard an algorithm may have to work to solve a problem). Searching data involves determining whether a value (referred to as the search key) is present in the data and, if so, finding the value's location. In the examples and exercises of this chapter, we discuss a variety of searching algorithms, including: binary search and recursive versions of linear search and binary search. Through examples and exercises, Chapter 20 discusses the recursive merge sort, bubble sort, bucket sort and the recursive quicksort.

Chapter 21
Data Structuresdiscusses the techniques used to create and manipulate dynamic data structures. The chapter begins with discussions of self-referential classes and dynamic memory allocation, then proceeds with a discussion of how to create and maintain various dynamic data structures, including linked lists, queues (or waiting lines), stacks and trees. For each type of data structure, we present complete, working programs and show sample outputs. The chapter also helps the student master pointers. The chapter includes abundant examples that use indirection and double indirectiona particularly difficult concept. One problem when working with pointers is that students have trouble visualizing the data structures and how their nodes are linked together. We have included illustrations that show the links and the sequence in which they are created. The binary-tree example is a superb capstone for the study of pointers and dynamic data structures. This example creates a binary tree, enforces duplicate elimination and introduces recursive preorder, inorder and postorder tree traversals. Students have a genuine sense of accomplishment when they study and implement this example. They particularly appreciate seeing that the inorder traversal prints the node values in sorted order. We include a substantial collection of exercises. A highlight of the exercises is the special section Building Your Own Compiler. The exercises walk the student through the development of an infix-to-postfix-conversion program and a postfix-expression-evaluation program. We then modify the postfix-evaluation algorithm to generate machine-language code. The compiler places this code in a file (using the techniques of Chapter 17. Students then run the machine language produced by their compilers on the software simulators they built in the exercises of Chapter 8! The 35 exercises include recursively searching a list, recursively printing a list backwards, binary-tree node deletion, level-order traversal of a binary tree, printing trees, writing a portion of an optimizing compiler, writing an interpreter, inserting/deleting anywhere in a linked list, implementing lists and queues without tail pointers, analyzing the performance of binary-tree searching and sorting, implementing an indexed-list class and a supermarket simulation that uses queueing. After studying Chapter 21, the reader is prepared for the treatment of STL containers, iterators and algorithms in Chapter 23. The STL containers are prepackaged, templatized data structures that most programmers will find sufficient for the vast majority of applications they will need to implement. The STL is a giant leap forward in achieving the vision of reuse.

Chapter 20
Searching and Sortingdiscusses two of the most important classes of algorithms in computer science. We consider a variety of specific algorithms for each and compare them with regard to their memory consumption and processor consumption (introducing Big O notation, which indicates how hard an algorithm may have to work to solve a problem). Searching data involves determining whether a value (referred to as the search key) is present in the data and, if so, finding the value's location. In the examples and exercises of this chapter, we discuss a variety of searching algorithms, including: binary search and recursive versions of linear search and binary search. Through examples and exercises, Chapter 20 discusses the recursive merge sort, bubble sort, bucket sort and the recursive quicksort.

Chapter 21
Data Structuresdiscusses the techniques used to create and manipulate dynamic data structures. The chapter begins with discussions of self-referential classes and dynamic memory allocation, then proceeds with a discussion of how to create and maintain various dynamic data structures, including linked lists, queues (or waiting lines), stacks and trees. For each type of data structure, we present complete, working programs and show sample outputs. The chapter also helps the student master pointers. The chapter includes abundant examples that use indirection and double indirectiona particularly difficult concept. One problem when working with pointers is that students have trouble visualizing the data structures and how their nodes are linked together. We have included illustrations that show the links and the sequence in which they are created. The binary-tree example is a superb capstone for the study of pointers and dynamic data structures. This example creates a binary tree, enforces duplicate elimination and introduces recursive preorder, inorder and postorder tree traversals. Students have a genuine sense of accomplishment when they study and implement this example. They particularly appreciate seeing that the inorder traversal prints the node values in sorted order. We include a substantial collection of exercises. A highlight of the exercises is the special section Building Your Own Compiler. The exercises walk the student through the development of an infix-to-postfix-conversion program and a postfix-expression-evaluation program. We then modify the postfix-evaluation algorithm to generate machine-language code. The compiler places this code in a file (using the techniques of Chapter 17. Students then run the machine language produced by their compilers on the software simulators they built in the exercises of Chapter 8! The 35 exercises include recursively searching a list, recursively printing a list backwards, binary-tree node deletion, level-order traversal of a binary tree, printing trees, writing a portion of an optimizing compiler, writing an interpreter, inserting/deleting anywhere in a linked list, implementing lists and queues without tail pointers, analyzing the performance of binary-tree searching and sorting, implementing an indexed-list class and a supermarket simulation that uses queueing. After studying Chapter 21, the reader is prepared for the treatment of STL containers, iterators and algorithms in Chapter 23. The STL containers are prepackaged, templatized data structures that most programmers will find sufficient for the vast majority of applications they will need to implement. The STL is a giant leap forward in achieving the vision of reuse.

Chapter 24
Other Topicsis a collection of miscellaneous C++ topics. This chapter discusses one additional cast operatorconst_cast. This operator, along with static_cast (Chapter 5), dynamic_cast (Chapter 13) and reinterpret_cast (Chapter 17), provide a more robust mechanism for converting between types than do the original cast operators C++ inherited from C (which are now deprecated). We discuss namespaces, a feature particularly crucial for software developers who build substantial systems, especially for those who build systems from class libraries. Namespaces prevent naming collisions, which can hinder such large software efforts. The Chapter discusses the operator keywords, which are useful for programmers who have keyboards that do not support certain characters used in operator symbols, such as !, &, ^, ~ and |. These operators can also be used by programmers who do not like cryptic operator symbols. We discuss keyword mutable, which allows a member of a const object to be changed. Previously, this was accomplished by "casting away const-ness", which is considered a dangerous practice. We also discuss pointer-to-member operators .* and ->*, multiple inheritance (including the problem of "diamond inheritance") and virtual base classes.

Read Comments To Download

1 comments:

Anonymous said...

http://rapidshare.com/files/114519993/C___-_How_To_Program__5th_Edition__2005_.chm

or

http://tinyurl.com/56kcsy

Would you like to get my updates directly to your mailbox? Click below to Enter your mail address

Subscribe to Books Tube


AddThis Feed Button 
Page copy protected against web site content infringement by Copyscape