id
int64
0
25.6k
text
stringlengths
0
4.59k
23,300
programminga general overview clearlyn is larger than pk soby assumptionn is not prime howevernone of pk divides exactlybecause there will always be remainder of this is contradictionbecause every number is either prime or product of primes hencethe original assumptionthat pk is the largest primeis falsewhich implies that the theorem is true brief introduction to recursion most mathematical functions that we are familiar with are described by simple formula for instancewe can convert temperatures from fahrenheit to celsius by applying the formula ( )/ given this formulait is trivial to write +functionwith declarations and braces removedthe one-line formula translates to one line of +mathematical functions are sometimes defined in less standard form as an examplewe can define function fvalid on nonnegative integersthat satisfies ( and ( ( from this definition we see that ( ( ( and ( function that is defined in terms of itself is called recursive +allows functions to be recursive it is important to remember that what +provides is merely an attempt to follow the recursive spirit not all mathematically recursive functions are efficiently (or correctlyimplemented by ++' simulation of recursion the idea is that the recursive function ought to be expressible in only few linesjust like nonrecursive function figure shows the recursive implementation of lines and handle what is known as the base casethat isthe value for which the function is directly known without resorting to recursion just as declaring ( ( is meaninglessmathematicallywithout including the fact that ( the recursive +function doesn' make sense without base case line makes the recursive call int fint ifx = return else return fx xfigure recursive function using recursion for numerical calculations is usually bad idea we have done so to illustrate the basic points
23,301
there are several important and possibly confusing points about recursion common question isisn' this just circular logicthe answer is that although we are defining function in terms of itselfwe are not defining particular instance of the function in terms of itself in other wordsevaluating ( by computing ( would be circular evaluating ( by computing ( is not circular--unlessof coursef( is evaluated by eventually computing ( the two most important issues are probably the how and why questions in the how and why issues are formally resolved we will give an incomplete description here it turns out that recursive calls are handled no differently from any others if is called with the value of then line requires the computation of ( thusa call is made to compute ( this requires the computation of ( thereforeanother call is made to compute ( this means that ( must be evaluated to do sof( is computed as * ( )+ * nowf( must be evaluated since this is base casewe know priori that ( this enables the completion of the calculation for ( )which is now seen to be then ( ) ( )and finally ( can be determined all the bookkeeping needed to keep track of pending function calls (those started but waiting for recursive call to complete)along with their variablesis done by the computer automatically an important pointhoweveris that recursive calls will keep on being made until base case is reached for instancean attempt to evaluate (- will result in calls to (- ) (- )and so on since this will never get to base casethe program won' be able to compute the answer (which is undefined anywayoccasionallya much more subtle error is madewhich is exhibited in figure the error in figure is that bad( is definedby line to be bad( obviouslythis doesn' give any clue as to what bad( actually is the computer will thus repeatedly make calls to bad( in an attempt to resolve its values eventuallyits bookkeeping system will run out of spaceand the program will terminate abnormally generallywe would say that this function doesn' work for one special case but is correct otherwise this isn' true heresince bad( calls bad( thusbad( cannot be evaluated either furthermorebad( )bad( )and bad( all make calls to bad( since bad( is not evaluablenone of these values are either in factthis program doesn' work for any nonnegative value of nexcept with recursive programsthere is no such thing as "special case these considerations lead to the first two fundamental rules of recursion base cases you must always have some base caseswhich can be solved without recursion making progress for the cases that are to be solved recursivelythe recursive call must always be to case that makes progress toward base case int badint ifn = return else return badn figure nonterminating recursive function
23,302
programminga general overview throughout this bookwe will use recursion to solve problems as an example of nonmathematical useconsider large dictionary words in dictionaries are defined in terms of other words when we look up wordwe might not always understand the definitionso we might have to look up words in the definition likewisewe might not understand some of thoseso we might have to continue this search for while because the dictionary is finiteeventually either ( we will come to point where we understand all of the words in some definition (and thus understand that definition and retrace our path through the other definitionsor ( we will find that the definitions are circular and we are stuckor that some word we need to understand for definition is not in the dictionary our recursive strategy to understand words is as followsif we know the meaning of wordthen we are doneotherwisewe look the word up in the dictionary if we understand all the words in the definitionwe are doneotherwisewe figure out what the definition means by recursively looking up the words we don' know this procedure will terminate if the dictionary is well defined but can loop indefinitely if word is either not defined or circularly defined printing out numbers suppose we have positive integernthat we wish to print out our routine will have the heading printout(nassume that the only / routines available will take single-digit number and output it we will call this routine printdigitfor exampleprintdigit( will output recursion provides very clean solution to this problem to print out we need to first print out and then print out the second step is easily accomplished with the statement printdigit( % )but the first doesn' seem any simpler than the original problem indeed it is virtually the same problemso we can solve it recursively with the statement printout( / this tells us how to solve the general problembut we still need to make sure that the program doesn' loop indefinitely since we haven' defined base case yetit is clear that we still have something to do our base case will be printdigit(nif < now printout(nis defined for every positive number from to and larger numbers are defined in terms of smaller positive number thusthere is no cycle the entire function is shown in figure we have made no effort to do this efficiently we could have avoided using the mod routine (which can be very expensivebecause % / is true for positive void printoutint /print nonnegative ifn > printoutn )printdigitn )figure recursive routine to print an integer is the largest integer that is less than or equal to
23,303
recursion and induction let us prove (somewhatrigorously that the recursive number-printing program works to do sowe'll use proof by induction theorem the recursive number-printing algorithm is correct for > proof (by induction on the number of digits in nfirstif has one digitthen the program is trivially correctsince it merely makes call to printdigit assume then that printout works for all numbers of or fewer digits number of digits is expressed by its first digits followed by its least significant digit but the number formed by the first digits is exactly / whichby the inductive hypothesisis correctly printedand the last digit is mod so the program prints out any ( + )-digit number correctly thusby inductionall numbers are correctly printed this proof probably seems little strange in that it is virtually identical to the algorithm description it illustrates that in designing recursive programall smaller instances of the same problem (which are on the path to base casemay be assumed to work correctly the recursive program needs only to combine solutions to smaller problemswhich are "magicallyobtained by recursioninto solution for the current problem the mathematical justification for this is proof by induction this gives the third rule of recursion design rule assume that all the recursive calls work this rule is important because it means that when designing recursive programsyou generally don' need to know the details of the bookkeeping arrangementsand you don' have to try to trace through the myriad of recursive calls frequentlyit is extremely difficult to track down the actual sequence of recursive calls of coursein many cases this is an indication of good use of recursionsince the computer is being allowed to work out the complicated details the main problem with recursion is the hidden bookkeeping costs although these costs are almost always justifiablebecause recursive programs not only simplify the algorithm design but also tend to give cleaner coderecursion should not be used as substitute for simple for loop we'll discuss the overhead involved in recursion in more detail in section when writing recursive routinesit is crucial to keep in mind the four basic rules of recursion base cases you must always have some base caseswhich can be solved without recursion making progress for the cases that are to be solved recursivelythe recursive call must always be to case that makes progress toward base case design rule assume that all the recursive calls work compound interest rule never duplicate work by solving the same instance of problem in separate recursive calls
23,304
programminga general overview the fourth rulewhich will be justified (along with its nicknamein later sectionsis the reason that it is generally bad idea to use recursion to evaluate simple mathematical functionssuch as the fibonacci numbers as long as you keep these rules in mindrecursive programming should be straightforward +classes in this textwe will write many data structures all of the data structures will be objects that store data (usually collection of identically typed itemsand will provide functions that manipulate the collection in +(and other languages)this is accomplished by using class this section describes the +class basic class syntax class in +consists of its members these members can be either data or functions the functions are called member functions each instance of class is an object each object contains the data components specified in the class (unless the data components are statica detail that can be safely ignored for nowa member function is used to act on an object often member functions are called methods as an examplefigure is the intcell class in the intcell classeach instance of the intcell--an intcell object--contains single data member named storedvalue everything else in this particular class is method in our examplethere are four methods two of these methods are read and write the other two are special methods known as constructors let us describe some key features firstnotice the two labels public and private these labels determine visibility of class members in this exampleeverything except the storedvalue data member is public storedvalue is private member that is public may be accessed by any method in any class member that is private may only be accessed by methods in its class typicallydata members are declared privatethus restricting access to internal details of the classwhile methods intended for general use are made public this is known as information hiding by using private data memberswe can change the internal representation of the object without having an effect on other parts of the program that use the object this is because the object is accessed through the public member functionswhose viewable behavior remains unchanged the users of the class do not need to know internal details of how the class is implemented in many caseshaving this access leads to trouble for instancein class that stores dates using monthdayand yearby making the monthdayand year privatewe prohibit an outsider from setting these data members to illegal datessuch as feb howeversome methods may be for internal use and can be private in classall members are private by defaultso the initial public is not optional secondwe see two constructors constructor is method that describes how an instance of the class is constructed if no constructor is explicitly definedone that initializes the data members using language defaults is automatically generated the intcell class defines two constructors the first is called if no parameter is specified the second is called if an int parameter is providedand uses that int to initialize the storedvalue member
23,305
/* class for simulating an integer memory cell *class intcell public/*construct the intcell initial value is *intcellstoredvalue /*construct the intcell initial value is initialvalue *intcellint initialvalue storedvalue initialvalue/*return the stored value *int readreturn storedvalue/*change the stored value to *void writeint storedvalue xprivateint storedvalue}figure complete declaration of an intcell class extra constructor syntax and accessors although the class works as writtenthere is some extra syntax that makes for better code four changes are shown in figure (we omit comments for brevitythe differences are as followsdefault parameters the intcell constructor illustrates the default parameter as resultthere are still two intcell constructors defined one accepts an initialvalue the other is the zero-parameter
23,306
programminga general overview constructorwhich is implied because the one-parameter constructor says that initialvalue is optional the default value of signifies that is used if no parameter is provided default parameters can be used in any functionbut they are most commonly used in constructors initialization list the intcell constructor uses an initialization list (figure line prior to the body of the constructor the initialization list is used to initialize the data members directly in figure there' hardly differencebut using initialization lists instead of an assignment statement in the body saves time in the case where the data members are class types that have complex initializations in some cases it is required for instanceif data member is const (meaning that it is not changeable after the object has been constructed)then the data member' value can only be initialized in the initialization list alsoif data member is itself class type that does not have zero-parameter constructorthen it must be initialized in the initialization list line in figure uses the syntax storedvalueinitialvalue instead of the traditional storedvalueinitialvalue the use of braces instead of parentheses is new in ++ and is part of larger effort to provide uniform syntax for initialization everywhere generally speakinganywhere you can initializeyou can do so by enclosing initializations in braces (though there is one important exceptionin section relating to vectors /* class for simulating an integer memory cell *class intcell publicexplicit intcellint initialvalue storedvalueinitialvalue int readconst return storedvaluevoid writeint storedvalue xprivateint storedvalue}figure intcell class with revisions
23,307
explicit constructor the intcell constructor is explicit you should make all one-parameter constructors explicit to avoid behind-the-scenes type conversions otherwisethere are somewhat lenient rules that will allow type conversions without explicit casting operations usuallythis is unwanted behavior that destroys strong typing and can lead to hard-to-find bugs as an exampleconsider the followingintcell objobj /obj is an intcell /should not compiletype mismatch the code fragment above constructs an intcell object obj and then performs an assignment statement but the assignment statement should not workbecause the right-hand side of the assignment operator is not another intcell obj' write method should have been used instead howeverc+has lenient rules normallya one-parameter constructor defines an implicit type conversionin which temporary object is created that makes an assignment (or parameter to functioncompatible in this casethe compiler would attempt to convert obj /should not compiletype mismatch into intcell temporary obj temporarynotice that the construction of the temporary can be performed by using the oneparameter constructor the use of explicit means that one-parameter constructor cannot be used to generate an implicit temporary thussince intcell' constructor is declared explicitthe compiler will correctly complain that there is type mismatch constant member function member function that examines but does not change the state of its object is an accessor member function that changes the state is mutator (because it mutates the state of the objectin the typical collection classfor instanceisempty is an accessorwhile makeempty is mutator in ++we can mark each member function as being an accessor or mutator doing so is an important part of the design process and should not be viewed as simply comment indeedthere are important semantic consequences for instancemutators cannot be applied to constant objects by defaultall member functions are mutators to make member function an accessorwe must add the keyword const after the closing parenthesis that ends the parameter type list the const-ness is part of the signature const can be used with many different meanings the function declaration can have const in three different contexts only the const after closing parenthesis signifies an accessor other uses are described in sections and in the intcell classread is clearly an accessorit does not change the state of the intcell thus it is made constant member function at line if member function
23,308
programminga general overview is marked as an accessor but has an implementation that changes the value of any data membera compiler error is generated separation of interface and implementation the class in figure contains all the correct syntactic constructs howeverin +it is more common to separate the class interface from its implementation the interface lists the class and its members (data and functionsthe implementation provides implementations of the functions figure shows the class interface for intcellfigure shows the implementationand figure shows main routine that uses the intcell some important points follow preprocessor commands the interface is typically placed in file that ends with source code that requires knowledge of the interface must #include the interface file in our casethis is both the implementation file and the file that contains main occasionallya complicated project will have files including other filesand there is the danger that an interface might be read twice in the course of compiling file this can be illegal to guard against thiseach header file uses the preprocessor to define symbol when the class interface is read this is shown on the first two lines in figure the symbol nameintcell_hshould not appear in any other fileusuallywe construct it from the filename the first line of the interface file #ifndef intcell_h #define intcell_h /* class for simulating an integer memory cell *class intcell publicexplicit intcellint initialvalue )int readconstvoid writeint )privateint storedvalue}#endif figure intcell class interface in file intcell data members can be marked mutable to indicate that const-ness should not apply to them
23,309
#include "intcell /*construct the intcell with initialvalue *intcell::intcellint initialvalue storedvalueinitialvalue /*return the stored value *int intcell::readconst return storedvalue/*store *void intcell::writeint storedvalue xfigure intcell class implementation in file intcell cpp #include #include "intcell husing namespace stdint mainintcell mm write )cout <"cell contents< read<endlreturn figure program that uses intcell in file testintcell cpp
23,310
programminga general overview tests whether the symbol is undefined if sowe can process the file otherwisewe do not process the file (by skipping to the #endif)because we know that we have already read the file scope resolution operator in the implementation filewhich typically ends in cppccor ceach member function must identify the class that it is part of otherwiseit would be assumed that the function is in global scope (and zillions of errors would resultthe syntax is classname::member the :is called the scope resolution operator signatures must match exactly the signature of an implemented member function must match exactly the signature listed in the class interface recall that whether member function is an accessor (via the const at the endor mutator is part of the signature thus an error would result iffor examplethe const was omitted from exactly one of the read signatures in figures and note that default parameters are specified in the interface only they are omitted in the implementation objects are declared like primitive types in classic ++an object is declared just like primitive type thus the following are legal declarations of an intcell objectintcell obj intcell obj )/zero parameter constructor /one parameter constructor on the other handthe following are incorrectintcell obj intcell obj )/constructor is explicit /function declaration the declaration of obj is illegal because the one-parameter constructor is explicit it would be legal otherwise (in other wordsin classic + declaration that uses the oneparameter constructor must use the parentheses to signify the initial value the declaration for obj states that it is function (defined elsewherethat takes no parameters and returns an intcell the confusion of obj is one reason for the uniform initialization syntax using braces it was ugly that initializing with zero parameter in constructor initialization list (fig line would require parentheses with no parameterbut the same syntax would be illegal elsewhere (for obj in ++ we can instead writeintcell obj intcell obj }intcell obj }/zero parameter constructorsame as before /one parameter constructorsame as before /zero parameter constructor the declaration of obj is nicer because initialization with zero-parameter constructor is no longer special syntax casethe initialization style is uniform
23,311
#include #include using namespace stdint mainvector squares )forint squares size)++ squaresi iforint squares size)++ cout < <<squaresi <endlreturn figure using the vector classstores squares and outputs them vector and string the +standard defines two classesthe vector and string vector is intended to replace the built-in +arraywhich causes no end of trouble the problem with the built-in +array is that it does not behave like first-class object for instancebuilt-in arrays cannot be copied with = built-in array does not remember how many items it can storeand its indexing operator does not check that the index is valid the built-in string is simply an array of charactersand thus has the liabilities of arrays plus few more for instance=does not correctly compare two built-in strings the vector and string classes in the stl treat arrays and strings as first-class objects vector knows how large it is two string objects can be compared with ==<and so on both vector and string can be copied with if possibleyou should avoid using the built-in +array and string we discuss the built-in array in in the context of showing how vector can be implemented vector and string are easy to use the code in figure creates vector that stores one hundred perfect squares and outputs them notice also that size is method that returns the size of the vector nice feature of the vector that we explore in is that it is easy to change its size in many casesthe initial size is and the vector grows as needed +has long allowed initialization of built-in +arraysint daysinmonth }it was annoying that this syntax was not legal for vectors in older ++vectors were either initialized with size or possibly by specifying size sofor instancewe would write
23,312
programminga general overview vector daysinmonth )/no {before ++ daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth daysinmonth certainly this leaves something to be desired ++ fixes this problem and allowsvector daysinmonth }requiring the in the initialization violates the spirit of uniform initializationsince now we would have to remember when it would be appropriate to use consequentlyc++ also allows (and some prefer)vector daysinmonth }with syntaxhowevercomes ambiguityas one sees with the declaration vector daysinmonth }is this vector of size or is it vector of size with single element in position ++ gives precedence to the initializer listso in fact this is vector of size with single element in position and if the intention is to initialize vector of size the old +syntax using parentheses must be usedvector daysinmonth )/must use (to call constructor that takes size string is also easy to use and has all the relational and equality operators to compare the states of two strings thus str ==str is true if the value of the strings are the same it also has length method that returns the string length as figure showsthe basic operation on arrays is indexing with [thusthe sum of the squares can be computed asint sum forint squares size)++ sum +squaresi ]the pattern of accessing every element sequentially in collection such as an array or vector is fundamentaland using array indexing for this purpose does not clearly express the idiom ++ adds range for syntax for this purpose the above fragment can be written instead asint sum forint squares sum +xin many casesthe declaration of the type in the range for statement is unneededif squares is vectorit is obvious that is intended to be an int thus ++ also allows the use of the reserved word auto to signify that the compiler will automatically infer the appropriate typeint sum forauto squares sum +
23,313
the range for loop is appropriate only if every item is being accessed sequentially and only if the index is not needed thusin figure the two loops cannot be rewritten as range for loopsbecause the index is also being used for other purposes the range for loop as shown so far allows only the viewing of itemschanging the items can be done using syntax described in section +details like any languagec+has its share of details and language features some of these are discussed in this section pointers pointer variable is variable that stores the address where another object resides it is the fundamental mechanism used in many data structures for instanceto store list of itemswe could use contiguous arraybut insertion into the middle of the contiguous array requires relocation of many items rather than store the collection in an arrayit is common to store each item in separatenoncontiguous piece of memorywhich is allocated as the program runs along with each object is link to the next object this link is pointer variablebecause it stores memory location of another object this is the classic linked list that is discussed in more detail in to illustrate the operations that apply to pointerswe rewrite figure to dynamically allocate the intcell it must be emphasized that for simple intcell classthere is no good reason to write the +code this way we do it only to illustrate dynamic memory allocation in simple context later in the textwe will see more complicated classeswhere this technique is useful and necessary the new version is shown in figure declaration line illustrates the declaration of the indicates that is pointer variableit is allowed to point at an intcell object the value of is the address of the object that it points at int mainintcell *mm new intcell } ->write )cout read<endldelete mreturn figure program that uses pointers to intcell (there is no compelling reason to do this
23,314
programminga general overview is uninitialized at this point in ++no such check is performed to verify that is assigned value prior to being used (howeverseveral vendors make products that do additional checksincluding this onethe use of uninitialized pointers typically crashes programsbecause they result in access of memory locations that do not exist in generalit is good idea to provide an initial valueeither by combining lines and or by initializing to the nullptr pointer dynamic object creation line illustrates how objects can be created dynamically in +new returns pointer to the newly created object in +there are several ways to create an object using its zero-parameter constructor the following would be legalm new intcell) new intcell} new intcell/ok / ++ /preferred in this text we generally use the last form because of the problem illustrated by obj in section garbage collection and delete in some languageswhen an object is no longer referencedit is subject to automatic garbage collectionthe programmer does not have to worry about it +does not have garbage collection when an object that is allocated by new is no longer referencedthe delete operation must be applied to the object (through pointerotherwisethe memory that it consumes is lost (until the program terminatesthis is known as memory leak memory leaks areunfortunatelycommon occurrences in many +programs fortunatelymany sources of memory leaks can be automatically removed with care one important rule is to not use new when an automatic variable can be used instead in the original programthe intcell is not allocated by new but instead is allocated as local variable in that casethe memory for the intcell is automatically reclaimed when the function in which it is declared returns the delete operator is illustrated at line of figure assignment and comparison of pointers assignment and comparison of pointer variables in +is based on the value of the pointermeaning the memory address that it stores thus two pointer variables are equal if they point at the same object if they point at different objectsthe pointer variables are not equaleven if the objects being pointed at are themselves equal if lhs and rhs are pointer variables (of compatible types)then lhs=rhs makes lhs point at the same object that rhs points at accessing members of an object through pointer if pointer variable points at class typethen (visiblemember of the object being pointed at can be accessed via the -operator this is illustrated at lines and of figure throughout this textwe use lhs and rhs to signify left-hand side and right-hand side of binary operator
23,315
address-of operator (&one important operator is the address-of operator this operator returns the memory location where an object resides and is useful for implementing an alias test that is discussed in section lvaluesrvaluesand references in addition to pointer typesc+defines reference types one of the major changes in ++ is the creation of new reference typeknown as an rvalue reference in order to discuss rvalue referencesand the more standard lvalue referencewe need to discuss the concept of lvalues and rvalues note that the precise rules are complexand we provide general description rather than focusing on the corner cases that are important in language specification and for compiler writers an lvalue is an expression that identifies non-temporary object an rvalue is an expression that identifies temporary object or is value (such as literal constantnot associated with any object as examplesconsider the followingvector arr )const int int yint ystring str "foo"vector *ptr &arrwith these declarationsarrstrarr[ ]&xyzptr*ptr(*ptr)[xare all lvalues additionallyx is also an lvaluealthough it is not modifiable lvalue as general ruleif you have name for variableit is an lvalueregardless of whether it is modifiable for the above declarations "foo" +ystr substr( , are all rvalues and "fooare rvalues because they are literals intuitivelyx+ is an rvalue because its value is temporaryit is certainly not or ybut it is stored somewhere prior to being assigned to similar logic applies for str substr( , notice the consequence that there are some cases in which the result of function call or operator call can be an lvalue (since *ptr and arr[xgenerate lvaluesas does cin>> >> and others where it can be an rvaluehencethe language syntax allows function call or operator overload to specify this in the return typeand this aspect is discussed in section intuitivelyif the function call computes an expression whose value does not exist prior to the call and does not exist once the call is finished unless it is copied somewhereit is likely to be an rvalue reference type allows us to define new name for an existing value in classic ++ reference can generally only be name for an lvaluesince having reference to temporary would lead to the ability to access an object that has theoretically been declared as no longer neededand thus may have had its resources reclaimed for another object howeverin ++ we can have two types of referenceslvalue references and rvalue references
23,316
programminga general overview in ++ an lvalue reference is declared by placing an after some type an lvalue reference then becomes synonym ( another namefor the object it references for instancestring str "hell"string rstr str/rstr is another name for str rstr +' '/changes str to "hellobool cond (&str =&rstr)/truestr and rstr are same object string bad "hello"/illegal"hellois not modifiable lvalue string bad str ""/illegalstr+"is not an lvalue string sub str substr )/illegalstr substr is not an lvalue in ++ an rvalue reference is declared by placing an &after some type an rvalue reference has the same characteristics as an lvalue reference except thatunlike an lvalue referencean rvalue reference can also reference an rvalue ( temporaryfor instancestring str "hell"string &bad "hello"/legal string &bad str ""/legal string &sub str substr )/legal whereas lvalue references have several clear uses in ++the utility of rvalue references is not obvious several uses of lvalue references will be discussed nowrvalue references are deferred until section lvalue references use # aliasing complicated names the simplest usewhich we will see in is to use local reference variable solely for the purpose of renaming an object that is known by complicated expression the code we will see is similar to the followingauto whichlist thelistsmyhashxthelists size]iffindbeginwhichlist )endwhichlist ) !endwhichlist return falsewhichlist push_backx ) reference variable is used so that the considerably more complex expression thelists[myhash( ,thelists size())does not have to be written (and then evaluatedfour times simply writing auto whichlist thelistsmyhashxthelists size]would not workit would create copyand then the push_back operation on the last line would be applied to the copynot the original lvalue references use # range for loops second use is in the range for statement suppose we would like to increment by all values in vector this is easy with for loopforint arr size)++ ++arri ]
23,317
but of coursea range for loop would be more elegant unfortunatelythe natural code does not workbecause assumes copy of each value in the vector forauto arr ++ /broken what we really want is for to be another name for each value in the vectorwhich is easy to do if is referenceforauto arr /works ++xlvalue references use # avoiding copy suppose we have function findmax that returns the largest value in vector or other large collection then given vector arrif we invoke findmaxwe would naturally write auto findmaxarr )howevernotice that if the vector stores large objectsthen the result is that will be copy of the largest value in arr if we need copy for some reasonthat is finehoweverin many instanceswe only need the value and will not make any changes to in such caseit would be more efficient to declare that is another name for the largest value in arrand hence we would declare to be reference (auto will deduce constnessif auto is not usedthen typically non-modifiable reference is explicitly stated with const)auto findmaxarr )normallythis means that findmax would also specify return type that indicates reference variable (section this code illustrates two important concepts reference variables are often used to avoid copying objects across function-call boundaries (either in the function call or the function return syntax is needed in function declarations and returns to enable the passing and returning using references instead of copies parameter passing many languagesc and java includedpass all parameters using call-by-valuethe actual argument is copied into the formal parameter howeverparameters in +could be large complex objects for which copying is inefficient additionallysometimes it is desirable to be able to alter the value being passed in as result of thisc+has historically had three different ways to pass parametersand ++ has added fourth we will begin by describing the three parameter-passing mechanisms in classic +and then explain the new parameter-passing mechanism that has been recently added
23,318
programminga general overview to see the reasons why call-by-value is not sufficient as the only parameter-passing mechanism in ++consider the three function declarations belowdouble averagedouble adouble )/returns average of and void swapdouble adouble )/swaps and bwrong parameter types string randomitemvector arr )/returns random item in arrinefficient average illustrates an ideal use of call-by-value if we make call double averagexy )then call-by-value copies into ay into band then executes the code for the average function definition that is fully specified elsewhere presuming that and are local variables inaccessible to averageit is guaranteed that when average returnsx and are unchangedwhich is very desirable property howeverthis desirable property is exactly why call-by-value cannot work for swap if we make call swapxy )then call-by-value guarantees that regardless of how swap is implementedx and will remain unchanged what we need instead is to declare that and are referencesvoid swapdouble adouble )/swaps and bcorrect parameter types with this signaturea is synonym for xand is synonym for changes to and in the implementation of swap are thus changes to and this form of parameter passing has always been known as call-by-reference in +in ++ this is more technically call-by-lvalue-referencebut we will use call-by-reference throughout this text to refer to this style of parameter passing the second problem with call-by-value is illustrated in randomitem this function intends to return random item from the vector arrin principlethis is quick operation consisting of the generation of "randomnumber between and arr size()- inclusivein order to determine an array index and the returning of the item at this randomly chosen array index but using call-by-value as the parameter-passing mechanism forces the copy of the vector vec in the call randomitem(vecthis is tremendously expensive operation compared to the cost of computing and returning randomly chosen array index and is completely unnecessary normallythe only reason to make copy is to make changes to the copy while preserving the original but randomitem doesn' intend to make any changes at allit is just viewing arr thuswe can avoid the copy but achieve the same semantics by declaring that arr is constant reference to vecas resultarr is synonym for vecwith no copybut since it is constit cannot be modified this essentially provides the same viewable behavior as call-by-value the signature would be string randomitemconst vector arr )/returns random item in arr this form of parameter passing is known as call-by-reference-to- -constant in ++but as that is overly verbose and the const precedes the &it is also known by the simpler terminology of call-by-constant reference the parameter-passing mechanism for +prior to ++ can thus generally be decided by two-part test
23,319
if the formal parameter should be able to change the value of the actual argumentthen you must use call-by-reference otherwisethe value of the actual argument cannot be changed by the formal parameter if the type is primitive typeuse call-by-value otherwisethe type is class type and is generally passed using call-by-constant-referenceunless it is an unusually small and easily copyable type ( type that stores two or fewer primitive typesput another way call-by-value is appropriate for small objects that should not be altered by the function call-by-constant-reference is appropriate for large objects that should not be altered by the function and are expensive to copy call-by-reference is appropriate for all objects that may be altered by the function because ++ adds rvalue referencethere is fourth way to pass parameterscall-byrvalue-reference the central concept is that since an rvalue stores temporary that is about to be destroyedan expression such as =rval (where rval is an rvaluecan be implemented by move instead of copyoften moving an object' state is much easier than copying itas it may involve just simple pointer change what we see here is that = can be copy if is an lvaluebut move if is an rvalue this gives primary use case of overloading function based on whether parameter is an lvalue or rvaluesuch asstring randomitemconst vector arr )string randomitemvector &arr )/returns random item in lvalue arr /returns random item in rvalue arr vector "hello""world}cout <randomitemv <endl/invokes lvalue method cout <randomitem"hello""world<endl/invokes rvalue method it is easy to test that with both functions writtenthe second overload is called on rvalueswhile the first overload is called on lvaluesas shown above the most common use of this idiom is in defining the behavior of and in writing constructorsand this discussion is deferred until section return passing in ++there are several different mechanisms for returning from function the most straightforward mechanism to use is return-by-valueas shown in these signaturesdouble averagedouble adouble )largetype randomitemconst vector arr )vector partialsumconst vector arr )/returns average of and /potentially inefficient /efficient in ++ these signatures all convey the basic idea that the function returns an object of an appropriate type that can be used by the callerin all cases the result of the function call is an rvalue howeverthe call to randomitem has potential inefficiencies the call to partialsum similarly has potential inefficienciesthough in ++ the call is likely to be very efficient
23,320
programminga general overview vector veclargetype item randomitem vec )largetype item randomitem vec )const largetype item randomitem vec )largetype randomitem const vector arr return arrrandomint arr size ]const largetype randomitem const vector arr return arrrandomint arr size ]/copy /copy /no copy figure two versions to obtain random item in an arraysecond version avoids creation of temporary largetype objectbut only if caller accesses it with constant reference firstconsider two implementations of randomitem the first implementationshown in lines - of figure uses return-by-value as resultthe largetype at the random array index will be copied as part of the return sequence this copy is done becausein generalreturn expressions could be rvalues ( return + and hence will not logically exist by the time the function call returns at line but in this casethe return type is an lvalue that will exist long after the function call returnssince arr is the same as vec the second implementation shown at lines - takes advantage of this and uses returnby-constant-reference to avoid an immediate copy howeverthe caller must also use constant reference to access the return valueas shown at line otherwisethere will still be copy the constant reference signifies that we do not want to allow changes to be made by the caller by using the return valuein this case it is needed since arr itself is non-modifiable vector an alternative is to use auto at line to declare item figure illustrates similar situation in which call-by-value was inefficient in classic +due to the creation and eventual cleanup of copy historicallyc+programmers have gone to great extent to rewrite their code in an unnatural wayusing techniques involving pointers or additional parameters that decrease readability and maintainabilityeventually leading to programming errors in ++ objects can define move semantics that can be employed when return-by-value is seenin effectthe result vector will be moved to sumsand the vector implementation is optimized to allow this to be done with little more than pointer change this means that partialsum as shown in figure can be expected to avoid unnecessary copying and not need any changes the details on how move semantics are implemented are discussed in section vector implementation is discussed in section notice that the move semantics can be called on result at line in figure but not on the returned expression at line in figure this is consequence of the distinction between temporary and non-temporaryand the distinction between an lvalue reference and an rvalue reference
23,321
vector partialsumconst vector arr vector resultarr size)result arr ]forint arr size)++ resulti resulti arri ]return resultvector vecvector sums partialsumvec )/copy in old ++move in ++ figure returning of stack-allocated rvalue in ++ in addition to the return-by-value and return-by-constant-reference idiomsfunctions can use return-by-reference this idiom is used in few places to allow the caller of function to have modifiable access to the internal data representation of class return-byreference in this context is discussed in section when we implement simple matrix class std::swap and std::move throughout this sectionwe have discussed instances in which ++ allows the programmer to easily replace expensive copies with moves yet another example of this is the implementation of swap routine swapping doubles is easily implemented with three copiesas shown in figure howeveralthough the same logic works to swap larger typesit comes with significant costnow the copies are very expensivehoweverit is easy to see that there is no need to copywhat we actually want is to do moves instead of copies in ++ if the right-hand side of the assignment operator (or constructoris an rvaluethen if the object supports movingwe can automatically avoid copies in other wordsif vector supports efficient movingand if at line were an rvaluethen could be moved into tmpsimilarlyif was an rvalue at line then it could be moved in to vector does indeed support movinghoweverxyand tmp are all lvalues at lines (rememberif an object has nameit is an lvaluefigure shows how this problem is solvedan implementation of swap at lines - shows that we can use cast to treat the right-hand side of lines - as rvalues the syntax of static cast is dauntingfortunatelyfunction std::move exists that converts any lvalue (or rvalueinto an rvalue note that the name is misleadingstd::move doesn' move anythingratherit makes value subject to be moved use of std::move is also shown in revised implementation of swap at lines - of figure the swap function std::swap is also part of the standard library and will work for any type
23,322
programminga general overview void swapdouble xdouble double tmp xx yy tmpvoid swapvector xvector vector tmp xx yy tmpfigure swapping by three copies void swapvector xvector vector tmp static_cast &&> ) static_cast &&> ) static_cast &&>tmp )void swapvector xvector vector tmp std::movex ) std::movey ) std::movetmp )figure swapping by three movesfirst with type castsecond using std::move the big-fivedestructorcopy constructormove constructorcopy assignment operator=move assignment operatorin ++ classes come with five special functions that are already written for you these are the destructorcopy constructormove constructorcopy assignment operatorand move assignment operator collectively these are the big-five in many casesyou can accept the default behavior provided by the compiler for the big-five sometimes you cannot destructor the destructor is called whenever an object goes out of scope or is subjected to delete typicallythe only responsibility of the destructor is to free up any resources that were
23,323
acquired during the use of the object this includes calling delete for any corresponding newsclosing any files that were openedand so on the default simply applies the destructor on each data member copy constructor and move constructor there are two special constructors that are required to construct new objectinitialized to the same state as another object of the same type these are the copy constructor if the existing object is an lvalueand the move constructor if the existing object is an rvalue ( temporary that is about to be destroyed anywayfor any objectsuch as an intcell objecta copy constructor or move constructor is called in the following instancesr declaration with initializationsuch as intcell /copy construct if is lvaluemove construct if is rvalue intcell }/copy construct if is lvaluemove construct if is rvalue but not /assignment operatordiscussed later an object passed using call-by-value (instead of by or const &)whichas mentioned earliershould rarely be done anyway an object returned by value (instead of by or const &againa copy constructor is invoked if the object being returned is an lvalueand move constructor is invoked if the object being returned is an rvalue by defaultthe copy constructor is implemented by applying copy constructors to each data member in turn for data members that are primitive types (for instanceintdoubleor pointers)simple assignment is done this would be the case for the storedvalue data member in our intcell class for data members that are themselves class objectsthe copy constructor or move constructoras appropriatefor each data member' class is applied to that data member copy assignment and move assignment (operator=the assignment operator is called when is applied to two objects that have both been previously constructed lhs=rhs is intended to copy the state of rhs into lhs if rhs is an lvaluethis is done by using the copy assignment operatorif rhs is an rvalue ( temporary that is about to be destroyed anyway)this is done by using the move assignment operator by defaultthe copy assignment operator is implemented by applying the copy assignment operator to each data member in turn defaults if we examine the intcell classwe see that the defaults are perfectly acceptableso we do not have to do anything this is often the case if class consists of data members that are exclusively primitive types and objects for which the defaults make sensethe class defaults will usually make sense thus class whose data members are intdoublevectorstringand even vector can accept the defaults
23,324
programminga general overview the main problem occurs in class that contains data member that is pointer we will describe the problem and solutions in detail in for nowwe can sketch the problem suppose the class contains single data member that is pointer this pointer points at dynamically allocated object the default destructor does nothing to data members that are pointers (for good reason--recall that we must delete ourselvesfurthermorethe copy constructor and copy assignment operator both copy the value of the pointer rather than the objects being pointed at thuswe will have two class instances that contain pointers that point to the same object this is so-called shallow copy typicallywe would expect deep copyin which clone of the entire object is made thusas resultwhen class contains pointers as data membersand deep semantics are importantwe typically must implement the destructorcopy assignmentand copy constructors ourselves doing so removes the move defaultsso we also must implement move assignment and the move constructor as general ruleeither you accept the default for all five operationsor you should declare all fiveand explicitly definedefault (use the keyword default)or disallow each (use the keyword deletegenerally we will define all five for intcellthe signatures of these operations are ~intcell)intcellconst intcell rhs )intcellintcell &rhs )intcell operatorconst intcell rhs )intcell operatorintcell &rhs )/destructor /copy constructor /move constructor /copy assignment /move assignment the return type of operatoris reference to the invoking objectso as to allow chained assignments = = though it would seem that the return type should be const referenceso as to disallow nonsense such as ( = )=cthat expression is in fact allowed in +even for integer types hencethe reference return type (rather than the const reference return typeis customarily used but is not strictly required by the language specification if you write any of the big-fiveit would be good practice to explicitly consider all the othersas the defaults may be invalid or inappropriate in simple example in which debugging code is placed in the destructorno default move operations will be generated and although unspecified copy operations are generatedthat guarantee is deprecated and might not be in future version of the language thusit is best to explicitly list the copy-and-move operations again~intcellcout <"invoking destructor<endlintcellconst intcell rhs defaultintcellintcell &rhs defaultintcell operatorconst intcell rhs defaultintcell operatorintcell &rhs default/destructor /copy constructor /move constructor /copy assignment /move assignment alternativelywe could disallow all copying and moving of intcells intcellconst intcell rhs deleteintcellintcell &rhs deleteintcell operatorconst intcell rhs deleteintcell operatorintcell &rhs delete/no copy constructor /no move constructor /no copy assignment /no move assignment
23,325
if the defaults make sense in the routines we writewe will always accept them howeverif the defaults do not make sensewe will need to implement the destructorcopy-and-move constructorsand copy-and-move assignment operators when the default does not workthe copy assignment operator can generally be implemented by creating copy using the copy constructor and then swapping it with the existing object the move assignment operator can generally be implemented by swapping member by member when the defaults do not work the most common situation in which the defaults do not work occurs when data member is pointer type and the pointer is allocated by some object member function (such as the constructoras an examplesuppose we implement the intcell by dynamically allocating an intas shown in figure for simplicitywe do not separate the interface and implementation there are now numerous problems that are exposed in figure firstthe output is three seven though logically only should be the problem is that the default copy assignment operator and copy constructor copy the pointer storedvalue thus storedvalueb storedvalueand storedvalue all point at the same int value these copies are shallowthe pointers rather than the pointees are copied secondless obvious problem is memory leak the int initially allocated by ' constructor remains allocated and needs to be reclaimed the int allocated by ' constructor is no longer referenced by any pointer variable it also needs to be reclaimedbut we no longer have pointer to it to fix these problemswe implement the big-five the result (again without separation of interface and implementationis shown in figure as we can seeonce the destructor is implementedshallow copying would lead to programming errortwo intcell objects would have storedvalue pointing at the same int object once the first intcell object' destructor was invoked to reclaim the object that its storedvalue pointer was viewingthe second intcell object would have stale storedvalue pointer this is why ++ has deprecated the prior behavior that allowed default copy operations even if destructor was written class intcell publicexplicit intcellint initialvalue storedvalue new intinitialvalue }int readconst return *storedvaluevoid writeint *storedvalue xprivateint *storedvalue}figure data member is pointerdefaults are no good
23,326
programminga general overview int fintcell }intcell aintcell cc ba write )cout < read<endl < read<endl < read<endlreturn figure simple function that exposes problems in figure the copy assignment operator at lines - uses standard idiom of checking for aliasing at line ( self-assignmentin which the client is making call obj=objand then copying each data field in turn as needed on completionit returns reference to itself using *this in ++ copy assignment is often written using copy-and-swap idiomleading to an alternate implementation intcell operatorconst intcell rhs intcell copy rhsstd::swap*thiscopy )return *this/copy assignment line places copy of rhs into copy using the copy constructor then this copy is swapped into *thisplacing the old contents into copy on returna destructor is invoked for copycleaning up the old memory for intcell this is bit inefficientbut for other typesespecially those with many complex interacting data membersit can be reasonably good default notice that if swap were implemented using the basic copy algorithm in figure the copy-and-swap idiom would not workbecause there would be mutual nonterminating recursion in ++ we have basic expectation that swapping is implemented either with three moves or by swapping member by member the move constructor at lines and moves the data representation from rhs into *thisthen it sets rhsprimitive data (including pointersto valid but easily destroyed state note that if there is non-primitive datathen that data must be moved in the initialization list for exampleif there were also vector itemsthen the constructor would beintcellintcell &rhs storedvaluerhs storedvalue }itemsstd::moverhs items rhs storedvalue nullptr/move constructor
23,327
class intcell publicexplicit intcellint initialvalue storedvalue new intinitialvalue }~intcelldelete storedvalue/destructor intcellconst intcell rhs storedvalue new int*rhs storedvalue }/copy constructor intcellintcell &rhs storedvaluerhs storedvalue rhs storedvalue nullptr/move constructor intcell operatorconst intcell rhs ifthis !&rhs *storedvalue *rhs storedvaluereturn *this/copy assignment intcell operatorintcell &rhs std::swapstoredvaluerhs storedvalue )return *this/move assignment int readconst return *storedvaluevoid writeint *storedvalue xprivateint *storedvalue}figure data member is pointerbig-five is written finallythe move assignment operator at lines - is implemented as member-bymember swap note that sometimes it is implemented as single swap of objects in the same manner as the copy assignment operatorbut that only works if swap itself is implemented as member-by-member swap if swap is implemented as three movesthen we would have mutual nonterminating recursion -style arrays and strings the +language provides built-in -style array type to declare an arrayarr of integersone writesint arr ]
23,328
programminga general overview arr is actually pointer to memory that is large enough to store intsrather than first-class array type applying to arrays is thus an attempt to copy two pointer values rather than the entire arrayand with the declaration aboveit is illegalbecause arr is constant pointer when arr is passed to functiononly the value of the pointer is passedinformation about the size of the array is lost thusthe size must be passed as an additional parameter there is no index range checkingsince the size is unknown in the declaration abovethe size of the array must be known at compile time variable cannot replace if the size is unknownwe must explicitly declare pointer and allocate memory via new[for instanceint *arr new intn ]now arr behaves like arr except that it is not constant pointer thusit can be made to point at larger block of memory howeverbecause memory has been dynamically allocatedat some point it must be freed with delete[]delete arr otherwisea memory leak will resultand the leak could be significant if the array is large built-in -style strings are implemented as an array of characters to avoid having to pass the length of the stringthe special null-terminator '\ is used as character that signals the logical end of the string strings are copied by strcpycompared with strcmpand their length can be determined by strlen individual characters can be accessed by the array indexing operator these strings have all the problems associated with arraysincluding difficult memory managementcompounded by the fact that when strings are copiedit is assumed that the target array is large enough to hold the result when it is notdifficult debugging ensuesoften because room has not been left for the null terminator the standard vector class and string class are implemented by hiding the behavior of the built-in -style array and string discusses the vector class implementation it is almost always better to use the vector and string classbut you may be forced to use the -style when interacting with library routines that are designed to work with both and +it also is occasionally necessary (but this is rareto use the -style in section of code that must be optimized for speed templates consider the problem of finding the largest item in an array of items simple algorithm is the sequential scanin which we examine each item in orderkeeping track of the maximum as is typical of many algorithmsthe sequential scan algorithm is type independent by type independentwe mean that the logic of this algorithm does not depend on the type of items that are stored in the array the same logic works for an array of integersfloating-point numbersor any type for which comparison can be meaningfully defined throughout this textwe will describe algorithms and data structures that are type independent when we write +code for type-independent algorithm or data structurewe would prefer to write the code once rather than recode it for each different type
23,329
in this sectionwe will describe how type-independent algorithms (also known as generic algorithmsare written in +using the template we begin by discussing function templates then we examine class templates function templates function templates are generally very easy to write function template is not an actual functionbut instead is pattern for what could become function figure illustrates function template findmax the line containing the template declaration indicates that comparable is the template argumentit can be replaced by any type to generate function for instanceif call to findmax is made with vector as parameterthen function will be generated by replacing comparable with string figure illustrates that function templates are expanded automatically as needed it should be noted that an expansion for each new type generates additional codethis is known as code bloat when it occurs in large projects note also that the call findmax( will result in compile-time error this is because when comparable is replaced by intcellline in figure becomes illegalthere is no function defined for intcell thusit is customary to includeprior to any templatecomments that explain what assumptions are made about the template argument(sthis includes assumptions about what kinds of constructors are required because template arguments can assume any class typewhen deciding on parameterpassing and return-passing conventionsit should be assumed that template arguments are not primitive types that is why we have returned by constant reference not surprisinglythere are many arcane rules that deal with function templates most of the problems occur when the template cannot provide an exact match for the parameters but can come close (through implicit type conversionsthere must be ways to resolve /*return the maximum item in array assumes size comparable objects must provide operatorand operator*template const comparable findmaxconst vector int maxindex forint size)++ ifamaxindex ai maxindex ireturn amaxindex ]figure findmax function template
23,330
programminga general overview int mainvector )vector )vector )vector )/additional code to fill in the vectors not shown cout <findmaxv <endlcout <findmaxv <endlcout <findmaxv <endlcout <findmaxv <endl/okcomparable int /okcomparable double /okcomparable string /illegaloperatorundefined return figure using findmax function template ambiguitiesand the rules are quite complex note that if there is nontemplate and template and both matchthen the nontemplate gets priority also note that if there are two equally close approximate matchesthen the code is illegal and the compiler will declare an ambiguity class templates in the simplest versiona class template works much like function template figure shows the memorycell template memorycell is like the intcell classbut works for any type /* class for simulating memory cell *template class memorycell publicexplicit memorycellconst object initialvalue objectstoredvalueinitialvalue const object readconst return storedvaluevoid writeconst object storedvalue xprivateobject storedvalue}figure memorycell class template without separation
23,331
int mainmemorycell memorycell "hello} write ) writem read"world)cout < read<end < read<end return figure program that uses memorycell class template objectprovided that object has zero-parameter constructora copy constructorand copy assignment operator notice that object is passed by constant reference alsonotice that the default parameter for the constructor is not because might not be valid object insteadthe default parameter is the result of constructing an object with its zero-parameter constructor figure shows how the memorycell can be used to store objects of both primitive and class types notice that memorycell is not classit is only class template memorycell and memorycell are the actual classes if we implement class templates as single unitthen there is very little syntax baggage many class templates arein factimplemented this way becausecurrentlyseparate compilation of templates does not work well on many platforms thereforein many casesthe entire classwith its implementationmust be placed in file popular implementations of the stl follow this strategy an alternativediscussed in appendix ais to separate the interface and implementation of the class templates this adds extra syntax and baggage and historically has been difficult for compilers to handle cleanly to avoid the extra syntax throughout this textwe providewhen necessaryin the online codeclass templates with no separation of interface and implementation in the figuresthe interface is shown as if separate compilation was usedbut the member function implementations are shown as if separate compilation was avoided this allows us to avoid focusing on syntax objectcomparableand an example in this textwe repeatedly use object and comparable as generic types object is assumed to have zero-parameter constructoran operator=and copy constructor comparableas suggested in the findmax examplehas additional functionality in the form of operatorthat can be used to provide total order some of the data structures in use operator=in addition to operatornote that for the purpose of providing total ordera== if both < and < are falsethus the use of operator=is simply for convenience
23,332
programminga general overview class square publicexplicit squaredouble sides double getsideconst return sidedouble getareaconst return side sidedouble getperimeterconst return sidevoid printostream out cout const out <"(square <getside<")"bool operatorconst square rhs const return getsiderhs getside)privatedouble side}/define an output operator for square ostream operator<ostream outconst square rhs rhs printout )return outint mainvector square }square }square }cout <"largest square<findmaxv <endlreturn figure comparable can be class typesuch as square figure shows an example of class type that implements the functionality required of comparable and illustrates operator overloading operator overloading allows us to define the meaning of built-in operator the square class represents square by storing the length of side and defines operatorthe square class also provides zero-parameter constructoroperator=and copy constructor (all by defaultthusit has enough to be used as comparable in findmax
23,333
figure shows minimal implementation and also illustrates the widely used idiom for providing an output function for new class type the idiom is to provide public member functionnamed printthat takes an ostream as parameter that public member function can then be called by globalnonclass functionoperator<<that accepts an ostream and an object to output function objects in section we showed how function templates can be used to write generic algorithms as an examplethe function template in figure can be used to find the maximum item in an array howeverthe template has an important limitationit works only for objects that have an operatorfunction definedand it uses that operatoras the basis for all comparison decisions in many situationsthis approach is not feasible for instanceit is stretch to presume that rectangle class will implement operator<and even if it doesthe compareto method that it has might not be the one we want for instancegiven by- rectangle and -by- rectanglewhich is the larger rectanglethe answer would depend on whether we are using area or width to decide or perhaps if we are trying to fit the rectangle through an openingthe larger rectangle is the rectangle with the larger minimum dimension as second exampleif we wanted to find the maximum string (alphabetically lastin an array of stringsthe default operatordoes not ignore case distinctionsso "zebrawould be considered to precede "alligatoralphabeticallywhich is probably not what we want third example would occur if we had an array of pointers to objects (which would be common in advanced +programs that make use of feature known as inheritancewhich we do not make much use of in this textthe solutionin these casesis to rewrite findmax to accept as parameters an array of objects and comparison function that explains how to decide which of two objects is the larger and which is the smaller in effectthe array objects no longer know how to compare themselvesinsteadthis information is completely decoupled from the objects in the array an ingenious way to pass functions as parameters is to notice that an object contains both data and member functionsso we can define class with no data and one member functionand pass an instance of the class in effecta function is being passed by placing it inside an object this object is commonly known as function object figure shows the simplest implementation of the function object idea findmax takes second parameterwhich is generic type in order for the findmax template to expand without errorthe generic type must have member function named islessthanwhich takes two parameters of the first generic type (objectand returns bool otherwisean error will be generated at line when the template expansion is attempted by the compiler at line we can see that findmax is called by passing an array of string and an object that contains an islessthan method with two strings as parameters +function objects are implemented using this basic ideabut with some fancy syntax firstinstead of using function with namewe use operator overloading instead of the function being islessthanit is operator(secondwhen invoking operator()
23,334
programminga general overview /generic findmaxwith function objectversion # /preconditiona size template const object findmaxconst vector arrcomparator cmp int maxindex forint arr size)++ ifcmp islessthanarrmaxindex ]arri maxindex ireturn arrmaxindex ]class caseinsensitivecompare publicbool islessthanconst string lhsconst string rhs const return strcasecmplhs c_str)rhs c_str }int mainvector arr "zebra""alligator""crocodile}cout <findmaxarrcaseinsensitivecompare<endlreturn figure simplest idea of using function object as second parameter to findmaxoutput is zebra cmp operator()( ,ycan be shortened to cmp( , (in other wordsit looks like function calland consequently operator(is known as the function call operatoras resultthe name of the parameter can be changed to the more meaningful islessthanand the call is islessthan( ,ythirdwe can provide version of findmax that works without function object the implementation uses the standard library function object template less (defined in header file functionalto generate function object that imposes the normal default ordering figure shows the implementation using the more typicalsomewhat crypticc+idioms in we will give an example of class that needs to order the items it stores we will write most of the code using comparable and show the adjustments needed to use the function objects elsewhere in the bookwe will avoid the detail of function objects to keep the code as simple as possibleknowing that it is not difficult to add function objects later
23,335
/generic findmaxwith function objectc+style /preconditiona size template const object findmaxconst vector arrcomparator islessthan int maxindex forint arr size)++ ifislessthanarrmaxindex ]arri maxindex ireturn arrmaxindex ]/generic findmaxusing default ordering #include template const object findmaxconst vector arr return findmaxarrless)class caseinsensitivecompare publicbool operator)const string lhsconst string rhs const return strcasecmplhs c_str)rhs c_str }int mainvector arr "zebra""alligator""crocodile}cout <findmaxarrcaseinsensitivecompare<endlcout <findmaxarr <endlreturn figure using function object +stylewith second version of findmaxoutput is zebrathen crocodile
23,336
programminga general overview separate compilation of class templates like regular classesclass templates can be implemented either entirely in their declarationsor we can separate the interface from the implementation howevercompiler support for separate compilation of templates historically has been weak and platformspecific thusin many casesthe entire class template with its implementation is placed in single header file popular implementations of the standard library follow this strategy to implement class templates appendix describes the mechanics involved in the separate compilation of templates the declaration of the interface for template is exactly what you would expectthe member functions end with single semicoloninstead of providing an implementation but as shown in appendix athe implementation of the member functions can introduce complicated-looking syntaxespecially for complicated functions like operatorworsewhen compilingthe compiler will often complain about missing functionsand avoiding this problem requires platform-specific solutions consequentlyin the online code that accompanies the textwe implement all class templates entirely in its declaration in single header file we do so because it seems to be the only way to avoid compilation problems across platforms in the textwhen illustrating the codewe provide the class interface as if separate compilation was in ordersince that is easily presentablebut implementations are shown as in the online code in platformspecific mannerone can mechanically transform our single header file implementations into separate compilation implementations if desired see appendix for some of the different scenarios that might apply using matrices several algorithms in use two-dimensional arrayswhich are popularly known as matrices the +library does not provide matrix class howevera reasonable matrix class can quickly be written the basic idea is to use vector of vectors doing this requires additional knowledge of operator overloading for the matrixwe define operator[]namelythe array-indexing operator the matrix class is given in figure the data membersconstructorand basic accessors the matrix is represented by an array data member that is declared to be vector of vector the constructor first constructs array as having rows entries each of type vector that is constructed with the zero-parameter constructor thuswe have rows zero-length vectors of object the body of the constructor is then enteredand each row is resized to have cols columns thus the constructor terminates with what appears to be two-dimensional array the numrows and numcols accessors are then easily implementedas shown
23,337
#ifndef matrix_h #define matrix_h #include using namespace stdtemplate class matrix publicmatrixint rowsint cols arrayrows forauto thisrow array thisrow resizecols )matrixvectorv arrayv matrixvector& arraystd::movev const vector operator[]int row const return arrayrow ]vector operator[]int row return arrayrow ]int numrowsconst return array size)int numcolsconst return numrowsarray size privatevectorarray}#endif figure complete matrix class operator[the idea of operator[is that if we have matrix mthen [ishould return vector corresponding to row of matrix if this is donethen [ ][jwill give the entry in position for vector [ ]using the normal vector indexing operator thusthe matrix operator[returns vector rather than an object
23,338
programminga general overview we now know that operator[should return an entity of type vector should we use return-by-valuereturn-by-referenceor return-by-constant-referenceimmediately we eliminate return-by-valuebecause the returned entity is large but guaranteed to exist after the call thuswe are down to return-by-reference or return-by-constant-reference consider the following method (ignore the possibility of aliasing or incompatible sizesneither of which affects the algorithm)void copyconst matrix frommatrix to forint to numrows)++ toi fromi ]in the copy functionwe attempt to copy each row in matrix from into the corresponding row in matrix to clearlyif operator[returns constant referencethen to[icannot appear on the left side of the assignment statement thusit appears that operator[should return reference howeverif we did thatthen an expression such as from[ ]=to[iwould compilesince from[iwould not be constant vectoreven though from was constant matrix that cannot be allowed in good design so what we really need is for operator[to return constant reference for frombut plain reference for to in other wordswe need two versions of operator[]which differ only in their return types that is not allowed howeverthere is loopholesince member function const-ness ( whether function is an accessor or mutatoris part of the signaturewe can have the accessor version of operator[return constant referenceand have the mutator version return the simple reference thenall is well this is shown in figure big-five these are all taken care of automaticallybecause the vector has taken care of it thereforethis is all the code needed for fully functioning matrix class summary this sets the stage for the rest of the book the time taken by an algorithm confronted with large amounts of input will be an important criterion for deciding if it is good algorithm (of coursecorrectness is most important we will begin to address these issues in the next and will use the mathematics discussed here to establish formal model exercises write program to solve the selection problem let / draw table showing the running time of your program for various values of write program to solve the word puzzle problem
23,339
write function to output an arbitrary double number (which might be negativeusing only printdigit for / +allows statements of the form #include filename which reads filename and inserts its contents in place of the include statement include statements may be nestedin other wordsthe file filename may itself contain an include statementbutobviouslya file can' include itself in any chain write program that reads in file and outputs the file as modified by the include statements write recursive function that returns the number of in the binary representation of use the fact that this is equal to the number of in the representation of / plus if is odd write the routines with the following declarationsvoid permuteconst string str )void permuteconst string strint lowint high )the first routine is driver that calls the second and prints all the permutations of the characters in string str if str is "abc"then the strings that are output are abcacbbacbcacaband cba use recursion for the second routine prove the following formulasa log log(ab log evaluate following sumsthe = = = in  = estimate in/ what is (mod ) letfi be the fibonacci numbers as defined in section prove the followingn- = fi fn fn ph with ph ( )/  give precise closed-form expression for prove nthe following formulas = (    = =
23,340
programminga general overview design class templatecollectionthat stores collection of objects (in an array)along with the current size of the collection provide public functions isemptymakeemptyinsertremoveand contains contains(xreturns true if and only if an object that is equal to is present in the collection design class templateorderedcollectionthat stores collection of comparables (in an array)along with the current size of the collection provide public functions isemptymakeemptyinsertremovefindminand findmax findmin and findmax return references to the smallest and largestrespectivelycomparable in the collection explain what can be done if these operations are performed on an empty collection define rectangle class that provides getlength and getwidth using the findmax routines in figure write main that creates an array of rectangle and finds the largest rectangle first on the basis of area and then on the basis of perimeter for the matrix classadd resize member function and zero-parameter constructor references there are many good textbooks covering the mathematics reviewed in this small subset is [ ][ ][ ][ ][ ]and [ reference [ is specifically geared toward the analysis of algorithms it is the first volume of three-volume series that will be cited throughout this text more advanced material is covered in [ throughout this bookwe will assume knowledge of +for the most part[ describes the final draft standard of ++ andbeing written by the original designer of ++remains the most authoritative another standard reference is [ advanced topics in +are discussed in [ the two-part series [ gives great discussion of the many pitfalls in +the standard template librarywhich we will investigate throughout this textis described in [ the material in sections is meant to serve as an overview of the features that we will use in this text we also assume familiarity with pointers and recursion (the recursion summary in this is meant to be quick reviewwe will attempt to provide hints on their use where appropriate throughout the textbook readers not familiar with these should consult [ or any good intermediate programming textbook general programming style is discussed in several books some of the classics are [ ][ ]and [ albertson and hutchinsondiscrete mathematics with algorithmsjohn wiley sonsnew york bavelmath companion for computer sciencereston publishing co restonva brualdiintroductory combinatorics th ed pearsonbostonmass dijkstraa discipline of programmingprentice hallenglewood cliffsn eckelthinking in ++ ed prentice hallenglewood cliffsn grahamd knuthand patashnikconcrete mathematicsaddison-wesleyreadingmass griesthe science of programmingspringer-verlagnew york
23,341
kernighan and plaugerthe elements of programming style ed mcgraw-hillnew york knuththe art of computer programmingvol fundamental algorithms ed addison-wesleyreadingmass lippmanj lajoieand mooc+primer th ed pearsonbostonmass meyers specific ways to improve your programs and designs ed addison-wesleybostonmass meyersmore effective ++ new ways to improve your programs and designsaddisonwesleyreadingmass musserg durgeand sainistl tutorial and reference guidec+programming with the standard template library ed addison-wesleyreadingmass roberts and tesmanapplied combinatorics ed prentice hallenglewood cliffsn stroustropthe +programming language th ed pearsonbostonmass tuckerapplied combinatorics th ed john wiley sonsnew york weissalgorithmsdata structuresand problem solving with ++ nd ed addisonwesleyreadingmass
23,342
23,343
algorithm analysis an algorithm is clearly specified set of simple instructions to be followed to solve problem once an algorithm is given for problem and decided (somehowto be correctan important step is to determine how much in the way of resourcessuch as time or spacethe algorithm will require an algorithm that solves problem but requires year is hardly of any use likewisean algorithm that requires thousands of gigabytes of main memory is not (currentlyuseful on most machines in this we shall discuss how to estimate the time required for program how to reduce the running time of program from days or years to fractions of second the results of careless use of recursion very efficient algorithms to raise number to power and to compute the greatest common divisor of two numbers mathematical background the analysis required to estimate the resource use of an algorithm is generally theoretical issueand therefore formal framework is required we begin with some mathematical definitions throughout this bookwe will use the following four definitionsdefinition (no( ( )if there are positive constants and such that ( <cf(nwhen > definition ( ( ( )if there are positive constants and such that ( >cg(nwhen > definition ( ( ( )if and only if (no( ( )and ( ( ( )definition (no( ( )iffor all positive constants cthere exists an such that (ncp(nwhen less formallyt(no( ( )if (no( ( )and ( ( ( )
23,344
algorithm analysis the idea of these definitions is to establish relative order among functions given two functionsthere are usually points where one function is smaller than the other so it does not make sense to claimfor instancef(ng(nthuswe compare their relative rates of growth when we apply this to the analysis of algorithmswe shall see why this is the important measure although , is larger than for small values of nn grows at faster rateand thus will eventually be the larger function the turning point is , in this case the first definition says that eventually there is some point past which (nis always at least as large as ( )so that if constant factors are ignoredf(nis at least as big as (nin our casewe have ( , nf(nn , and we could also use and thuswe can say that , ( (order -squaredthis notation is known as big-oh notation frequentlyinstead of saying "order ,one says "big-oh if we use the traditional inequality operators to compare growth ratesthen the first definition says that the growth rate of (nis less than or equal to (<=that of (nthe second definitiont( ( ( )(pronounced "omega")says that the growth rate of (nis greater than or equal to (>=that of (nthe third definitiont( ( ( )(pronounced "theta")says that the growth rate of (nequals (=the growth rate of (nthe last definitiont(no( ( )(pronounced "little-oh")says that the growth rate of (nis less than (<the growth rate of (nthis is different from big-ohbecause big-oh allows the possibility that the growth rates are the same to prove that some function (no( ( ))we usually do not apply these definitions formally but instead use repertoire of known results in generalthis means that proof (or determination that the assumption is incorrectis very simple calculation and should not involve calculusexcept in extraordinary circumstances (not likely to occur in an algorithm analysiswhen we say that (no( ( ))we are guaranteeing that the function (ngrows at rate no faster than ( )thus (nis an upper bound on (nsince this implies that ( ( ( ))we say that (nis lower bound on (nas an examplen grows faster than so we can say that ( or ( (nn and ( grow at the same rateso both (no( ( )and ( ( ( )are true when two functions grow at the same ratethen the decision of whether or not to signify this with (can depend on the particular context intuitivelyif ( then (no( ) (no( )and (no( are all technically correctbut the last option is the best answer writing ( ( says not only that (no( but also that the result is as good (tightas possible here are the important things to knowrule if (no( ( )and (no( ( ))then (at (nt (no( (ng( )(intuitively and less formally it is (max( ( ) ( ))))(bt (nt (no( (ng( )rule if (nis polynomial of degree kthen ( (nk
23,345
function name log log log constant logarithmic log-squared linear quadratic cubic exponential figure typical growth rates rule logk (nfor any constant this tells us that logarithms grow very slowly this information is sufficient to arrange most of the common functions by growth rate (see fig several points are in order firstit is very bad style to include constants or low-order terms inside big-oh do not say (no( or (no( nin both casesthe correct form is (no( this means that in any analysis that will require big-oh answerall sorts of shortcuts are possible lower-order terms can generally be ignoredand constants can be thrown away considerably less precision is required in these cases secondwe can always determine the relative growth rates of two functions (nand (nby computing limnf( )/ ( )using 'hopital' rule if necessary the limit can have four possible valuesr the limit is this means that (no( ( ) the limit is this means that ( ( ( ) the limit is this means that (no( ( ) the limit does not existthere is no relation (this will not happen in our contextusing this method almost always amounts to overkill usually the relation between (nand (ncan be derived by simple algebra for instanceif (nn log and (nn then to decide which of (nand (ngrows fasterone really needs to determine which of log and grows faster this is like determining which of log or grows faster this is simple problembecause it is already known that grows faster than any power of log thusg(ngrows faster than (none stylistic noteit is bad to say ( < ( ( ))because the inequality is implied by the definition it is wrong to write ( > ( ( ))because it does not make sense nf(nand limng(nthen limnf( )/ (nlimnf ( )/ ( )where (nand (nare the derivatives of (nand ( )respectively 'hopital' rule states that if lim
23,346
algorithm analysis as an example of the typical kinds of analyses that are performedconsider the problem of downloading file over the internet suppose there is an initial -sec delay (to set up connection)after which the download proceeds at (bytes)/sec then it follows that if the file is megabytesthe time to download is described by the formula (nn/ this is linear function notice that the time to download , file ( , secis approximately (but not exactlytwice the time to download file ( secthis is typical of linear function noticealsothat if the speed of the connection doublesboth times decreasebut the , file still takes approximately twice the time to download as file this is the typical characteristic of linear-time algorithmsand it is the reason we write (no( )ignoring constant factors (although using big-theta would be more precisebig-oh answers are typically given observetoothat this behavior is not true of all algorithms for the first selection algorithm described in section the running time is controlled by the time it takes to perform sort for simple sorting algorithmsuch as the suggested bubble sortwhen the amount of input doublesthe running time increases by factor of four for large amounts of input this is because those algorithms are not linear insteadas we will see when we discuss sortingtrivial sorting algorithms are ( )or quadratic model in order to analyze algorithms in formal frameworkwe need model of computation our model is basically normal computer in which instructions are executed sequentially our model has the standard repertoire of simple instructionssuch as additionmultiplicationcomparisonand assignmentbutunlike the case with real computersit takes exactly one time unit to do anything (simpleto be reasonablewe will assume thatlike modern computerour model has fixed-size (say -bitintegers and no fancy operationssuch as matrix inversion or sortingwhich clearly cannot be done in one time unit we also assume infinite memory this model clearly has some weaknesses obviouslyin real lifenot all operations take exactly the same time in particularin our modelone disk reads counts the same as an additioneven though the addition is typically several orders of magnitude faster alsoby assuming infinite memorywe ignore the fact that the cost of memory access can increase when slower memory is used due to larger memory requirements what to analyze the most important resource to analyze is generally the running time several factors affect the running time of program somesuch as the compiler and computer usedare obviously beyond the scope of any theoretical modelsoalthough they are importantwe cannot deal with them here the other main factors are the algorithm used and the input to the algorithm typicallythe size of the input is the main consideration we define two functionstavg (nand tworst ( )as the average and worst-case running timerespectivelyused by an algorithm on input of size clearlytavg ( <tworst (nif there is more than one inputthese functions may have more than one argument
23,347
occasionallythe best-case performance of an algorithm is analyzed howeverthis is often of little interestbecause it does not represent typical behavior average-case performance often reflects typical behaviorwhile worst-case performance represents guarantee for performance on any possible input notice also thatalthough in this we analyze +codethese bounds are really bounds for the algorithms rather than programs programs are an implementation of the algorithm in particular programming languageand almost always the details of the programming language do not affect big-oh answer if program is running much more slowly than the algorithm analysis suggeststhere may be an implementation inefficiency this can occur in +when arrays are inadvertently copied in their entiretyinstead of passed with references another extremely subtle example of this is in the last two paragraphs of section thus in future we will analyze the algorithms rather than the programs generallythe quantity required is the worst-case timeunless otherwise specified one reason for this is that it provides bound for all inputincluding particularly bad inputwhich an average-case analysis does not provide the other reason is that average-case bounds are usually much more difficult to compute in some instancesthe definition of "averagecan affect the result (for instancewhat is average input for the following problem?as an examplein the next sectionwe shall consider the following problemmaximum subsequence sum problem  given (possibly negativeintegers an find the maximum value of = ak (for conveniencethe maximum subsequence sum is if all the integers are negative examplefor input - - - - the answer is ( through this problem is interesting mainly because there are so many algorithms to solve itand the performance of these algorithms varies drastically we will discuss four algorithms to solve this problem the running time on some computers (the exact computer is unimportantfor these algorithms is given in figure there are several important things worth noting in this table for small amount of inputthe algorithms all run in the blink of an eye so if only small amount of input is algorithm time input size , , , , , ( ( ( log ( na na na figure running times of several algorithms for maximum subsequence sum (in seconds
23,348
algorithm analysis expectedit might be silly to expend great deal of effort to design clever algorithm on the other handthere is large market these days for rewriting programs that were written five years ago based on no-longer-valid assumption of small input size these programs are now too slow because they used poor algorithms for large amounts of inputalgorithm is clearly the best choice (although algorithm is still usablesecondthe times given do not include the time required to read the input for algorithm the time merely to read the input from disk is likely to be an order of magnitude larger than the time required to solve the problem this is typical of many efficient algorithms reading the data is generally the bottleneckonce the data are readthe problem can be solved quickly for inefficient algorithms this is not trueand significant computer resources must be used thusit is important thatwhenever possiblealgorithms be efficient enough not to be the bottleneck of problem notice that for algorithm which is linearas the problem size increases by factor of so does the running time algorithm which is quadraticdoes not display this behaviora tenfold increase in input size yields roughly hundredfold ( increase in running time and algorithm which is cubicyields thousandfold ( increase in running time we would expect algorithm to take nearly , seconds (or two and half hoursto complete for , similarlywe would expect algorithm to take roughly seconds to complete for , , howeverit is possible that algorithm could take somewhat longer to complete due to the fact that , , could also yield slower memory accesses than , on modern computersdepending on the size of the memory cache figure shows the growth rates of the running times of the four algorithms even though this graph encompasses only values of ranging from to the relative linear ( log nquadratic cubic running time input size ( figure plot ( vs timeof various algorithms
23,349
running time linear ( log quadratic cubic input size (nfigure plot ( vs timeof various algorithms growth rates are still evident although the graph for the ( log nseems linearit is easy to verify that it is not by using straightedge (or piece of paperalthough the graph for the (nalgorithm seems constantthis is only because for small values of nthe constant term is larger than the linear term figure shows the performance for larger values it dramatically illustrates how useless inefficient algorithms are for even moderately large amounts of input running-time calculations there are several ways to estimate the running time of program the previous table was obtained empirically if two programs are expected to take similar timesprobably the best way to decide which is faster is to code them both and run themgenerallythere are several algorithmic ideasand we would like to eliminate the bad ones earlyso an analysis is usually required furthermorethe ability to do an analysis usually provides insight into designing efficient algorithms the analysis also generally pinpoints the bottleneckswhich are worth coding carefully to simplify the analysiswe will adopt the convention that there are no particular units of time thuswe throw away leading constants we will also throw away loworder termsso what we are essentially doing is computing big-oh running time since big-oh is an upper boundwe must be careful never to underestimate the running time of the program in effectthe answer provided is guarantee that the program will terminate within certain time period the program may stop earlier than thisbut never later
23,350
algorithm analysis simple example here is simple program fragment to calculate  = int sumint int partialsum partialsum forint < ++ partialsum + ireturn partialsumthe analysis of this fragment is simple the declarations count for no time lines and count for one unit each line counts for four units per time executed (two multiplicationsone additionand one assignmentand is executed timesfor total of units line has the hidden costs of initializing itesting <nand incrementing the total cost of all these is to initializen for all the testsand for all the incrementswhich is we ignore the costs of calling the function and returningfor total of thuswe say that this function is (nif we had to perform all this work every time we needed to analyze programthe task would quickly become infeasible fortunatelysince we are giving the answer in terms of big-ohthere are lots of shortcuts that can be taken without affecting the final answer for instanceline is obviously an ( statement (per execution)so it is silly to count precisely whether it is twothreeor four unitsit does not matter line is obviously insignificant compared with the for loopso it is silly to waste time here this leads to several general rules general rules rule --for loops the running time of for loop is at most the running time of the statements inside the for loop (including teststimes the number of iterations rule --nested loops analyze these inside out the total running time of statement inside group of nested loops is the running time of the statement multiplied by the product of the sizes of all the loops as an examplethe following program fragment is ( )fori ++ forj ++ ++krule --consecutive statements these just add (which means that the maximum is the one that countssee rule on page
23,351
as an examplethe following program fragmentwhich has (nwork followed by ( workis also ( )fori ++ ai fori ++ forj ++ ai +aj jrule --if/else for the fragment ifcondition else the running time of an if/else statement is never more than the running time of the test plus the larger of the running times of and clearlythis can be an overestimate in some casesbut it is never an underestimate other rules are obviousbut basic strategy of analyzing from the inside (or deepest partout works if there are function callsthese must be analyzed first if there are recursive functionsthere are several options if the recursion is really just thinly veiled for loopthe analysis is usually trivial for instancethe following function is really just simple loop and is ( )long factorialint ifn < return else return factorialn )this example is really poor use of recursion when recursion is properly usedit is difficult to convert the recursion into simple loop structure in this casethe analysis will involve recurrence relation that needs to be solved to see what might happenconsider the following programwhich turns out to be terrible use of recursion long fibint ifn < return else return fibn fibn )at first glancethis seems like very clever use of recursion howeverif the program is coded up and run for values of around it becomes apparent that this program
23,352
algorithm analysis is terribly inefficient the analysis is fairly simple let (nbe the running time for the function call fib(nif or then the running time is some constant valuewhich is the time to do the test at line and return we can say that ( ( because constants do not matter the running time for other values of is then measured relative to the running time of the base case for the time to execute the function is the constant work at line plus the work at line line consists of an addition and two function calls since the function calls are not simple operationsthey must be analyzed by themselves the first function call is fib( - and henceby the definition of trequires ( units of time similar argument shows that the second function call requires ( units of time the total time required is then ( ( where the accounts for the work at line plus the addition at line thusfor > we have the following formula for the running time of fib( ) (nt( ( since fib(nfib( - fib( - )it is easy to show by induction that ( >fib(nin section we showed that fib( ( / ) similar calculation shows that (for fib( >( / ) and so the running time of this program grows exponentially this is about as bad as possible by keeping simple array and using for loopthe running time can be reduced substantially this program is slow because there is huge amount of redundant work being performedviolating the fourth major rule of recursion (the compound interest rule)which was presented in section notice that the first call on line fib( - )actually computes fib( - at some point this information is thrown away and recomputed by the second call on line the amount of information thrown away compounds recursively and results in the huge running time this is perhaps the finest example of the maxim "don' compute anything more than onceand should not scare you away from using recursion throughout this bookwe shall see outstanding uses of recursion solutions for the maximum subsequence sum problem we will now present four algorithms to solve the maximum subsequence sum problem posed earlier the first algorithmwhich merely exhaustively tries all possibilitiesis depicted in figure the indices in the for loop reflect the fact that in ++arrays begin at instead of alsothe algorithm does not compute the actual subsequencesadditional code is required to do this convince yourself that this algorithm works (this should not take much convincingthe running time is ( and is entirely due to lines and which consist of an ( statement buried inside three nested for loops the loop at line is of size the second loop has size iwhich could be small but could also be of size we must assume the worstwith the knowledge that this could make the final bound bit high the third loop has size which again we must assume is of size the total is ( no( line takes only ( totaland lines and take only ( totalsince they are easy expressions inside only two loops
23,353
/*cubic maximum contiguous subsequence sum algorithm *int maxsubsum const vector int maxsum forint size)++ forint ij size)++ int thissum forint ik < ++ thissum +ak ]ifthissum maxsum maxsum thissumreturn maxsumfigure algorithm it turns out that more precise analysistaking into account the actual size of these loopsshows that the answer is ( and that our estimate above was factor of too high (which is all rightbecause constants do not matterthis is generally true in these  -  kinds of problems the precise analysis is obtained from the sum - = = = which tells how many times line is executed the sum can be evaluated inside outusing formulas from section in particularwe will use the formulas for the sum of the first integers and first squares first we have = - + = next we evaluate - = ( ( )( this sum is computed by observing that it is just the sum of the first integers to complete the calculationwe evaluate
23,354
algorithm analysis - = ( )( ( )( = ( = = = ( )( ( nn we can avoid the cubic running time by removing for loop this is not always possiblebut in this case there are an awful lot of unnecessary computations present in the algorithm the inefficiency that the improved algorithm corrects can be seen by noticing  -  that = ak aj = ak so the computation at lines and in algorithm is unduly expensive figure shows an improved algorithm algorithm is clearly ( )the analysis is even simpler than before there is recursive and relatively complicated ( log nsolution to this problemwhich we now describe if there didn' happen to be an ( (linearsolutionthis would be an excellent example of the power of recursion the algorithm uses "divide-andconquerstrategy the idea is to split the problem into two roughly equal subproblems /*quadratic maximum contiguous subsequence sum algorithm *int maxsubsum const vector int maxsum forint size)++ int thissum forint ij size)++ thissum +aj ]ifthissum maxsum maxsum thissumreturn maxsumfigure algorithm
23,355
which are then solved recursively this is the "dividepart the "conquerstage consists of patching together the two solutions of the subproblemsand possibly doing small amount of additional workto arrive at solution for the whole problem in our casethe maximum subsequence sum can be in one of three places either it occurs entirely in the left half of the inputor entirely in the right halfor it crosses the middle and is in both halves the first two cases can be solved recursively the last case can be obtained by finding the largest sum in the first half that includes the last element in the first halfand the largest sum in the second half that includes the first element in the second half these two sums can then be added together as an exampleconsider the following inputfirst half - - second half - - the maximum subsequence sum for the first half is (elements through and for the second half is (elements through the maximum sum in the first half that includes the last element in the first half is (elements through )and the maximum sum in the second half that includes the first element in the second half is (elements through thusthe maximum sum that spans both halves and goes through the middle is (elements through we seethenthat among the three ways to form large maximum subsequencefor our examplethe best way is to include elements from both halves thusthe answer is figure shows an implementation of this strategy the code for algorithm deserves some comment the general form of the call for the recursive function is to pass the input array along with the left and right borderswhich delimits the portion of the array that is operated upon one-line driver program sets this up by passing the borders and along with the array lines to handle the base case if left =rightthere is one elementand it is the maximum subsequence if the element is nonnegative the case left right is not possible unless is negative (although minor perturbations in the code could mess this uplines and perform the two recursive calls we can see that the recursive calls are always on smaller problem than the originalalthough minor perturbations in the code could destroy this property lines to and to calculate the two maximum sums that touch the center divider the sum of these two values is the maximum sum that spans both halves the routine max (not shownreturns the largest of the three possibilities algorithm clearly requires more effort to code than either of the two previous algorithms howevershorter code does not always mean better code as we have seen in the earlier table showing the running times of the algorithmsthis algorithm is considerably faster than the other two for all but the smallest of input sizes the running time is analyzed in much the same way as for the program that computes the fibonacci numbers let (nbe the time it takes to solve maximum subsequence sum problem of size if then the program takes some constant amount of time to execute lines to which we shall call one unit thust( otherwisethe
23,356
algorithm analysis /*recursive maximum contiguous subsequence sum algorithm finds maximum sum in subarray spanning [left rightdoes not attempt to maintain actual best sequence *int maxsumrecconst vector aint leftint right ifleft =right /base case ifaleft return aleft ]else return int center left right int maxleftsum maxsumrecaleftcenter )int maxrightsum maxsumrecacenter right )int maxleftbordersum leftbordersum forint centeri >left-- leftbordersum +ai ]ifleftbordersum maxleftbordersum maxleftbordersum leftbordersumint maxrightbordersum rightbordersum forint center <right++ rightbordersum +aj ]ifrightbordersum maxrightbordersum maxrightbordersum rightbordersumreturn max maxleftsummaxrightsummaxleftbordersum maxrightbordersum )/*driver for divide-and-conquer maximum contiguous subsequence sum algorithm *int maxsubsum const vector return maxsumreca size )figure algorithm
23,357
program must perform two recursive callsthe two for loops between lines and and some small amount of bookkeepingsuch as lines and the two for loops combine to touch every element in the subarrayand there is constant work inside the loopsso the time expended in lines to is (nthe code in lines to and is all constant amount of work and can thus be ignored compared with (nthe remainder of the work is performed in lines and these lines solve two subsequence problems of size / (assuming is eventhusthese lines take ( / units of time eachfor total of ( / the total time for the algorithm then is ( / (nthis gives the equations ( ( ( / (nto simplify the calculationswe can replace the (nterm in the equation above with nsince (nwill be expressed in big-oh notation anywaythis will not affect the answer in we shall see how to solve this equation rigorously for nowif ( ( / nand ( then ( ( ( and ( the pattern that is evidentand can be derivedis that if then (nn ( log ( log nthis analysis assumes is evensince otherwise / is not defined by the recursive nature of the analysisit is really valid only when is power of since otherwise we eventually get subproblem that is not an even sizeand the equation is invalid when is not power of somewhat more complicated analysis is requiredbut the big-oh result remains unchanged in future we will see several clever applications of recursion herewe present fourth algorithm to find the maximum subsequence sum this algorithm is simpler to implement than the recursive algorithm and also is more efficient it is shown in figure it should be clear why the time bound is correctbut it takes little thought to see why the algorithm actually works to sketch the logicnote that like algorithms and is representing the end of the current sequencewhile is representing the start of the current sequence it happens that the use of can be optimized out of the program if we do not need to know where the actual best subsequence isbut in designing the algorithmlet' pretend that is needed and that we are trying to improve algorithm one observation is that if [iis negativethen it cannot possibly be the start of the optimal subsequencesince any subsequence that begins by including [iwould be improved by beginning with [ + similarlyany negative subsequence cannot possibly be prefix of the optimal subsequence (same logicifin the inner loopwe detect that the subsequence from [ito [jis negativethen we can advance the crucial observation is that not only can we advance to + but we can also actually advance it all the way to + to see thislet be any index between + and any subsequence that starts at index is not larger than the corresponding subsequence that starts at index and includes the subsequence from [ito [ - ]since the latter subsequence is not negative ( is the first index that causes the subsequence starting at index to become negativethusadvancing to + is risk freewe cannot miss an optimal solution this algorithm is typical of many clever algorithmsthe running time is obviousbut the correctness is not for these algorithmsformal correctness proofs (more formal
23,358
algorithm analysis /*linear-time maximum contiguous subsequence sum algorithm *int maxsubsum const vector int maxsum thissum forint size)++ thissum +aj ]ifthissum maxsum maxsum thissumelse ifthissum thissum return maxsumfigure algorithm than the sketch aboveare almost always requiredeven thenmany people still are not convinced alsomany of these algorithms require trickier programmingleading to longer development but when these algorithms workthey run quicklyand we can test much of the code logic by comparing it with an inefficient (but easily implementedbrute-force algorithm using small input sizes an extra advantage of this algorithm is that it makes only one pass through the dataand once [iis read and processedit does not need to be remembered thusif the array is on disk or is being transmitted over the internetit can be read sequentiallyand there is no need to store any part of it in main memory furthermoreat any point in timethe algorithm can correctly give an answer to the subsequence problem for the data it has already read (the other algorithms do not share this propertyalgorithms that can do this are called online algorithms an online algorithm that requires only constant space and runs in linear time is just about as good as possible logarithms in the running time the most confusing aspect of analyzing algorithms probably centers around the logarithm we have already seen that some divide-and-conquer algorithms will run in ( log ntime besides divide-and-conquer algorithmsthe most frequent appearance of logarithms centers around the following general rulean algorithm is (log nif it takes constant ( ( )time to cut the problem size by fraction (which is usually on the other handif constant time is required to merely reduce the problem by constant amount (such as to make the problem smaller by )then the algorithm is (
23,359
it should be obvious that only special kinds of problems can be (log nfor instanceif the input is list of numbersan algorithm must take (nmerely to read the input in thuswhen we talk about (log nalgorithms for these kinds of problemswe usually presume that the input is preread we provide three examples of logarithmic behavior binary search the first example is usually referred to as binary search binary search given an integer and integers an- which are presorted and already in memoryfind such that ai xor return - if is not in the input the obvious solution consists of scanning through the list from left to right and runs in linear time howeverthis algorithm does not take advantage of the fact that the list is sorted and is thus not likely to be best better strategy is to check if is the middle element if sothe answer is at hand if is smaller than the middle elementwe can apply the same strategy to the sorted subarray to the left of the middle elementlikewiseif is larger than the middle elementwe look to the right half (there is also the case of when to stop figure shows the code for binary search (the answer is midas usualthe code reflects ++' convention that arrays begin with index /*performs the standard binary search using two comparisons per level returns index where item is found or - if not found *template int binarysearchconst vector aconst comparable int low high size whilelow <high int mid low high ifamid low mid else ifamid high mid else return mid/found return not_foundfigure binary search /not_found is defined as -
23,360
algorithm analysis clearlyall the work done inside the loop takes ( per iterationso the analysis requires determining the number of times around the loop the loop starts with high low and finishes with high low >- every time through the loopthe value high low must be at least halved from its previous valuethusthe number of times around the loop is at most log( ) (as an exampleif high low then the maximum values of high low after each iteration are - thusthe running time is (log nequivalentlywe could write recursive formula for the running timebut this kind of brute-force approach is usually unnecessary when you understand what is really going on and why binary search can be viewed as our first data-structure implementation it supports the contains operation in (log ntimebut all other operations (in particularinsertrequire (ntime in applications where the data are static ( insertions and deletions are not allowed)this could be very useful the input would then need to be sorted oncebut afterward accesses would be fast an example is program that needs to maintain information about the periodic table of elements (which arises in chemistry and physicsthis table is relatively stableas new elements are added infrequently the element names could be kept sorted since there are only about elementsat most eight accesses would be required to find an element performing sequential search would require many more accesses euclid' algorithm second example is euclid' algorithm for computing the greatest common divisor the greatest common divisor (gcdof two integers is the largest integer that divides both thusgcd( the algorithm in figure computes gcd(mn)assuming > (if mthe first iteration of the loop swaps them the algorithm works by continually computing remainders until is reached the last nonzero remainder is the answer thusif , and , then the sequence of remainders is thereforegcd( as the example showsthis is fast algorithm as beforeestimating the entire running time of the algorithm depends on determining how long the sequence of remainders is although log seems like good answerit is not at all obvious that the value of the remainder has to decrease by constant factor long long gcdlong long mlong long whilen ! long long rem nm nn remreturn mfigure euclid' algorithm
23,361
since we see that the remainder went from to only in the example indeedthe remainder does not decrease by constant factor in one iteration howeverwe can prove that after two iterationsthe remainder is at most half of its original value this would show that the number of iterations is at most log (log nand establish the running time this proof is easyso we include it here it follows directly from the following theorem theorem if nthen mod / proof there are two cases if < / then since the remainder is smaller than nthe theorem is true for this case the other case is / but then goes into once with remainder / proving the theorem one might wonder if this is the best bound possiblesince log is about for our exampleand only seven operations were performed it turns out that the constant can be improved slightlyto roughly log nin the worst case (which is achievable if and are consecutive fibonacci numbersthe average-case performance of euclid' algorithm requires pages and pages of highly sophisticated mathematical analysisand it turns out that the average number of iterations is about ( ln ln )/ exponentiation our last example in this section deals with raising an integer to power (which is also an integernumbers that result from exponentiation are generally quite largeso an analysis works only if we can assume that we have machine that can store such large integers (or compiler that can simulate thiswe will count the number of multiplications as the measurement of running time the obvious algorithm to compute xn uses - multiplications recursive algorithm can do better < is the base case of the recursion otherwiseif is evenwe have xn xn/ xn/ and if is oddxn ( - )/ ( - )/ for instanceto compute the algorithm does the following calculationswhich involve only nine multiplications ( )xx ( xx ( xx ( xx ( the number of multiplications required is clearly at most log nbecause at most two multiplications (if is oddare required to halve the problem againa recurrence formula can be written and solved simple intuition obviates the need for brute-force approach figure implements this idea it is sometimes interesting to see how much the code can be tweaked without affecting correctness in figure lines to are actually unnecessarybecause if is then line does the right thing line can also be rewritten as return powxn
23,362
algorithm analysis long long powlong-long xint ifn = return ifn = return xifisevenn return powx xn )else return powx xn xfigure efficient exponentiation without affecting the correctness of the program indeedthe program will still run in (log )because the sequence of multiplications is the same as before howeverall of the following alternatives for line are badeven though they look correct return powpowx ) )return powpowxn ) )return powxn powxn )both lines and are incorrect because when is one of the recursive calls to pow has as the second argument thus no progress is madeand an infinite loop results (in an eventual crashusing line affects the efficiencybecause there are now two recursive calls of size / instead of only one an analysis will show that the running time is no longer (log nwe leave it as an exercise to the reader to determine the new running time limitations of worst-case analysis sometimes the analysis is shown empirically to be an overestimate if this is the casethen either the analysis needs to be tightened (usually by clever observation)or it may be that the average running time is significantly less than the worst-case running time and no improvement in the bound is possible for many complicated algorithms the worstcase bound is achievable by some bad input but is usually an overestimate in practice unfortunatelyfor most of these problemsan average-case analysis is extremely complex (in many cases still unsolved)and worst-case boundeven though overly pessimisticis the best analytical result known summary this gives some hints on how to analyze the complexity of programs unfortunatelyit is not complete guide simple programs usually have simple analysesbut this is not always the case as an examplelater in the text we shall see sorting algorithm (shellsortand an algorithm for maintaining disjoint sets ()each of
23,363
which requires about lines of code the analysis of shellsort is still not completeand the disjoint set algorithm has an analysis that until recently was extremely difficult and require pages and pages of intricate calculations most of the analyses that we will encounter here will be simple and involve counting through loops an interesting kind of analysiswhich we have not touched uponis lower-bound analysis we will see an example of this in where it is proved that any algorithm that sorts by using only comparisons requires ( log ncomparisons in the worst case lower-bound proofs are generally the most difficultbecause they apply not to an algorithm but to class of algorithms that solve problem we close by mentioning that some of the algorithms described here have real-life application the gcd algorithm and the exponentiation algorithm are both used in cryptography specificallya -digit number is raised to large power (usually another -digit number)with only the low or so digits retained after each multiplication since the calculations require dealing with -digit numbersefficiency is obviously important the straightforward algorithm for exponentiation would require about multiplicationswhereas the algorithm presented requires only about , in the worst case exercises order the following functions by growth ratennn log nn log log nn log nn log( ) / / log nn indicate which functions grow at the same rate suppose (no( ( )and (no( ( )which of the following are truea (nt (no( ( ) (nt (no( ( ) (no( (nd (no( ( )which function grows fastern log or log prove that for any constant klogk (nfind two functions (nand (nsuch that neither (no( ( )nor (no( ( )in recent court casea judge cited city for contempt and ordered fine of $ for the first day each subsequent dayuntil the city followed the judge' orderthe fine was squared ( the fine progressed as follows$ $ $ $ $ , what would be the fine on day nb how many days would it take for the fine to reach dollars ( big-oh answer will do)for each of the following six program fragmentsa give an analysis of the running time (big-oh will dob implement the code in the language of your choiceand give the running time for several values of compare your analysis with the actual running times
23,364
algorithm analysis ( ( ( ( ( ( sum fori ++ ++sumsum fori ++ forj ++ ++sumsum fori ++ forj ++ ++sumsum fori ++ forj ++ ++sumsum fori ++ forj ++ fork ++ ++sumsum fori ++ forj ++ ifj = fork ++ ++sumsuppose you need to generate random permutation of the first integers for example{ and { are legal permutationsbut { is notbecause one number ( is duplicated and another ( is missing this routine is often used in simulation of algorithms we assume the existence of random number generatorrwith method randint( , )that generates integers between and with equal probability here are three algorithms fill the array from [ to [ - as followsto fill [ ]generate random numbers until you get one that is not already in [ ] [ ] [ - same as algorithm ( )but keep an extra array called the used array when random numberranis first put in the array aset used[rantrue this means that when filling [iwith random numberyou can test in one step to see whether the random number has been usedinstead of the (possiblyi steps in the first algorithm fill the array such that [ii+ then fori ++ swapai ]arandint ) prove that all three algorithms generate only legal permutations and that all permutations are equally likely
23,365
give as accurate (big-ohan analysis as you can of the expected running time of each algorithm write (separateprograms to execute each algorithm timesto get good average run program ( for , , program ( for , , , , , , and program ( for , , , , , , , , , , compare your analysis with the actual running times what is the worst-case running time of each algorithm complete the table in figure with estimates for the running times that were too long to simulate interpolate the running times for these algorithms and estimate the time required to compute the maximum subsequence sum of million numbers what assumptions have you madedeterminefor the typical algorithms that you use to perform calculations by handthe running time to do the followinga add two -digit integers multiply two -digit integers divide two -digit integers an algorithm takes ms for input size how long will it take for input size if the running time is the following (assume low-order terms are negligible) linear ( log nc quadratic cubic an algorithm takes ms for input size how large problem can be solved in min if the running time is the following (assume low-order terms are negligible) linear ( log nc quadratic cubic how much time is required to compute (xn = ai using simple routine to perform exponentiationb using the routine in section consider the following algorithm (known as horner' ruleto evaluate (  = ai poly fori ni > -- poly poly [ ] show how the steps are performed by this algorithm for ( explain why this algorithm works what is the running time of this algorithm
23,366
algorithm analysis give an efficient algorithm to determine if there exists an integer such that ai in an array of integers an what is the running time of your algorithm write an alternative gcd algorithm based on the following observations (arrange so that ) gcd(ab gcd( / / if and are both even gcd(abgcd( / bif is even and is odd gcd(abgcd(ab/ if is odd and is even gcd(abgcd(( )/ ( )/ if and are both odd give efficient algorithms (along with running time analysesto find the minimum subsequence sum find the minimum positive subsequence sum find the maximum subsequence product an important problem in numerical analysis is to find solution to the equation ( for some arbitrary if the function is continuous and has two points low and high such that (lowand (highhave opposite signsthen root must exist between low and high and can be found by binary search write function that takes as parameters flowand high and solves for zero what must you do to ensure termination the maximum contiguous subsequence sum algorithms in the text do not give any indication of the actual sequence modify them so that they return in single object the value of the maximum subsequence and the indices of the actual sequence write program to determine if positive integernis prime in terms of nwhat is the worst-case running time of your program(you should be able to do this in onc let equal the number of bits in the binary representation of what is the value of bd in terms of bwhat is the worst-case running time of your programe compare the running times to determine if -bit number and -bit number are prime is it more reasonable to give the running time in terms of or bwhythe sieve of eratosthenes is method used to compute all primes less than we begin by making table of integers to we find the smallest integerithat is not crossed outprint iand cross out iwhen nthe algorithm terminates what is the running time of this algorithmshow that can be computed with only eight multiplications write the fast exponentiation routine without recursion give precise count on the number of multiplications used by the fast exponentiation routine (hintconsider the binary representation of programs and are analyzed and found to have worst-case running times no greater than log and respectively answer the following questionsif possible
23,367
which program has the better guarantee on the running time for large values of ( , ) which program has the better guarantee on the running time for small values of ( ) which program will run faster on average for , is it possible that program will run faster than program on all possible inputsa majority element in an arrayaof size is an element that appears more than / times (thusthere is at most onefor examplethe array has majority element ( )whereas the array does not if there is no majority elementyour program should indicate this here is sketch of an algorithm to solve the problemfirsta candidate majority element is found (this is the harder partthis candidate is the only element that could possibly be the majority element the second step determines if this candidate is actually the majority this is just sequential search through the array to find candidate in the arrayaform second arrayb then compare and if they are equaladd one of these to botherwise do nothing then compare and again if they are equaladd one of these to botherwise do nothing continue in this fashion until the entire array is read then recursively find candidate for bthis is the candidate for (why? how does the recursion terminateb how is the case where is odd handledc what is the running time of the algorithmd how can we avoid using an extra arraybe write program to compute the majority element the input is an by matrix of numbers that is already in memory each individual row is increasing from left to right each individual column is increasing from top to bottom give an (nworst-case algorithm that decides if number is in the matrix design efficient algorithms that take an array of positive numbers aand determinea the maximum value of [ ]+ [ ]with > the maximum value of [ ]- [ ]with > the maximum value of [ ]* [ ]with > the maximum value of [ ]/ [ ]with > why is it important to assume that integers in our computer model have fixed sizeconsider the word puzzle problem on page suppose we fix the size of the longest word to be characters
23,368
in terms of and cwhich are the number of rows and columns in the puzzleand wwhich is the number of wordswhat are the running times of the algorithms described in suppose the word list is presorted show how to use binary search to obtain an algorithm with significantly better running time suppose that line in the binary search routine had the statement low mid instead of low mid would the routine still workimplement the binary search so that only one two-way comparison is performed in each iteration suppose that lines and in algorithm (fig are replaced by algorithm analysis int maxleftsum maxsumrecaleftcenter )int maxrightsum maxsumrecacenterright )would the routine still workthe inner loop of the cubic maximum subsequence sum algorithm performs ( + )( + )/ iterations of the innermost code the quadratic version performs ( )/ iterations the linear version performs iterations what pattern is evidentcan you give combinatoric explanation of this phenomenonreferences analysis of the running time of algorithms was first made popular by knuth in the threepart series [ ][ ]and [ analysis of the gcd algorithm appears in [ another early text on the subject is [ big-ohbig-omegabig-thetaand little-oh notation were advocated by knuth in [ there is still no uniform agreement on the matterespecially when it comes to using (many people prefer to use ()even though it is less expressive additionallyo(is still used in some corners to express lower boundwhen (is called for the maximum subsequence sum problem is from [ the series of books [ ][ ]and [ show how to optimize programs for speed ahoj hopcroftand ullmanthe design and analysis of computer algorithmsaddison-wesleyreadingmass bentleywriting efficient programsprentice hallenglewood cliffsn bentleyprogramming pearlsaddison-wesleyreadingmass bentleymore programming pearlsaddison-wesleyreadingmass knuththe art of computer programmingvol fundamental algorithms ed addison-wesleyreadingmass knuththe art of computer programmingvol seminumerical algorithms ed addison-wesleyreadingmass knuththe art of computer programmingvol sorting and searching ed addisonwesleyreadingmass knuth"big omicron and big omega and big theta,acm sigact news ( ) -
23,369
listsstacksand queues this discusses three of the most simple and basic data structures virtually every significant program will use at least one of these structures explicitlyand stack is always implicitly used in programwhether or not you declare one among the highlights of this we will introduce the concept of abstract data types (adtsr show how to efficiently perform operations on lists introduce the stack adt and its use in implementing recursion introduce the queue adt and its use in operating systems and algorithm design in this we provide code that implements significant subset of two library classesvector and list abstract data types (adtsan abstract data type (adtis set of objects together with set of operations abstract data types are mathematical abstractionsnowhere in an adt' definition is there any mention of how the set of operations is implemented objects such as listssetsand graphsalong with their operationscan be viewed as adtsjust as integersrealsand booleans are data types integersrealsand booleans have operations associated with themand so do adts for the set adtwe might have such operations as addremovesizeand contains alternativelywe might only want the two operations union and findwhich would define different adt on the set the +class allows for the implementation of adtswith appropriate hiding of implementation details thusany other part of the program that needs to perform an operation on the adt can do so by calling the appropriate method if for some reason implementation details need to be changedit should be easy to do so by merely changing the routines that perform the adt operations this changein perfect worldwould be completely transparent to the rest of the program there is no rule telling us which operations must be supported for each adtthis is design decision error handling and tie breaking (where appropriateare also generally up to the program designer the three data structures that we will study in this are primary examples of adts we will see how each can be implemented in several waysbut
23,370
listsstacksand queues if they are done correctlythe programs that use them will not necessarily need to know which implementation was used the list adt we will deal with general list of the form an- we say that the size of this list is we will call the special list of size an empty list for any list except the empty listwe say that ai follows (or succeedsai- ( nand that ai- precedes ai ( the first element of the list is and the last element is an- we will not define the predecessor of or the successor of an- the position of element ai in list is throughout this discussionwe will assumeto simplify mattersthat the elements in the list are integersbut in generalarbitrarily complex elements are allowed (and easily handled by class templateassociated with these "definitionsis set of operations that we would like to perform on the list adt some popular operations are printlist and makeemptywhich do the obvious thingsfindwhich returns the position of the first occurrence of an iteminsert and removewhich generally insert and remove some element from some position in the listand findkthwhich returns the element in some position (specified as an argumentif the list is then find( might return insert( , might make the list into (if we insert into the position given)and remove( might turn that list into of coursethe interpretation of what is appropriate for function is entirely up to the programmeras is the handling of special cases (for examplewhat does find( return above?we could also add operations such as next and previouswhich would take position as argument and return the position of the successor and predecessorrespectively simple array implementation of lists all these instructions can be implemented just by using an array although arrays are created with fixed capacitythe vector classwhich internally stores an arrayallows the array to grow by doubling its capacity when needed this solves the most serious problem with using an array--namelythat historicallyto use an arrayan estimate of the maximum size of the list was required this estimate is no longer needed an array implementation allows printlist to be carried out in linear timeand the findkth operation takes constant timewhich is as good as can be expected howeverinsertion and deletion are potentially expensivedepending on where the insertions and deletions occur in the worst caseinserting into position (in other wordsat the front of the listrequires pushing the entire array down one spot to make roomand deleting the first element requires shifting all the elements in the list up one spotso the worst case for these operations is (non averagehalf of the list needs to be moved for either operationso linear time is still required on the other handif all the operations occur at the high end of the listthen no elements need to be shiftedand then adding and deleting take ( time
23,371
there are many situations where the list is built up by insertions at the high endand then only array accesses ( findkth operationsoccur in such casethe array is suitable implementation howeverif insertions and deletions occur throughout the list andin particularat the front of the listthen the array is not good option the next section deals with the alternativethe linked list simple linked lists in order to avoid the linear cost of insertion and deletionwe need to ensure that the list is not stored contiguouslysince otherwise entire parts of the list will need to be moved figure shows the general idea of linked list the linked list consists of series of nodeswhich are not necessarily adjacent in memory each node contains the element and link to node containing its successor we call this the next link the last cell' next link points to nullptr to execute printlist(or find( )we merely start at the first node in the list and then traverse the list by following the next links this operation is clearly linear-timeas in the array implementationalthoughthe constant is likely to be larger than if an array implementation were used the findkth operation is no longer quite as efficient as an array implementationfindkth(itakes (itime and works by traversing down the list in the obvious manner in practicethis bound is pessimisticbecause frequently the calls to findkth are in sorted order (by ias an examplefindkth( )findkth( )findkth( )and findkth( can all be executed in one scan down the list the remove method can be executed in one next pointer change figure shows the result of deleting the third element in the original list the insert method requires obtaining new node from the system by using new call and then executing two next pointer maneuvers the general idea is shown in figure the dashed line represents the old pointer as we can seein principleif we know where change is to be madeinserting or removing an item from linked list does not require moving lots of itemsand instead involves only constant number of changes to node links the special case of adding to the front or removing the first item is thus constanttime operationpresuming of course that link to the front of the linked list is maintained figure linked list figure deletion from linked list
23,372
listsstacksand queues figure insertion into linked list first last figure doubly linked list the special case of adding at the end ( making the new item the last itemcan be constant-timeas long as we maintain link to the last node thusa typical linked list keeps links to both ends of the list removing the last item is trickierbecause we have to find the next-to-last itemchange its next link to nullptrand then update the link that maintains the last node in the classic linked listwhere each node stores link to its next nodehaving link to the last node provides no information about the next-to-last node the obvious idea of maintaining third link to the next-to-last node doesn' workbecause it too would need to be updated during remove insteadwe have every node maintain link to its previous node in the list this is shown in figure and is known as doubly linked list vector and list in the stl the +language includesin its libraryan implementation of common data structures this part of the language is popularly known as the standard template library (stlthe list adt is one of the data structures implemented in the stl we will see some others in and in generalthese data structures are called collections or containers there are two popular implementations of the list adt the vector provides growable array implementation of the list adt the advantage of using the vector is that it is indexable in constant time the disadvantage is that insertion of new items and removal of existing items is expensiveunless the changes are made at the end of the vector the list provides doubly linked list implementation of the list adt the advantage of using the
23,373
list is that insertion of new items and removal of existing items is cheapprovided that the position of the changes is known the disadvantage is that the list is not easily indexable both vector and list are inefficient for searches throughout this discussionlist refers to the doubly linked list in the stlwhereas list (typeset without the monospace fontrefers to the more general list adt both vector and list are class templates that are instantiated with the type of items that they store both have several methods in common the first three methods shown are actually available for all the stl containersr int sizeconstreturns the number of elements in the container void clear)removes all elements from the container bool emptyconstreturns true if the container contains no elementsand false otherwise both vector and list support adding and removing from the end of the list in constant time both vector and list support accessing the front item in the list in constant time the operations arer void push_backconst object )adds to the end of the list void pop_back)removes the object at the end of the list const object backconstreturns the object at the end of the list ( mutator that returns reference is also providedr const object frontconstreturns the object at the front of the list ( mutator that returns reference is also providedbecause doubly linked list allows efficient changes at the frontbut vector does notthe following two methods are available only for listr void push_frontconst object )adds to the front of the list void pop_front)removes the object at the front of the list the vector has its own set of methods that are not part of list two methods allow efficient indexing the other two methods allow the programmer to view and change the internal capacity these methods arer object operator[int idx )returns the object at index idx in the vectorwith no bounds-checking (an accessor that returns constant reference is also providedr object atint idx )returns the object at index idx in the vectorwith boundschecking (an accessor that returns constant reference is also providedr int capacityconstreturns the internal capacity of the vector (see section for more details void reserveint newcapacity )sets the new capacity if good estimate is availableit can be used to avoid expansion of the vector (see section for more details
23,374
listsstacksand queues iterators some operations on listsmost critically those to insert and remove from the middle of the listrequire the notion of position in the stla position is represented by nested typeiterator in particularfor listthe position is represented by the type list::iteratorfor vectorthe position is represented by class vector::iteratorand so on in describing some methodswe'll simply use iterator as shorthandbut when writing codewe will use the actual nested class name initiallythere are three main issues to addressfirsthow one gets an iteratorsecondwhat operations the iterators themselves can performthirdwhich list adt methods require iterators as parameters getting an iterator for the first issuethe stl lists (and all other stl containersdefine pair of methodsr iterator begin)returns an appropriate iterator representing the first item in the container iterator end)returns an appropriate iterator representing the endmarker in the container ( the position after the last item in the containerthe end method seems little unusualbecause it returns an iterator that is "out-ofbounds to see the ideaconsider the following code typically used to print the items in vector prior to the introduction of range-based for loops in ++ forint ! size)++ cout <vi <endlif we were to rewrite this code using iteratorswe would see natural correspondence with the begin and end methodsforvector::iterator itr begin)itr ! end)itr ??cout <itr ??<endlin the loop termination testboth != sizeand itr!= endare intended to test if the loop counter has become "out-of-bounds the code fragment also brings us to the second issuewhich is that the iterator must have methods associated with it (these unknown methods are represented by ???iterator methods based on the code fragment aboveit is obvious that iterators can be compared with !and ==and likely have copy constructors and operatordefined thusiterators have methodsand many of the methods use operator overloading besides copyingthe most commonly used operations on iterators include the followingr itr+and ++itradvances the iterator itr to the next location both the prefix and postfix forms are allowable
23,375
*itrreturns reference to the object stored at iterator itr' location the reference returned may or may not be modifiable (we discuss these details shortlyr itr ==itr returns true if iterators itr and itr refer to the same location and false otherwise itr !=itr returns true if iterators itr and itr refer to different location and false otherwise with these operatorsthe code to print would be forvector::iterator itr begin)itr ! end)++itr cout <*itr <endlthe use of operator overloading allows one to access the current itemthen advance to the next item using *itr+thusan alternative to the fragment above is vector::iterator itr begin)whileitr != endcout <*itr+<endlcontainer operations that require iterators for the last issuethe three most popular methods that require iterators are those that add or remove from the list (either vector or listat specified positionr iterator insertiterator posconst object )adds into the listprior to the position given by the iterator pos this is constant-time operation for listbut not for vector the return value is an iterator representing the position of the inserted item iterator eraseiterator pos )removes the object at the position given by the iterator this is constant-time operation for listbut not for vector the return value is the position of the element that followed pos prior to the call this operation invalidates poswhich is now stalesince the container item it was viewing has been removed iterator eraseiterator startiterator end )removes all items beginning at position startup tobut not including end observe that the entire list can be erased by the call erasec begin) endexampleusing erase on list as an examplewe provide routine that removes every other item in liststarting with the initial item thus if the list contains then after the method is invoked it will contain we do this by stepping through the list and using the erase method on every second item on listthis will be linear-time routine because each of the calls to erase takes constant timebut in vector the entire routine will take quadratic time because each of the calls to erase is inefficientusing (ntime as resultwe would normally write the code for list only howeverfor experimentation purposeswe write general function template that will work with both list or vectorand then provide
23,376
listsstacksand queues template void removeeveryotheritemcontainer lst auto itr lst begin)/itr is container::iterator whileitr !lst enditr lst eraseitr )ifitr !lst end++itrfigure using iterators to remove every other item in list (either vector or listefficient for listbut not for vector timing information the function template is shown in figure the use of auto at line is ++ feature that allows us to avoid the longer type container::iterator if we run the codepassing listit takes sec for , -item listand sec for an , , -item listand is clearly linear-time routinebecause the running time increases by the same factor as the input size when we pass vectorthe routine takes almost five minutes for an , -item vector and about twenty minutes for an , , -item vectorthe four fold increase in running time when the input increases by only factor of two is consistent with quadratic behavior const_iterators the result of *itr is not just the value of the item that the iterator is viewing but also the item itself this distinction makes the iterators very powerful but also introduces some complications to see the benefitsuppose we want to change all the items in collection to specified value the following routine works for both vector and list and runs in linear time it' wonderful example of writing generictype-independent code template void changecontainer cconst object newvalue typename container::iterator itr begin)whileitr ! end*itr+newvalueto see the potential problemsuppose the container was passed to routine using callby-constant reference this means we would expect that no changes would be allowed to cand the compiler would ensure this by not allowing calls to any of ' mutators consider the following code that prints list of integers but also tries to sneak in change to the list
23,377
void printconst list lstostream out cout typename container::iterator itr lst begin)whileitr !lst endout <*itr <endl*itr /this is fishy!!++itrif this code were legalthen the const-ness of the list would be completely meaninglessbecause it would be so easily bypassed the code is not legal and will not compile the solution provided by the stl is that every collection contains not only an iterator nested type but also const_iterator nested type the main difference between an iterator and const_iterator is that operatorfor const_iterator returns constant referenceand thus *itr for const_iterator cannot appear on the left-hand side of an assignment statement furtherthe compiler will force you to use const_iterator to traverse constant collection it does so by providing two versions of begin and two versions of endas followsr iterator beginr const_iterator beginconst iterator endr const_iterator endconst the two versions of begin can be in the same class only because the const-ness of method ( whether it is an accessor or mutatoris considered to be part of the signature we saw this trick in section and we will see it again in section both in the context of overloading operator[if begin is invoked on nonconstant containerthe "mutatorversion that returns an iterator is invoked howeverif begin is invoked on constant containerwhat is returned is const_iteratorand the return value may not be assigned to an iterator if you try to do soa compiler error is generated once itr is const_iterator*itr= is easily detected as being illegal if you use auto to declare your iteratorsthe compiler will deduce for you whether an iterator or const_iterator is substitutedto large extentthis relieves the programmer from having to keep track of the correct iterator type and is precisely one of the intended uses of auto additionallylibrary classes such as vector and list that provide iterators as described above are compatible with the range-based for loopas are user-defined classes an additional feature in ++ allows one to write code that works even if the container type does not have begin and end member functions non-member free functions begin and end are defined that allow one to use begin(cin any place where begin(is allowed writing generic code using begin(cinstead of begin(has the advantage that it allows the generic code to work on containers that have begin/end as membersas well as those that do not have begin/end but which can later be augmented with appropriate
23,378
listsstacksand queues template void printconst container costream out cout ifc emptyout <"(empty)"else auto itr beginc )/itr is container::const_iterator out <"<*itr++/print first item whileitr !endc out <"<*itr++out <]<endlfigure printing any container non-member functions the addition of begin and end as free functions in ++ is made possible by the addition of language features auto and decltypeas shown in the code below template auto begincontainer -decltypec beginreturn begin)template auto beginconst container -decltypec beginreturn begin)in this codethe return type of begin is deduced to be the type of begin(the code in figure makes use of auto to declare the iterator (as in fig and uses non-member functions begin and end implementation of vector in this sectionwe provide the implementation of usable vector class template the vector will be first-class typemeaning that unlike the primitive array in ++the vector can be copiedand the memory it uses can be automatically reclaimed (via its destructorin section we described some important features of +primitive arrays
23,379
the array is simply pointer variable to block of memorythe actual array size must be maintained separately by the programmer the block of memory can be allocated via new[but then must be freed via delete[ the block of memory cannot be resized (but newpresumably larger block can be obtained and initialized with the old blockand then the old block can be freedto avoid ambiguities with the library classwe will name our class template vector before examining the vector codewe outline the main details the vector will maintain the primitive array (via pointer variable to the block of allocated memory)the array capacityand the current number of items stored in the vector the vector will implement the big-five to provide deep-copy semantics for the copy constructor and operator=and will provide destructor to reclaim the primitive array it will also implement ++ move semantics the vector will provide resize routine that will change (generally to larger numberthe size of the vector and reserve routine that will change (generally to larger numberthe capacity of the vector the capacity is changed by obtaining new block of memory for the primitive arraycopying the old block into the new blockand reclaiming the old block the vector will provide an implementation of operator[(as mentioned in section operator[is typically implemented with both an accessor and mutator version the vector will provide basic routinessuch as sizeemptyclear (which are typically one-liners)backpop_backand push_back the push_back routine will call reserve if the size and capacity are same the vector will provide support for the nested types iterator and const_iteratorand associated begin and end methods figure and figure show the vector class like its stl counterpartthere is limited error checking later we will briefly discuss how error checking can be provided as shown on lines to the vector stores the sizecapacityand primitive array as its data members the constructor at lines to allows the user to specify an initial sizewhich defaults to zero it then initializes the data memberswith the capacity slightly larger than the sizeso few push_backs can be performed without changing the capacity the copy constructorshown at lines to makes new vector and can then be used by casual implementation of operatorthat uses the standard idiom of swapping in copy this idiom works only if swapping is done by movingwhich itself requires the implementation of the move constructor and move operatorshown at lines to againthese use very standard idioms implementation of the copy assignment operatorusing copy constructor and swapwhile simpleis certainly not the most efficient methodespecially in the case where both vectors have the same size in that special casewhich can be tested forit can be more efficient to simply copy each element one by one using object' operator
23,380
listsstacksand queues #include template class vector publicexplicit vectorint initsize thesizeinitsize }thecapacityinitsize spare_capacity objects new objectthecapacity ]vectorconst vector rhs thesizerhs thesize }thecapacityrhs thecapacity }objectsnullptr objects new objectthecapacity ]forint thesize++ objectsk rhs objectsk ]vector operatorconst vector rhs vector copy rhsstd::swap*thiscopy )return *this~vectordelete objectsvectorvector &rhs thesizerhs thesize }thecapacityrhs thecapacity }objectsrhs objects rhs objects nullptrrhs thesize rhs thecapacity vector operatorvector &rhs std::swapthesizerhs thesize )std::swapthecapacityrhs thecapacity )std::swapobjectsrhs objects )return *thisfigure vector class (part of
23,381
void resizeint newsize ifnewsize thecapacity reservenewsize )thesize newsizevoid reserveint newcapacity ifnewcapacity thesize returnobject *newarray new objectnewcapacity ]forint thesize++ newarrayk std::moveobjectsk )thecapacity newcapacitystd::swapobjectsnewarray )delete newarrayfigure (continuedthe resize routine is shown at lines to the code simply sets the thesize data memberafter possibly expanding the capacity expanding capacity is very expensive so if the capacity is expandedit is made twice as large as the size to avoid having to change the capacity again unless the size increases dramatically (the + is used in case the size is expanding capacity is done by the reserve routineshown at lines to it consists of allocation of new array at line moving the old contents at lines and and the reclaiming of the old array at line as shown at lines and the reserve routine can also be used to shrink the underlying arraybut only if the specified new capacity is at least as large as the size if it isn'tthe reserve request is ignored the two versions of operator[are trivial (and in fact very similar to the implementations of operator[in the matrix class in section and are shown in lines to error checking is easily added by making sure that index is in the range to size()- inclusiveand throwing an exception if it is not host of short routinesnamelyemptysizecapacitypush_backpop_backand backare implemented in lines to at lines and we see the use of the postfix +operatorwhich uses thesize to index the array and then increases thesize we saw the same idiom when discussing iterators*itr+uses itr to decide which item to view and then advances itr the positioning of the +mattersin the prefix +operator*++itr advances itr and then uses the new itr to decide which item to viewand likewiseobjects[++thesizewould increment thesize and use the new value to index the array (which is not what we would wantpop_back and back could both benefit from error checks in which an exception is thrown if the size is
23,382
listsstacksand queues object operator[]int index return objectsindex ]const object operator[]int index const return objectsindex ]bool emptyconst return size= int sizeconst return thesizeint capacityconst return thecapacityvoid push_backconst object ifthesize =thecapacity reserve thecapacity )objectsthesize+xvoid push_backobject & ifthesize =thecapacity reserve thecapacity )objectsthesize+std::movex )void pop_back--thesizeconst object back const return objectsthesize ]typedef object iteratortypedef const object const_iteratoriterator beginreturn &objects ]const_iterator beginconst return &objects ]figure vector class (part of
23,383
iterator endreturn &objectssize]const_iterator endconst return &objectssize]static const int spare_capacity privateint thesizeint thecapacityobject objects}figure (continuedfinallyat lines to we see the declaration of the iterator and const_iterator nested types and the two begin and two end methods this code makes use of the fact that in ++ pointer variable has all the same operators that we expect for an iterator pointer variables can be copied and comparedthe operator yields the object being pointed atandmost peculiarlywhen +is applied to pointer variablethe pointer variable then points at the object that would be stored next sequentiallyif the pointer is pointing inside an arrayincrementing the pointer positions it at the next array element these semantics for pointers date back to the early with the programming languageupon which +is based the stl iterator mechanism was designed in part to mimic pointer operations consequentlyat lines and we see typedef statements that state the iterator and const_iterator are simply other names for pointer variableand begin and end need to simply return the memory addresses representing the first array position and the first invalid array positionrespectively the correspondence between iterators and pointers for the vector type means that using vector instead of the +array is likely to carry little overhead the disadvantage is thatas writtenthe code has no error checks if the iterator itr goes crashing past the end markerneither ++itr nor *itr will necessarily signal an error to fix this problem would require that the iterator and const_iterator be actual nested class types rather than simply pointer variables using nested class types is much more common and is what we will see in the list class in section implementation of list in this sectionwe provide the implementation of usable list class template as in the case of the vector classour list class will be named list to avoid ambiguities with the library class recall that the list class will be implemented as doubly linked list and that we will need to maintain pointers to both ends of the list doing so allows us to maintain constant time cost per operationso long as the operation occurs at known position the known position can be at either end or at position specified by an iterator
23,384
listsstacksand queues in considering the designwe will need to provide four classes the list class itselfwhich contains links to both endsthe size of the listand host of methods the node classwhich is likely to be private nested class node contains the data and pointers to the previous and next nodesalong with appropriate constructors the const_iterator classwhich abstracts the notion of positionand is public nested class the const_iterator stores pointer to "currentnodeand provides implementation of the basic iterator operationsall in the form of overloaded operators such as ===!=and + the iterator classwhich abstracts the notion of positionand is public nested class the iterator has the same functionality as const_iteratorexcept that operatorreturns reference to the item being viewedrather than constant reference to the item an important technical issue is that an iterator can be used in any routine that requires const_iteratorbut not vice versa in other wordsiterator is- const_iterator because the iterator classes store pointer to the "current node,and the end marker is valid positionit makes sense to create an extra node at the end of the list to represent the endmarker furtherwe can create an extra node at the front of the listlogically representing the beginning marker these extra nodes are sometimes known as sentinel nodesspecificallythe node at the front is sometimes known as header nodeand the node at the end is sometimes known as tail node the advantage of using these extra nodes is that they greatly simplify the coding by removing host of special cases for instanceif we do not use header nodethen removing the first node becomes special casebecause we must reset the list' link to the first node during the remove and because the remove algorithm in general needs to access the node prior to the node being removed (and without header nodethe first node does not have node prior to itfigure shows doubly linked list with header and tail nodes figure shows an empty list figure and figure show the outline and partial implementation of the list class we can see at line the beginning of the declaration of the private nested node class rather than using the class keywordwe use struct in ++the struct is relic from the programming language struct in +is essentially class in which the members default to public recall that in classthe members default to private clearly the struct head tail figure doubly linked list with header and tail nodes
23,385
head tail figure an empty doubly linked list with header and tail nodes keyword is not neededbut you will often see it and it is commonly used by programmers to signify type that contains mostly data that are accessed directlyrather than through methods in our casemaking the members public in the node class will not be problemsince the node class is itself private and inaccessible outside of the list class at line we see the beginning of the declaration of the public nested const_iterator classand at line we see the beginning of the declaration of the public nested iterator class the unusual syntax is inheritancewhich is powerful construct not otherwise used in the book the inheritance syntax states that iterator has exactly the same functionality as const_iteratorwith possibly some additionsand that iterator is type-compatible with const_iterator and can be used wherever const_iterator is needed we'll discuss those details when we see the actual implementations later lines to contain the data members for listnamelythe pointers to the header and tail nodes we also keep track of the size in data member so that the size method can be implemented in constant time the rest of the list class consists of the constructorthe big-fiveand host of methods many of the methods are one-liners begin and end return appropriate iteratorsthe call at line is typical of the implementationin which we return constructed iterator (thus the iterator and const_iterator classes each have constructor that takes pointer to node as its parameterthe clear method at lines to works by repeatedly removing items until the list is empty using this strategy allows clear to avoid getting its hands dirty reclaiming nodes because the node reclamation is now funneled to pop_front the methods at lines to all work by cleverly obtaining and using an appropriate iterator recall that the insert method inserts prior to positionso push_back inserts prior to the endmarkeras required in pop_backnote that erase(-end()creates temporary iterator corresponding to the endmarkerretreats the temporary iteratorand uses that iterator to erase similar behavior occurs in back note also that in the case of the pop_front and pop_back operationswe again avoid dealing with node reclamation figure shows the node classconsisting of the stored itempointers to the previous and next nodeand constructor all the data members are public figure shows the const_iterator classand figure shows the iterator class as we mentioned earlierthe syntax at line in figure indicates an advanced feature known as inheritance and means that iterator is- const_iterator when the iterator class is written this wayit inherits all the data and methods from const_iterator it may then add new dataadd new methodsand override ( redefineexisting methods in the most general scenariothere is significant syntactical baggage (often resulting in the keyword virtual appearing in the code
23,386
template class list privatestruct node /see figure *}publicclass const_iterator /see figure *}class iterator public const_iterator /see figure *}publiclist/see figure *listconst list rhs /see figure *~list/see figure *list operatorconst list rhs /see figure *listlist &rhs /see figure *list operatorlist &rhs /see figure *iterator beginreturn head->next }const_iterator beginconst return head->next }iterator endreturn tail }const_iterator endconst return tail }int sizeconst return thesizebool emptyconst return size= void clearwhile!emptypop_front)figure list class (part of
23,387
object frontreturn *begin)const object frontconst return *begin)object backreturn *--end)const object backconst return *--end)void push_frontconst object insertbegin) )void push_frontobject & insertbegin)std::movex )void push_backconst object insertend) )void push_backobject & insertend)std::movex )void pop_fronterasebegin)void pop_backerase--end)iterator insertiterator itrconst object /see figure *iterator insertiterator itrobject & /see figure *iterator eraseiterator itr /see figure *iterator eraseiterator fromiterator to /see figure *privateint thesizenode *headnode *tailvoid init/see figure *}figure list class (part of
23,388
listsstacksand queues struct node object datanode *prevnode *nextnodeconst object object}node nullptrnode nullptr datad }prevp }nextn nodeobject &dnode nullptrnode nullptr datastd::moved }prevp }nextn }figure nested node class for list class howeverin our casewe can avoid much of the syntactical baggage because we are not adding new datanor are we intending to change the behavior of an existing method we arehoweveradding some new methods in the iterator class (with very similar signatures to the existing methods in the const_iterator classas resultwe can avoid using virtual even sothere are quite few syntax tricks in const_iterator at lines and const_iterator stores as its single data member pointer to the "currentnode normallythis would be privatebut if it were privatethen iterator would not have access to it marking members of const_iterator as protected allows the classes that inherit from const_iterator to have access to these membersbut does not allow other classes to have access at lines and we see the constructor for const_iterator that was used in the list class implementation of begin and end we don' want all classes to see this constructor (iterators are not supposed to be visibly constructed from pointer variables)so it can' be publicbut we also want the iterator class to be able to see itso logically this constructor is made protected howeverthis doesn' give list access to the constructor the solution is the friend declaration at line which grants the list class access to const_iterator' nonpublic members the public methods in const_iterator all use operator overloading operator==operator!=and operatorare straightforward at lines to we see the implementation of operator+recall that the prefix and postfix versions of operator+are completely different in semantics (and precedence)so we need to write separate routines for each form they have the same nameso they must have different signatures to be distinguished +requires that we give them different signatures by specifying an empty parameter list for the prefix form and single (anonymousint parameter for the postfix form then ++itr calls the zero-parameter operator++and itr+calls the one-parameter operator+the int parameter is never usedit is present only to give different signature the implementation suggests thatin many cases where there is choice between using the prefix or postfix operator++the prefix form will be faster than the postfix form in the iterator classthe protected constructor at line uses an initialization list to initialize the inherited current node we do not have to reimplement operator=
23,389
class const_iterator publicconst_iteratorcurrentnullptr const object operatorconst return retrieve)const_iterator operator+current current->nextreturn *thisconst_iterator operator+int const_iterator old *this++*this )return oldbool operator=const const_iterator rhs const return current =rhs currentbool operator!const const_iterator rhs const return !*this =rhs )protectednode *currentobject retrieveconst return current->dataconst_iteratornode * currentp friend class list}figure nested const_iterator class for list class and operator!because those are inherited unchanged we do provide new pair of operator+implementations (because of the changed return typethat hide the originals in the const_iteratorand we provide an accessor/mutator pair for operatorthe accessor operator*shown at lines and simply uses the same implementation as in const_iterator the accessor is explicitly implemented in iterator because otherwise the original implementation is hidden by the newly added mutator version
23,390
listsstacksand queues class iterator public const_iterator publiciteratorobject operatorreturn const_iterator::retrieve)const object operatorconst return const_iterator::operator*)iterator operator+this->current this->current->nextreturn *thisiterator operator+int iterator old *this++*this )return oldprotectediteratornode * const_iteratorp friend class list}figure nested iterator class for list class figure shows the constructor and big-five because the zero-parameter constructor and copy constructor must both allocate the header and tail nodeswe provide private init routine init creates an empty list the destructor reclaims the header and tail nodesall the other nodes are reclaimed when the destructor invokes clear similarlythe copy constructor is implemented by invoking public methods rather than attempting low-level pointer manipulations figure illustrates how new node containing is spliced in between node pointed at by and prev the assignment to the node pointers can be described as followsnode *newnode new nodexp->prevp } ->prev->next newnodep->prev newnode/steps and /step /step
23,391
listinit)~listclear)delete headdelete taillistconst list rhs init)forauto rhs push_backx )list operatorconst list rhs list copy rhsstd::swap*thiscopy )return *thislistlist &rhs thesizerhs thesize }headrhs head }tailrhs tail rhs thesize rhs head nullptrrhs tail nullptrlist operatorlist &rhs std::swapthesizerhs thesize )std::swapheadrhs head )std::swaptailrhs tail )return *thisvoid initthesize head new nodetail new nodehead->next tailtail->prev headfigure constructorbig-fiveand private init routine for list class
23,392
listsstacksand queues prev figure insertion in doubly linked list by getting new node and then changing pointers in the order indicated steps and can be combinedyielding only two linesnode *newnode new nodexp->prevp } ->prev ->prev->next newnode/steps and /steps and but then these two lines can also be combinedyieldingp->prev ->prev->next new nodexp->prevp }this makes the insert routine in figure short figure shows the logic of removing node if points to the node being removedonly two pointers change before the node can be reclaimedp->prev->next ->nextp->next->prev ->prevdelete pfigure shows pair of erase routines the first version of erase contains the three lines of code shown above and the code to return an iterator representing the item after /insert before itr iterator insertiterator itrconst object node * itr currentthesize++return ->prev ->prev->next new nodexp->prevp }/insert before itr iterator insertiterator itrobject & node * itr currentthesize++return ->prev ->prev->next new nodestd::movex ) ->prevp }figure insert routine for list class
23,393
figure removing node specified by from doubly linked list /erase item at itr iterator eraseiterator itr node * itr currentiterator retvalp->next } ->prev->next ->nextp->next->prev ->prevdelete pthesize--return retvaliterator eraseiterator fromiterator to foriterator itr fromitr !toitr eraseitr )return tofigure erase routines for list class the erased element like inserterase must update thesize the second version of erase simply uses an iterator to call the first version of erase note that we cannot simply use itr+in the for loop at line and ignore the return value of erase at line the value of itr is stale immediately after the call to erasewhich is why erase returns an iterator in examining the codewe can see host of errors that can occur and for which no checks are provided for instanceiterators passed to erase and insert can be uninitialized or for the wrong listiterators can have +or applied to them when they are already at the endmarker or are uninitialized an uninitialized iterator will have current pointing at nullptrso that condition is easily tested the endmarker' next pointer points at nullptrso testing for +or on an endmarker condition is also easy howeverin order to determine if an iterator passed to erase or insert is an iterator for the correct listthe iterator must store an additional data member representing pointer to the list from which it was constructed
23,394
listsstacksand queues protectedconst list *thelistnode *currentconst_iteratorconst list lstnode * thelist&lst }currentp void assertisvalidconst ifthelist =nullptr |current =nullptr |current =thelist->head throw iteratoroutofboundsexception}figure revised protected section of const_iterator that incorporates ability to perform additional error checks we will sketch the basic idea and leave the details as an exercise in the const_iterator classwe add pointer to the list and modify the protected constructor to take the list as parameter we can also add methods that throw an exception if certain assertions aren' met the revised protected section looks something like the code in figure then all calls to iterator and const_iterator constructors that formerly took one parameter now take twoas in the begin method for listconst_iterator beginconst const_iterator itr*thishead }return ++itrthen insert can be revised to look something like the code in figure we leave the details of these modifications as an exercise /insert before itr iterator insertiterator itrconst object itr assertisvalid)ifitr thelist !this throw iteratormismatchexception}node * itr currentthesize++return *thisp->prev ->prev->next new nodexp->prevp }figure list insert with additional error checks
23,395
the stack adt stack is list with the restriction that insertions and deletions can be performed in only one positionnamelythe end of the listcalled the top stack model the fundamental operations on stack are pushwhich is equivalent to an insertand popwhich deletes the most recently inserted element the most recently inserted element can be examined prior to performing pop by use of the top routine pop or top on an empty stack is generally considered an error in the stack adt on the other handrunning out of space when performing push is an implementation limit but not an adt error stacks are sometimes known as lifo (last infirst outlists the model depicted in figure signifies only that pushes are input operations and pops and tops are output the usual operations to make empty stacks and test for emptiness are part of the repertoirebut essentially all that you can do to stack is push and pop figure shows an abstract stack after several operations the general model is that there is some element that is at the top of the stackand it is the only element that is visible pop stack push top figure stack modelinput to stack is by pushoutput is by pop and top top figure stack modelonly the top element is accessible
23,396
listsstacksand queues implementation of stacks since stack is listany list implementation will do clearly list and vector support stack operations of the time they are the most reasonable choice occasionally it can be faster to design special-purpose implementation because stack operations are constanttime operationsthis is unlikely to yield any discernable improvement except under very unique circumstances for these special timeswe will give two popular stack implementations one uses linked structureand the other uses an arrayand both simplify the logic in vector and listso we do not provide code linked list implementation of stacks the first implementation of stack uses singly linked list we perform push by inserting at the front of the list we perform pop by deleting the element at the front of the list top operation merely examines the element at the front of the listreturning its value sometimes the pop and top operations are combined into one array implementation of stacks an alternative implementation avoids links and is probably the more popular solution it uses the backpush_backand pop_back implementation from vectorso the implementation is trivial associated with each stack is thearray and topofstackwhich is - for an empty stack (this is how an empty stack is initializedto push some element onto the stackwe increment topofstack and then set thearray[topofstackx to popwe set the return value to thearray[topofstackand then decrement topofstack notice that these operations are performed in not only constant time but very fast constant time on some machinespushes and pops (of integerscan be written in one machine instructionoperating on register with auto-increment and auto-decrement addressing the fact that most modern machines have stack operations as part of the instruction set enforces the idea that the stack is probably the most fundamental data structure in computer scienceafter the array applications it should come as no surprise that if we restrict the operations allowed on listthose operations can be performed very quickly the big surprisehoweveris that the small number of operations left are so powerful and important we give three of the many applications of stacks the third application gives deep insight into how programs are organized balancing symbols compilers check your programs for syntax errorsbut frequently lack of one symbol (such as missing brace or comment startercan cause the compiler to spill out hundred lines of diagnostics without identifying the real error useful tool in this situation is program that checks whether everything is balanced thusevery right bracebracketand parenthesis must correspond to its left counterpart
23,397
the sequence [()is legalbut [(]is wrong obviouslyit is not worthwhile writing huge program for thisbut it turns out that it is easy to check these things for simplicitywe will just check for balancing of parenthesesbracketsand braces and ignore any other character that appears the simple algorithm uses stack and is as followsmake an empty stack read characters until end of file if the character is an opening symbolpush it onto the stack if it is closing symbol and the stack is emptyreport an error otherwisepop the stack if the symbol popped is not the corresponding opening symbolthen report an error at end of fileif the stack is not emptyreport an error you should be able to convince yourself that this algorithm works it is clearly linear and actually makes only one pass through the input it is thus online and quite fast extra work can be done to attempt to decide what to do when an error is reported--such as identifying the likely cause postfix expressions suppose we have pocket calculator and would like to compute the cost of shopping trip to do sowe add list of numbers and multiply the result by this computes the purchase price of some items with local sales tax added if the items are and then natural way to enter this would be the sequence depending on the calculatorthis produces either the intended answer or the scientific answer most simple four-function calculators will give the first answerbut many advanced calculators know that multiplication has higher precedence than addition on the other handsome items are taxable and some are notso if only the first and last items were actually taxablethen the sequence would give the correct answer ( on scientific calculator and the wrong answer ( on simple calculator scientific calculator generally comes with parenthesesso we can always get the right answer by parenthesizingbut with simple calculator we need to remember intermediate results typical evaluation sequence for this example might be to multiply and saving this answer as we then add and saving the result in we multiply and saving the answer in and finish by adding and leaving the final answer in we can write this sequence of operations as follows this notation is known as postfixor reverse polish notationand is evaluated exactly as we have described above the easiest way to do this is to use stack when number is seenit is pushed onto the stackwhen an operator is seenthe operator is applied to the
23,398
listsstacksand queues two numbers (symbolsthat are popped from the stackand the result is pushed onto the stack for instancethe postfix expression + is evaluated as followsthe first four symbols are placed on the stack the resulting stack is topofstack nexta '+is readso and are popped from the stackand their sum is pushed topofstack topofstack next is pushed now '*is seenso and are poppedand is pushed topofstack
23,399
nexta '+is seenso and are poppedand is pushed topofstack topofstack now is pushed next'+pops and and pushes topofstack finallya '*is seen and and are poppedthe result is pushed topofstack the time to evaluate postfix expression is ( )because processing each element in the input consists of stack operations and therefore takes constant time the algorithm to do so is very simple notice that when an expression is given in postfix notationthere is no need to know any precedence rulesthis is an obvious advantage