+ All Categories
Home > Documents > Data Structures and Algorithms in C

Data Structures and Algorithms in C

Date post: 11-Aug-2015
Category:
Upload: siddharthay
View: 170 times
Download: 3 times
Share this document with a friend
Description:
c++ book for all
Popular Tags:
738
Transcript

This page intentionally left blank iimain 2011/1/13 9:10page i #1iiiiiiDataStructuresandAlgorithmsinC++SecondEditionThis page intentionally left blank iimain 2011/1/13 9:10page iii #3iiiiiiDataStructuresandAlgorithmsinC++SecondEditionMichael T.GoodrichDepartment of Computer ScienceUniversity of California, IrvineRobertoTamassiaDepartment of Computer ScienceBrown UniversityDavidM.MountDepartment of Computer ScienceUniversity of MarylandJohn Wiley & Sons, Inc.iimain 2011/1/13 9:10page iv#4iiiiiiACQUISITIONS EDITOR Beth Lang GolubMARKETING MANAGER Chris RuelEDITORIAL ASSISTANT Elizabeth MillsMEDIA EDITOR Thomas KulesaSENIOR DESIGNER Jim OSheaCONTENT MANAGER Micheline FrederickPRODUCTION EDITOR Amy WeintraubPHOTO EDITOR Sheena GoldsteinThis book was set in LATEX by the authors and printed and bound by Malloy Lithographers.The cover was printed by Malloy Lithographers. The cover image is fromWuta Wuta Tjan-gala, Emu dreaming c estate of the artist 2009 licensed by Aboriginal Artists Agency.Jennifer Steele/Art Resource, NY.This book is printed on acid free paper. Trademark Acknowledgments:Java is a trademark of Sun Microsystems, Inc. UNIXR isa registered trademark in the United States and other countries, licensed through X/OpenCompany, Ltd. PowerPointR is a trademark of Microsoft Corporation. All other productnames mentioned herein are the trademarks of their respective owners.Copyright c 2011, John Wiley & Sons, Inc. All rights reserved.No part of this publication may be reproduced, stored in a retrieval system or transmittedin any form or by any means, electronic, mechanical, photocopying, recording, scanningorotherwise, except aspermittedunderSections107or108ofthe1976UnitedStatesCopyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc.222 Rosewood Drive, Danvers, MA 01923, (978)750-8400, fax (978)646-8600.Requests to the Publisher for permission should be addressed to the Permissions Depart-ment, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201)748-6011, fax(201)748-6008, E-Mail:[email protected] order books or for customer service please call 1-800-CALL WILEY (225-5945).Founded in 1807, John Wiley & Sons,Inc. has been a valued source of knowledge andunderstanding for more than 200 years, helping people around the world meet their needsand fulll their aspirations. Our company is built on a foundation of principles that includeresponsibilitytothecommunitiesweserveandwhereweliveandwork. In2008, welaunched a Corporate Citizenship Initiative, a global effort to address the environmental,social,economic, and ethical challenges we face in our business. Among the issues weare addressing are carbon impact,paper specications and procurement, ethical conductwithin our business and among our vendors, and community and charitable support. Formore information, please visit our website: www.wiley.com/go/citizenship.Library of Congress Cataloging in Publication DataISBN-13 978-0-470-38327-8Printed in the United States of America10 9 8 7 6 5 4 3 2 1iimain 2011/1/13 9:10page v#5iiiiiiTo Karen, Paul, Anna, and Jack Michael T. GoodrichTo Isabel Roberto TamassiaTo Jeanine David M. MountThis page intentionally left blank iimain 2011/1/13 9:10page vii #7iiiiiiPrefaceThis second edition of Data Structures and Algorithms in C++ is designed to pro-vide an introduction to data structures and algorithms, including their design, analy-sis, and implementation. In terms of curricula based on the IEEE/ACM 2001 Com-puting Curriculum, this book is appropriate for use in the courses CS102 (I/O/Bversions), CS103 (I/O/B versions), CS111 (A version), and CS112 (A/I/O/F/H ver-sions). We discuss its use for such courses in more detail later in this preface.The major changes in the second edition are the following:We added more examples of data structure and algorithm analysis.We enhanced consistency with the C++ Standard Template Library (STL).We incorporated STL data structures into many of our data structures.We added a chapter on arrays, linked lists, and iterators (Chapter 3).We added a chapter on memory management and B-trees (Chapter 14).We enhanced the discussion of algorithmic design techniques, like dynamicprogramming and the greedy method.We simplied and reorganized the presentation of code fragments.We have introduced STL-style iterators into our container classes, and havepresented C++ implementations for these iterators,even for complex struc-tures such as hash tables and binary search trees.We have modied our priority-queue interface to use STL-style comparatorobjects.Weexpandedandrevisedexercises, continuingour approachofdividingthem into reinforcement, creativity, and project exercises.This book is related to the following books:M.T.GoodrichandR.Tamassia, DataStructuresandAlgorithmsinJava,JohnWiley&Sons, Inc. Thisbookhasasimilaroverall structuretothepresent book, but uses Java as the underlying language (with some modest,but necessary pedagogical differences required by this approach).M.T. Goodrich and R. Tamassia, Algorithm Design:Foundations,Analysis,and Internet Examples, John Wiley & Sons, Inc. This is a textbook for a moreadvancedalgorithmsanddatastructurescourse, suchasCS210(T/W/C/Sversions) in the IEEE/ACM 2001 curriculum.While this book retains the same pedagogicalapproach and generalstructureasDataStructuresandAlgorithmsinJava, thecodefragmentshavebeencom-pletely redesigned. We have been careful to make full use of C++s capabilities anddesign code in a manner that is consistent with modern C++ usage. In particular,whenever appropriate, we make extensive use of C++ elements that are not part ofJava, including the C++ Standard Template Library (STL), C++ memory allocationviiiimain 2011/1/13 9:10page viii #8iiiiiiviii Prefaceand deallocation (and the associated issues of destructors), virtual functions, streaminput and output, operator overloading, and C++s safe run-time casting.UseasaTextbookThe design and analysis of efcient data structures has long been recognized as avital subject in computing, because the study of data structures is part of the coreof every collegiate computer science and computer engineering major program wearefamiliarwith. Typically, theintroductorycoursesarepresentedas atwo-orthree-coursesequence. Elementary data structures are often briey introduced inthe rst programming course or in an introduction to computer science course andthis is followed by a more in-depth introduction to data structures in the courses thatfollow after this.Furthermore, this course sequence is typically followed at a laterpoint in the curriculum by a more in-depth study of data structures and algorithms.We feel that the central role of data structure design and analysis in the curriculumis fully justied, given the importance of efcient data structures in most softwaresystems, including the Web, operating systems, databases, compilers, and scienticsimulation systems.With the emergence of the object-oriented paradigm as the framework of choicefor building robust and reusable software, we have tried to take a consistent object-oriented viewpoint throughout this text. One of the main ideas behind the object-oriented approach is that data should be presented as being encapsulated with themethodsthataccessandmodifythem. Thatis, ratherthansimplyviewingdataas a collection of bytes and addresses, we think of data objects as instances of anabstract data type (ADT), which includes a repertoire of methods for performingoperations on data objects of this type. Likewise, object-oriented solutions are oftenorganizedutilizingcommon designpatterns, which facilitatesoftwarereuseandrobustness. Thus, we present each data structure using ADTs and their respectiveimplementations and we introduce important design patterns as a way to organizethose implementations into classes, methods, and objects.For most of the ADTs presented in this book, we provide a description of thepublicinterfaceinC++. Also, concretedatastructuresrealizingtheADTsarediscussed and we often give concrete C++ classes implementing these interfaces.We also give C++ implementations of fundamental algorithms, such as sorting andgraph searching. Moreover, in addition to providing techniques for using data struc-tures to implement ADTs, we also give sample applications of data structures, suchas HTML tag matchinganda simplesystemto maintaina playlistfora digitalaudio system.Due to space limitations, however, we only show code fragments ofsome of the implementations in this book and make additional source code avail-able on the companion web site.iimain 2011/1/13 9:10 page ix#9iiiiiiPreface ixOnlineResourcesThis book is accompaniedby an extensiveset of onlineresources, which can befound at the following web site:www.wiley.com/college/goodrichIncluded on this Web site is a collection of educationalaids that augment thetopics of this book, for both students and instructors. Students are encouraged touse this site along with the book, to help with exercises and increase understand-ing ofthe subject. Instructorsare likewise welcome to use the site to helpplan,organize, and present their course materials. Because of their added value, some ofthese online resources are password protected.FortheStudentFor all readers, and especially for students, we include the following resources:All the C++ source code presented in this book.PDF handouts of Powerpoint slides (four-per-page) provided to instructors.A database of hints to all exercises, indexed by problem number.An online study guide, which includes solutions to selected exercises.Thehintsshouldbeofconsiderableusetoanyoneneedingalittlehelpgettingstarted on certain exercises, and the solutionsshould help anyone wishing to seecompleted exercises. Students who have purchased a new copy of this book willget password access to the hints and other password-protected online resources atno extra charge. Other readers can purchase password access for a nominal fee.FortheInstructorFor instructors using this book, we include the following additional teaching aids:Solutions to over 200 of the books exercises.A database of additional exercises, suitable for quizes and exams.Additional C++ source code.Slides in Powerpoint and PDF (one-per-page) format.Self-contained, special-topicsupplements,including discussions on convexhulls, range trees, and orthogonal segment intersection.The slides are fully editable, so as to allow an instructor using this book full free-dom in customizing his or her presentations. All the online resources are providedat no extra charge to any instructor adopting this book for his or her course.iimain 2011/1/13 9:10page x#10iiiiiix PrefaceAResourceforTeachingDataStructuresandAlgorithmsThis book contains many C++-code and pseudo-code fragments, and hundreds ofexercises, which are divided into roughly 40% reinforcementexercises, 40% cre-ativity exercises, and 20% programming projects.This book can be used for the CS2 course, as described in the 1978 ACM Com-puter Science Curriculum, or in courses CS102 (I/O/B versions), CS103 (I/O/B ver-sions), CS111 (A version), and/or CS112 (A/I/O/F/H versions), as described in theIEEE/ACM2001ComputingCurriculum, withinstructional unitsasoutlinedinTable 0.1.Instructional Unit Relevant MaterialPL1. Overview of Programming Languages Chapters 1 and 2PL2. Virtual Machines Sections 14.1.1 and 14.1.2PL3. Introduction to Language Translation Section 1.7PL4. Declarations and Types Sections 1.1.2, 1.1.3, and 2.2.5PL5. Abstraction Mechanisms Sections 2.2.5, 5.15.3, 6.1.1, 6.2.1, 6.3,7.1, 7.3.1, 8.1, 9.1, 9.5, 11.4, and 13.1.1PL6. Object-Oriented Programming Chapters 1 and 2 and Sections 6.2.1,7.3.7, 8.1.2, and 13.3.1PF1. Fundamental Programming Constructs Chapters 1 and 2PF2. Algorithms and Problem-Solving Sections 1.7 and 4.2PF3. Fundamental Data Structures Sections 3.1,3.2,5.15.3, 6.16.3,7.1,7.3, 8.1, 8.3, 9.19.4, 10.1, and 13.1.1PF4. Recursion Section 3.5SE1. Software Design Chapter 2 and Sections 6.2.1, 7.3.7,8.1.2, and 13.3.1SE2. Using APIs Sections 2.2.5, 5.15.3, 6.1.1, 6.2.1, 6.3,7.1, 7.3.1, 8.1, 9.1, 9.5, 11.4, and 13.1.1AL1. Basic Algorithmic Analysis Chapter 4AL2. Algorithmic Strategies Sections 11.1.1, 11.5.1, 12.2, 12.3.1, and12.4.2AL3. Fundamental Computing Algorithms Sections 8.1.5, 8.2.2, 8.3.5, 9.2, and9.3.1, and Chapters 11, 12, and 13DS1. Functions, Relations, and Sets Sections 4.1, 8.1, and 11.4DS3. Proof Techniques Sections 4.3, 6.1.3, 7.3.3, 8.3, 10.210.5,11.2.1, 11.3.1, 11.4.3, 13.1.1, 13.3.1,13.4, and 13.5DS4. Basics of Counting Sections 2.2.3 and 11.1.5DS5. Graphs and Trees Chapters 7, 8, 10, and 13DS6. Discrete Probability Appendix Aand Sections 9.2, 9.4.2,11.2.1, and 11.5Table 0.1: Material for units in the IEEE/ACM 2001 Computing Curriculum.iimain 2011/1/13 9:10page xi #11iiiiiiPreface xiContentsandOrganizationThe chapters for this course are organized to provide a pedagogical path that startswith the basicsof C++ programmingand object-orienteddesign. We provide anearly discussion of concrete structures, like arrays and linked lists, in order to pro-vide a concrete footing to build upon when constructing other data structures. Wethen add foundational techniques like recursion and algorithm analysis, and, in themain portion of the book, we present fundamental data structures and algorithms,concludingwithadiscussionofmemorymanagement (that is, thearchitecturalunderpinnings of data structures). Specically, the chapters for this book are orga-nized as follows:1. AC++Primer2. Object-OrientedDesign3. Arrays,LinkedLists, andRecursion4. AnalysisTools5. Stacks, Queues,andDeques6. ListandIteratorADTs7. Trees8. HeapsandPriorityQueues9. HashTables,Maps,andSkipLists10. SearchTrees11. Sorting,Sets,andSelection12. StringsandDynamicProgramming13. GraphAlgorithms14. MemoryManagementandB-TreesA. Useful Mathematical FactsA more detailed listing of the contents of this book can be found in the table ofcontents.iimain 2011/1/13 9:10page xii #12iiiiiixii PrefacePrerequisitesWe have written this book assuming that the reader comes to it with certain knowl-edge. We assume that the reader is at least vaguely familiar with a high-level pro-gramming language, such as C, C++, Python, or Java, and that he or she understandsthe main constructs from such a high-level language, including:Variables and expressions.Functions (also known as methods or procedures).Decision structures (such as if-statements and switch-statements).Iteration structures (for-loops and while-loops).For readerswho are familiarwith theseconcepts, butnotwith how theyare ex-pressed in C++, we provide a primer on the C++ language in Chapter 1. Still, thisbook is primarily a data structures book, not a C++ book; hence, it does not providea comprehensive treatment of C++. Nevertheless, we do not assume that the readeris necessarilyfamiliar with object-orienteddesign or with linked structures, suchas linked lists, since these topics are covered in the core chapters of this book.In terms of mathematical background, we assume the reader is somewhat famil-iar with topics from high-schoolmathematics. Even so, in Chapter 4, we discussthe seven most-important functions for algorithm analysis. In fact, sections that usesomething other than one of these seven functions are considered optional, and areindicated with a star (). We give a summary of other useful mathematical facts,including elementary probability, in Appendix A.AbouttheAuthorsProfessors Goodrich, Tamassia, and Mount are well-recognized researchers in al-gorithms and data structures, having published many papers in this eld, with ap-plications to Internet computing, information visualization, computer security, andgeometric computing. They have served as principal investigators in several jointprojectssponsoredbytheNationalScienceFoundation, theArmy ResearchOf-ce,the Ofce of Naval Research, and the Defense Advanced Research ProjectsAgency. They are also active in educational technology research.Michael Goodrich received his Ph.D. in Computer Science from Purdue Uni-versity in 1987. He is currently a Chancellors Professor in the Department of Com-puter Science at University of California, Irvine. Previously, he was a professor atJohnsHopkins University. He is an editorfor a numberof journalsin computerscience theory, computational geometry, and graph algorithms. He is an ACM Dis-tinguished Scientist, a Fellow of the American Association for the Advancement ofScience (AAAS), a Fulbright Scholar, and a Fellow of the IEEE. He is a recipient ofthe IEEE Computer Society Technical Achievement Award, the ACM Recognitionof Service Award, and the Pond Award for Excellence in Undergraduate Teaching.iimain 2011/1/13 9:10 page xiii #13iiiiiiPreface xiiiRoberto Tamassia received his Ph.D. in Electrical and Computer Engineeringfrom the University of Illinois at Urbana-Champaignin 1988. He is the PlastechProfessor of Computer Science and the Chair of the Department of Computer Sci-ence at Brown University. He is also the Director of Browns Center for GeometricComputing. His research interests include information security, cryptography, anal-ysis, design, and implementation of algorithms, graph drawing, and computationalgeometry. HeisanIEEEFellowandarecipient oftheTechnical AchievementAward from the IEEE Computer Society for pioneering the eld of graph drawing.He is an editor of several journals in geometric and graph algorithms. He previouslyserved on the editorial board of IEEE Transactions on Computers.David Mount received his Ph.D. in Computer Science from Purdue Universityin1983. He iscurrentlyaprofessorintheDepartmentofComputerScienceattheUniversityofMarylandwithajointappointment intheUniversityofMary-lands Institute for Advanced Computer Studies. He is an associate editor for ACMTransactions on Mathematical Software and the InternationalJournal of Compu-tational Geometry and Applications. He is the recipient of two ACM Recognitionof Service Awards.In addition to their research accomplishments, the authors also have extensiveexperience in the classroom.For example, Dr. Goodrich has taught data structuresand algorithms courses, including Data Structures as a freshman-sophomore levelcourse and Introduction to Algorithms as an upper-level course. He has earned sev-eral teaching awards in this capacity. His teaching style is to involve the students inlively interactive classroom sessions that bring out the intuition and insights behinddata structuring and algorithmic techniques. Dr. Tamassia has taught Data Struc-turesandAlgorithmsasanintroductoryfreshman-levelcoursesince1988. Onething that has set his teaching style apart is his effective use of interactive hyper-media presentations integrated with the Web. Dr. Mount has taught both the DataStructures and the Algorithms courses at the University of Maryland since 1985.He has won a number of teaching awards from Purdue University, the University ofMaryland, and the Hong Kong University of Science and Technology. His lecturenotes and homework exercises for the courses that he has taught are widely used assupplementary learning material by students and instructors at other universities.AcknowledgmentsThere are a number of individuals who have made contributions to this book.We are gratefulto all our researchcollaboratorsand teaching assistants, whoprovidedfeedbackonearlydraftsofchaptersandhavehelpedusindevelopingexercises, software, and algorithm animation systems. There have been a number offriends and colleagues whose comments have lead to improvements in the text. Weare particularly thankful to Michael Goldwasser for his many valuable suggestions.iimain 2011/1/13 9:10page xiv#14iiiiiixiv PrefaceWe are also grateful to Karen Goodrich, Art Moorshead, Scott Smith, and IoannisTollis for their insightful comments.Wearealsotrulyindebtedtotheoutsidereviewersandreadersfortheirco-piouscomments, emails, andconstructivecriticism, whichwereextremelyuse-ful in writing this edition. We specically thank the following reviewers for theircommentsandsuggestions: DivyAgarwal, UniversityofCalifornia, SantaBar-bara; Terry Andres, University of Manitoba; Bobby Blumofe, University of Texas,Austin; Michael Clancy, University of California, Berkeley;Larry Davis, Univer-sity of Maryland; Scott Drysdale, Dartmouth College; Arup Guha,University ofCentral Florida; Chris Ingram, University of Waterloo; Stan Kwasny, WashingtonUniversity; Calvin Lin, University of Texas at Austin; John Mark Mercer, McGillUniversity; Laurent Michel, University of Connecticut; Leonard Myers, CaliforniaPolytechnic State University, San Luis Obispo; David Naumann, Stevens InstituteofTechnology; Robert Pastel, MichiganTechnological University; BinaRama-murthy, SUNYBuffalo; KenSlonneger, UniversityofIowa; C.V. Ravishankar,UniversityofMichigan; Val Tannen, UniversityofPennsylvania; Paul VanAr-ragon, Messiah College; and Christopher Wilson, University of Oregon.We are grateful to our editor,Beth Golub, for her enthusiasticsupport of thisproject. The team at Wiley has been great. Many thanks go to Mike Berlin,Lil-ian Brady, Regina Brooks, Paul Crockett, Richard DeLorenzo, Jen Devine, SimonDurkin, Micheline Frederick, Lisa Gee, Katherine Hepburn, Rachael Leblond, An-dre Legaspi, Madelyn Lesure, Frank Lyman, Hope Miller, Bridget Morrisey, ChrisRuel, KenSantor, LaurenSapira, DanSayre, DianaSmith, BruceSpatz, DawnStanley, Jeri Warner, and Bill Zobrist.The computing systems and excellent technical support staff in the departmentsof computer science at Brown University, University of California, Irvine, and Uni-versity of Maryland gave us reliable working environments. This manuscript wasprepared primarily with the LATEX typesetting package.Finally, we would like to warmly thank Isabel Cruz, Karen Goodrich, JeanineMount, Giuseppe Di Battista, Franco Preparata, Ioannis Tollis, and our parents forproviding advice, encouragement, and support at various stages of the preparationofthisbook. Wealsothankthemforremindingusthattherearethingsinlifebeyond writing books.Michael T. GoodrichRoberto TamassiaDavid M. Mountiimain 2011/1/13 9:10page xv#15iiiiiiContents1 AC++Primer 11.1 BasicC++ProgrammingElements . . . . . . . . . . . . . . . 21.1.1 ASimple C++Program. . . . . . . . . . . . . . . . . . 21.1.2 FundamentalTypes . . . . . . . . . . . . . . . . . . . . 41.1.3 Pointers,Arrays,andStructures . . . . . . . . . . . . . 71.1.4 NamedConstants,Scope,andNamespaces . . . . . . . 131.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.2.1 ChangingTypesthroughCasting . . . . . . . . . . . . . 201.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261.4.1 ArgumentPassing. . . . . . . . . . . . . . . . . . . . . 281.4.2 OverloadingandInlining . . . . . . . . . . . . . . . . . 301.5 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321.5.1 ClassStructure . . . . . . . . . . . . . . . . . . . . . . 331.5.2 ConstructorsandDestructors . . . . . . . . . . . . . . . 371.5.3 ClassesandMemoryAllocation. . . . . . . . . . . . . . 401.5.4 ClassFriendsandClassMembers. . . . . . . . . . . . . 431.5.5 TheStandardTemplateLibrary. . . . . . . . . . . . . . 451.6 C++ProgramandFileOrganization. . . . . . . . . . . . . . 471.6.1 AnExampleProgram. . . . . . . . . . . . . . . . . . . 481.7 WritingaC++Program. . . . . . . . . . . . . . . . . . . . . 531.7.1 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 541.7.2 Pseudo-Code . . . . . . . . . . . . . . . . . . . . . . . 541.7.3 Coding. . . . . . . . . . . . . . . . . . . . . . . . . . . 551.7.4 TestingandDebugging . . . . . . . . . . . . . . . . . . 571.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 Object-OrientedDesign 652.1 Goals,Principles,andPatterns . . . . . . . . . . . . . . . . 662.1.1 Object-OrientedDesignGoals . . . . . . . . . . . . . . 662.1.2 Object-OrientedDesignPrinciples . . . . . . . . . . . . 672.1.3 DesignPatterns . . . . . . . . . . . . . . . . . . . . . . 70xviimain 2011/1/13 9:10page xvi #16iiiiiixvi Contents2.2 InheritanceandPolymorphism. . . . . . . . . . . . . . . . . 712.2.1 Inheritancein C++ . . . . . . . . . . . . . . . . . . . . . 712.2.2 Polymorphism. . . . . . . . . . . . . . . . . . . . . . . 782.2.3 ExamplesofInheritancein C++. . . . . . . . . . . . . . 792.2.4 MultipleInheritanceandClassCasting. . . . . . . . . . 842.2.5 InterfacesandAbstractClasses . . . . . . . . . . . . . . 872.3 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902.3.1 FunctionTemplates . . . . . . . . . . . . . . . . . . . . 902.3.2 ClassTemplates . . . . . . . . . . . . . . . . . . . . . . 912.4 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932.4.1 ExceptionObjects . . . . . . . . . . . . . . . . . . . . . 932.4.2 ThrowingandCatchingExceptions. . . . . . . . . . . . 942.4.3 ExceptionSpecication . . . . . . . . . . . . . . . . . . 962.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 983 Arrays,LinkedLists,andRecursion 1033.1 UsingArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 1043.1.1 StoringGameEntriesinanArray . . . . . . . . . . . . . 1043.1.2 SortinganArray. . . . . . . . . . . . . . . . . . . . . . 1093.1.3 Two-Dimensional ArraysandPositionalGames . . . . . 1113.2 SinglyLinkedLists. . . . . . . . . . . . . . . . . . . . . . . . 1173.2.1 ImplementingaSinglyLinkedList . . . . . . . . . . . . 1173.2.2 InsertiontotheFrontofaSinglyLinkedList . . . . . . 1193.2.3 Removal fromtheFrontofaSinglyLinkedList . . . . . 1193.2.4 ImplementingaGenericSinglyLinkedList . . . . . . . . 1213.3 DoublyLinkedLists . . . . . . . . . . . . . . . . . . . . . . . 1233.3.1 InsertionintoaDoublyLinkedList . . . . . . . . . . . . 1233.3.2 Removal fromaDoublyLinkedList . . . . . . . . . . . 1243.3.3 A C++Implementation . . . . . . . . . . . . . . . . . . 1253.4 CircularlyLinkedListsandListReversal . . . . . . . . . . . 1293.4.1 CircularlyLinkedLists. . . . . . . . . . . . . . . . . . . 1293.4.2 ReversingaLinkedList . . . . . . . . . . . . . . . . . . 1333.5 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1343.5.1 LinearRecursion. . . . . . . . . . . . . . . . . . . . . . 1403.5.2 BinaryRecursion . . . . . . . . . . . . . . . . . . . . . 1443.5.3 MultipleRecursion . . . . . . . . . . . . . . . . . . . . 1473.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1494 AnalysisTools 1534.1 TheSevenFunctionsUsedinThisBook. . . . . . . . . . . 1544.1.1 TheConstantFunction . . . . . . . . . . . . . . . . . . 1544.1.2 TheLogarithmFunction . . . . . . . . . . . . . . . . . 154iimain 2011/1/13 9:10page xvii #17iiiiiiContents xvii4.1.3 TheLinearFunction. . . . . . . . . . . . . . . . . . . . 1564.1.4 TheN-Log-NFunction . . . . . . . . . . . . . . . . . . 1564.1.5 TheQuadraticFunction . . . . . . . . . . . . . . . . . . 1564.1.6 TheCubicFunctionandOtherPolynomials . . . . . . . 1584.1.7 TheExponentialFunction . . . . . . . . . . . . . . . . . 1594.1.8 ComparingGrowthRates . . . . . . . . . . . . . . . . . 1614.2 AnalysisofAlgorithms . . . . . . . . . . . . . . . . . . . . . 1624.2.1 ExperimentalStudies . . . . . . . . . . . . . . . . . . . 1634.2.2 PrimitiveOperations . . . . . . . . . . . . . . . . . . . 1644.2.3 AsymptoticNotation . . . . . . . . . . . . . . . . . . . 1664.2.4 AsymptoticAnalysis. . . . . . . . . . . . . . . . . . . . 1704.2.5 UsingtheBig-OhNotation . . . . . . . . . . . . . . . . 1724.2.6 ARecursiveAlgorithmforComputingPowers . . . . . . 1764.2.7 SomeMoreExamplesofAlgorithmAnalysis . . . . . . . 1774.3 SimpleJusticationTechniques . . . . . . . . . . . . . . . . 1814.3.1 ByExample . . . . . . . . . . . . . . . . . . . . . . . . 1814.3.2 TheContraAttack . . . . . . . . . . . . . . . . . . . 1814.3.3 InductionandLoopInvariants . . . . . . . . . . . . . . 1824.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1855 Stacks,Queues,andDeques 1935.1 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1945.1.1 TheStackAbstractDataType . . . . . . . . . . . . . . 1955.1.2 TheSTLStack . . . . . . . . . . . . . . . . . . . . . . 1965.1.3 A C++StackInterface . . . . . . . . . . . . . . . . . . 1965.1.4 ASimpleArray-BasedStackImplementation . . . . . . 1985.1.5 ImplementingaStackwithaGenericLinkedList . . . . 2025.1.6 ReversingaVectorUsingaStack . . . . . . . . . . . . . 2035.1.7 MatchingParenthesesandHTMLTags . . . . . . . . . 2045.2 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2085.2.1 TheQueueAbstractDataType . . . . . . . . . . . . . 2085.2.2 TheSTLQueue . . . . . . . . . . . . . . . . . . . . . . 2095.2.3 A C++QueueInterface . . . . . . . . . . . . . . . . . . 2105.2.4 ASimpleArray-BasedImplementation . . . . . . . . . . 2115.2.5 ImplementingaQueuewithaCircularlyLinkedList . . . 2135.3 Double-EndedQueues . . . . . . . . . . . . . . . . . . . . . . 2175.3.1 TheDequeAbstractDataType . . . . . . . . . . . . . 2175.3.2 TheSTLDeque . . . . . . . . . . . . . . . . . . . . . . 2185.3.3 ImplementingaDequewithaDoublyLinkedList . . . . 2185.3.4 AdaptersandtheAdapterDesignPattern . . . . . . . . 2205.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223iimain 2011/1/13 9:10page xviii #18iiiiiixviii Contents6 ListandIteratorADTs 2276.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2286.1.1 TheVectorAbstractDataType . . . . . . . . . . . . . 2286.1.2 ASimpleArray-BasedImplementation . . . . . . . . . . 2296.1.3 AnExtendableArrayImplementation . . . . . . . . . . . 2316.1.4 STLVectors . . . . . . . . . . . . . . . . . . . . . . . . 2366.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2386.2.1 Node-BasedOperationsandIterators . . . . . . . . . . . 2386.2.2 TheListAbstractDataType . . . . . . . . . . . . . . . 2406.2.3 DoublyLinkedListImplementation. . . . . . . . . . . . 2426.2.4 STLLists . . . . . . . . . . . . . . . . . . . . . . . . . 2476.2.5 STLContainersandIterators . . . . . . . . . . . . . . . 2486.3 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2556.3.1 TheSequenceAbstractDataType . . . . . . . . . . . . 2556.3.2 ImplementingaSequencewithaDoublyLinkedList . . 2556.3.3 ImplementingaSequencewithanArray . . . . . . . . . 2576.4 CaseStudy: Bubble-SortonaSequence . . . . . . . . . . . 2596.4.1 TheBubble-SortAlgorithm. . . . . . . . . . . . . . . . 2596.4.2 ASequence-BasedAnalysisofBubble-Sort . . . . . . . . 2606.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2627 Trees 2677.1 General Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . 2687.1.1 TreeDenitionsandProperties . . . . . . . . . . . . . . 2697.1.2 TreeFunctions . . . . . . . . . . . . . . . . . . . . . . . 2727.1.3 A C++TreeInterface . . . . . . . . . . . . . . . . . . . 2737.1.4 ALinkedStructureforGeneralTrees. . . . . . . . . . . 2747.2 TreeTraversal Algorithms . . . . . . . . . . . . . . . . . . . 2757.2.1 DepthandHeight . . . . . . . . . . . . . . . . . . . . . 2757.2.2 PreorderTraversal . . . . . . . . . . . . . . . . . . . . . 2787.2.3 PostorderTraversal . . . . . . . . . . . . . . . . . . . . 2817.3 BinaryTrees . . . . . . . . . . . . . . . . . . . . . . . . . . . 2847.3.1 TheBinaryTreeADT. . . . . . . . . . . . . . . . . . . 2857.3.2 A C++BinaryTreeInterface . . . . . . . . . . . . . . . 2867.3.3 PropertiesofBinaryTrees . . . . . . . . . . . . . . . . 2877.3.4 ALinkedStructureforBinaryTrees . . . . . . . . . . . 2897.3.5 AVector-BasedStructureforBinaryTrees. . . . . . . . 2957.3.6 TraversalsofaBinaryTree . . . . . . . . . . . . . . . . 2977.3.7 TheTemplateFunctionPattern . . . . . . . . . . . . . 3037.3.8 RepresentingGeneralTreeswithBinaryTrees . . . . . . 3097.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310iimain 2011/1/13 9:10page xix#19iiiiiiContents xix8 HeapsandPriorityQueues 3218.1 ThePriorityQueueAbstractDataType . . . . . . . . . . . 3228.1.1 Keys,Priorities,andTotalOrderRelations. . . . . . . . 3228.1.2 Comparators . . . . . . . . . . . . . . . . . . . . . . . . 3248.1.3 ThePriorityQueueADT . . . . . . . . . . . . . . . . . 3278.1.4 A C++PriorityQueueInterface. . . . . . . . . . . . . . 3288.1.5 SortingwithaPriorityQueue. . . . . . . . . . . . . . . 3298.1.6 TheSTLpriorityqueueClass. . . . . . . . . . . . . . . 3308.2 ImplementingaPriorityQueuewithaList. . . . . . . . . . 3318.2.1 A C++PriorityQueueImplementationusingaList . . . 3338.2.2 Selection-SortandInsertion-Sort . . . . . . . . . . . . . 3358.3 Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3378.3.1 TheHeapDataStructure. . . . . . . . . . . . . . . . . 3378.3.2 CompleteBinaryTreesandTheirRepresentation . . . . 3408.3.3 ImplementingaPriorityQueuewithaHeap . . . . . . . 3448.3.4 C++Implementation . . . . . . . . . . . . . . . . . . . 3498.3.5 Heap-Sort . . . . . . . . . . . . . . . . . . . . . . . . . 3518.3.6 Bottom-UpHeapConstruction . . . . . . . . . . . . . 3538.4 AdaptablePriorityQueues . . . . . . . . . . . . . . . . . . . 3578.4.1 AList-BasedImplementation . . . . . . . . . . . . . . . 3588.4.2 Location-AwareEntries . . . . . . . . . . . . . . . . . . 3608.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3619 HashTables,Maps,andSkipLists 3679.1 Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3689.1.1 TheMapADT . . . . . . . . . . . . . . . . . . . . . . 3699.1.2 A C++MapInterface . . . . . . . . . . . . . . . . . . . 3719.1.3 TheSTLmapClass . . . . . . . . . . . . . . . . . . . . 3729.1.4 ASimpleList-BasedMapImplementation . . . . . . . . 3749.2 HashTables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3759.2.1 BucketArrays . . . . . . . . . . . . . . . . . . . . . . . 3759.2.2 HashFunctions . . . . . . . . . . . . . . . . . . . . . . 3769.2.3 HashCodes . . . . . . . . . . . . . . . . . . . . . . . . 3769.2.4 CompressionFunctions . . . . . . . . . . . . . . . . . . 3809.2.5 Collision-HandlingSchemes . . . . . . . . . . . . . . . . 3829.2.6 LoadFactorsandRehashing . . . . . . . . . . . . . . . 3869.2.7 A C++HashTableImplementation. . . . . . . . . . . . 3879.3 OrderedMaps . . . . . . . . . . . . . . . . . . . . . . . . . . 3949.3.1 OrderedSearchTablesandBinarySearch . . . . . . . . 3959.3.2 TwoApplicationsofOrderedMaps. . . . . . . . . . . . 3999.4 SkipLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402iimain 2011/1/13 9:10page xx#20iiiiiixx Contents9.4.1 SearchandUpdateOperationsinaSkipList . . . . . . 4049.4.2 AProbabilisticAnalysis ofSkipLists . . . . . . . . . 4089.5 Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . 4119.5.1 TheDictionaryADT . . . . . . . . . . . . . . . . . . . 4119.5.2 A C++DictionaryImplementation . . . . . . . . . . . . 4139.5.3 ImplementationswithLocation-AwareEntries . . . . . . 4159.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41710SearchTrees 42310.1BinarySearchTrees . . . . . . . . . . . . . . . . . . . . . . . 42410.1.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . 42610.1.2 UpdateOperations . . . . . . . . . . . . . . . . . . . . 42810.1.3 C++ImplementationofaBinarySearchTree . . . . . . 43210.2AVLTrees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43810.2.1 UpdateOperations . . . . . . . . . . . . . . . . . . . . 44010.2.2 C++ImplementationofanAVLTree . . . . . . . . . . . 44610.3SplayTrees . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45010.3.1 Splaying . . . . . . . . . . . . . . . . . . . . . . . . . . 45010.3.2 WhentoSplay . . . . . . . . . . . . . . . . . . . . . . . 45410.3.3 AmortizedAnalysisofSplaying . . . . . . . . . . . . 45610.4(2,4)Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46110.4.1 Multi-WaySearchTrees. . . . . . . . . . . . . . . . . . 46110.4.2 UpdateOperationsfor(2, 4)Trees . . . . . . . . . . . . 46710.5Red-BlackTrees . . . . . . . . . . . . . . . . . . . . . . . . . 47310.5.1 UpdateOperations . . . . . . . . . . . . . . . . . . . . 47510.5.2 C++ImplementationofaRed-BlackTree . . . . . . . . 48810.6Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49211Sorting,Sets,andSelection 49911.1Merge-Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50011.1.1 Divide-and-Conquer . . . . . . . . . . . . . . . . . . . . 50011.1.2 MergingArraysandLists . . . . . . . . . . . . . . . . . 50511.1.3 TheRunningTimeofMerge-Sort . . . . . . . . . . . . 50811.1.4 C++ImplementationsofMerge-Sort . . . . . . . . . . . 50911.1.5 Merge-SortandRecurrenceEquations . . . . . . . . . 51111.2Quick-Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51311.2.1 RandomizedQuick-Sort . . . . . . . . . . . . . . . . . . 52111.2.2 C++ImplementationsandOptimizations. . . . . . . . . 52311.3StudyingSortingthroughanAlgorithmicLens . . . . . . . 52611.3.1 ALowerBoundforSorting . . . . . . . . . . . . . . . . 52611.3.2 Linear-TimeSorting: Bucket-SortandRadix-Sort . . . . 52811.3.3 ComparingSortingAlgorithms . . . . . . . . . . . . . . 531iimain 2011/1/13 9:10page xxi #21iiiiiiContents xxi11.4SetsandUnion/FindStructures . . . . . . . . . . . . . . . . 53311.4.1 TheSetADT . . . . . . . . . . . . . . . . . . . . . . . 53311.4.2 MergableSetsandtheTemplateMethodPattern . . . . 53411.4.3 PartitionswithUnion-FindOperations . . . . . . . . . . 53811.5Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54211.5.1 Prune-and-Search . . . . . . . . . . . . . . . . . . . . . 54211.5.2 RandomizedQuick-Select . . . . . . . . . . . . . . . . . 54311.5.3 AnalyzingRandomizedQuick-Select . . . . . . . . . . . 54411.6Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54512StringsandDynamicProgramming 55312.1StringOperations . . . . . . . . . . . . . . . . . . . . . . . . 55412.1.1 TheSTLStringClass . . . . . . . . . . . . . . . . . . . 55512.2DynamicProgramming . . . . . . . . . . . . . . . . . . . . . 55712.2.1 MatrixChain-Product . . . . . . . . . . . . . . . . . . . 55712.2.2 DNAandTextSequenceAlignment . . . . . . . . . . . 56012.3PatternMatchingAlgorithms . . . . . . . . . . . . . . . . . 56412.3.1 BruteForce . . . . . . . . . . . . . . . . . . . . . . . . 56412.3.2 TheBoyer-MooreAlgorithm . . . . . . . . . . . . . . . 56612.3.3 TheKnuth-Morris-PrattAlgorithm. . . . . . . . . . . . 57012.4TextCompressionandtheGreedyMethod . . . . . . . . . 57512.4.1 TheHuman-CodingAlgorithm . . . . . . . . . . . . . 57612.4.2 TheGreedyMethod. . . . . . . . . . . . . . . . . . . . 57712.5Tries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57812.5.1 StandardTries. . . . . . . . . . . . . . . . . . . . . . . 57812.5.2 CompressedTries . . . . . . . . . . . . . . . . . . . . . 58212.5.3 SuxTries . . . . . . . . . . . . . . . . . . . . . . . . 58412.5.4 SearchEngines . . . . . . . . . . . . . . . . . . . . . . 58612.6Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58713GraphAlgorithms 59313.1Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59413.1.1 TheGraphADT. . . . . . . . . . . . . . . . . . . . . . 59913.2DataStructuresforGraphs. . . . . . . . . . . . . . . . . . . 60013.2.1 TheEdgeListStructure . . . . . . . . . . . . . . . . . . 60013.2.2 TheAdjacencyListStructure. . . . . . . . . . . . . . . 60313.2.3 TheAdjacencyMatrixStructure . . . . . . . . . . . . . 60513.3GraphTraversals . . . . . . . . . . . . . . . . . . . . . . . . . 60713.3.1 Depth-FirstSearch . . . . . . . . . . . . . . . . . . . . 60713.3.2 ImplementingDepth-FirstSearch. . . . . . . . . . . . . 61113.3.3 AGenericDFSImplementationin C++. . . . . . . . . . 61313.3.4 PolymorphicObjectsandDecoratorValues . . . . . . 621iimain 2011/1/13 9:10page xxii #22iiiiiixxii Contents13.3.5 Breadth-FirstSearch . . . . . . . . . . . . . . . . . . . 62313.4DirectedGraphs . . . . . . . . . . . . . . . . . . . . . . . . . 62613.4.1 TraversingaDigraph . . . . . . . . . . . . . . . . . . . 62813.4.2 TransitiveClosure . . . . . . . . . . . . . . . . . . . . . 63013.4.3 DirectedAcyclicGraphs. . . . . . . . . . . . . . . . . . 63313.5ShortestPaths . . . . . . . . . . . . . . . . . . . . . . . . . . 63713.5.1 WeightedGraphs . . . . . . . . . . . . . . . . . . . . . 63713.5.2 DijkstrasAlgorithm. . . . . . . . . . . . . . . . . . . . 63913.6MinimumSpanningTrees . . . . . . . . . . . . . . . . . . . . 64513.6.1 KruskalsAlgorithm. . . . . . . . . . . . . . . . . . . . 64713.6.2 ThePrim-JarnkAlgorithm. . . . . . . . . . . . . . . . 65113.7Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65414MemoryManagementandB-Trees 66514.1MemoryManagement. . . . . . . . . . . . . . . . . . . . . . 66614.1.1 MemoryAllocationin C++ . . . . . . . . . . . . . . . . 66914.1.2 GarbageCollection . . . . . . . . . . . . . . . . . . . . 67114.2External MemoryandCaching. . . . . . . . . . . . . . . . . 67314.2.1 TheMemoryHierarchy . . . . . . . . . . . . . . . . . . 67314.2.2 CachingStrategies . . . . . . . . . . . . . . . . . . . . 67414.3External SearchingandB-Trees . . . . . . . . . . . . . . . . 67914.3.1 (a, b)Trees . . . . . . . . . . . . . . . . . . . . . . . . 68014.3.2 B-Trees . . . . . . . . . . . . . . . . . . . . . . . . . . 68214.4External-MemorySorting. . . . . . . . . . . . . . . . . . . . 68314.4.1 Multi-WayMerging . . . . . . . . . . . . . . . . . . . . 68414.5Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685A Useful Mathematical Facts 689Bibliography 697Index 702iimain 2011/1/13 9:10page 1#23iiiiiiChapter1A C++PrimerContents1.1 BasicC++ProgrammingElements . . . . . . . . . . . 21.1.1 ASimple C++Program. . . . . . . . . . . . . . . . 21.1.2 FundamentalTypes . . . . . . . . . . . . . . . . . . 41.1.3 Pointers,Arrays,andStructures . . . . . . . . . . . 71.1.4 NamedConstants,Scope,andNamespaces . . . . . 131.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . 161.2.1 ChangingTypesthroughCasting . . . . . . . . . . . 201.3 Control Flow. . . . . . . . . . . . . . . . . . . . . . . 231.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . 261.4.1 ArgumentPassing. . . . . . . . . . . . . . . . . . . 281.4.2 OverloadingandInlining . . . . . . . . . . . . . . . 301.5 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 321.5.1 ClassStructure . . . . . . . . . . . . . . . . . . . . 331.5.2 ConstructorsandDestructors . . . . . . . . . . . . . 371.5.3 ClassesandMemoryAllocation. . . . . . . . . . . . 401.5.4 ClassFriendsandClassMembers. . . . . . . . . . . 431.5.5 TheStandardTemplateLibrary. . . . . . . . . . . . 451.6 C++ProgramandFileOrganization . . . . . . . . . . 471.6.1 AnExampleProgram. . . . . . . . . . . . . . . . . 481.7 WritingaC++Program. . . . . . . . . . . . . . . . . 531.7.1 Design . . . . . . . . . . . . . . . . . . . . . . . . . 541.7.2 Pseudo-Code . . . . . . . . . . . . . . . . . . . . . 541.7.3 Coding. . . . . . . . . . . . . . . . . . . . . . . . . 551.7.4 TestingandDebugging . . . . . . . . . . . . . . . . 571.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 60iimain 2011/1/13 9:10page 2#24iiiiii2 Chapter 1. A C++ Primer1.1 BasicC++ProgrammingElementsBuilding data structuresand algorithms requires communicatinginstructionsto acomputer, and an excellentway to performsuch communicationis using a high-level computerlanguage, such as C++. C++ evolved from the programminglan-guageC, and has,over time,undergonefurtherevolutionand developmentfromits originaldenition. It has incorporatedmany featuresthat were not part of C,such as symbolic constants, in-line function substitution, reference types, paramet-ric polymorphismthroughtemplates, and exceptions(which are discussedlater).As a result, C++ has grown to be a complex programming language. Fortunately,we do not need to know every detail of this sophisticated language in order to useit effectively.In this chapter and the next, we present a quick tour of the C++ programminglanguage and its features. It would be impossible to present a complete presentationof the languagein this shortspace,however. Since we assume that the readerisalready familiar with programming with some other language,such as C or Java,our descriptions are short.This chapter presents the languages basic features, andin the followingchapter, we concentrateon thosefeaturesthatare importantforobject-oriented programming.C++ is a powerful and exible programming language, which was designed tobuild upon the constructs of the C programming language. Thus, with minor ex-ceptions, C++ is a superset of the C programming language. C++ shares Cs abilityto deal efciently with hardware at the level of bits, bytes,words, addresses,etc.Inaddition, C++addsseveral enhancementsoverC(whichmotivatesthenameC++), withtheprincipal enhancement beingtheobject-orientedconcept ofaclass.A classis a user-denedtypethatencapsulatesmany importantmechanismssuch as guaranteed initialization, implicit type conversion, control of memory man-agement, operator overloading, and polymorphism (which are all important topicsthatare discussedlaterin this book). A classalso has the abilityto hideits un-derlying data. This allows a class to conceal its implementation details and allowsusers to conceptualize the class in terms of a well-dened interface. Classes enableprogrammers to break an application up into small, manageable pieces, or objects.The resulting programs are easier to understand and easier to maintain.1.1.1 ASimple C++ProgramLike many programming languages, creating and running a C++ program requiresseveral steps. First, we create a C++ source le into which we enter the lines of ourprogram. After we save this le, we then run a program, called a compiler, whichiimain 2011/1/13 9:10page 3#25iiiiii1.1. Basic C++ Programming Elements 3createsamachine-codeinterpretationofthisprogram. Anotherprogram, calleda linker (which is typically invoked automaticallyby the compiler),includes anyrequired library code functions needed and produces the nal machine-executablele. In order to run our program, the user requests that the system execute this le.Let us consider a very simple program to illustrate some of the languages basicelements. Dont worry if some elements in this example are not fully explained. Wediscuss them in greater depth later in this chapter. This program inputs two integers,which are stored in the variables x and y. It then computes their sum and stores theresult in a variable sum, and nally it outputs this sum. (The line numbers are notpart of the program; they are just for our reference.)1 #include2 #include3 /* Thisprograminputstwonumbersxandyandoutputstheir sum*/4 intmain() {5 intx, y;6 std::coutx>>y; //inputxandy8 intsum=x+y; //computetheir sum9 std::cout


Recommended