"El acceso a la version digitalizada
se brinda con fines académicos,
unicamente para las secciones que
lo requieren Vv habilitado
exclusivamente para el ciclo
académico vigente. Tener en
cuenta las consecuencias legales
que se desprenden de hacer uso
indebido de estos documentos, de
acuerdo a D.L. 822."Prete
is far too brief tobe used in such a course, You might find it uefa to use an adltonal
work on NP-completenesso augment this ext
Exercises
Eserlses, provided tthe end of each shapter, match the order which materiale pre=
‘sented The ast esecises may addres the chapter as 2 whole rater than a specifi seton,
Difficult exereves ate marked with an asterisk, and more challenging exercises have vo
aseriks
References
References are placed at the end of each chapter Generally the rlerences ether a his
torical, representing the orginal source ofthe materal,o they Yepresent extensions and
lunprosements to the results given in the text. Some references represent solutions (0
‘Supplements
‘The following supplements are availble oll reader t won:pearsoninterationaledtons
+ Source code for example programs
+ Ema
In addition, the following material is svalble only to quafed instructors at Pearson
Instructor Resource Center (woapersoniuemationaledtons comes). Vist the IRC of
contaet your Pearson Education sales representative for access,
+ Solutions to selected exerises
+ Figures rom the Boole
+ Bras
‘Acknowledgments
Many, many people have helped me in dhe prepa
Tse in eer versions ofthe book, thanks ll
ssa the wring process was made easier bythe profesional t Pearson, 1 ike
to thank my editor, Tay Johnson, and production editor, Maniyn Loyd. My wonderful
el deserves eta special thanks for everything she does.
Final Fd ke 10 thank the numerous readers who have sent e-mail messages and
pointed out eros inconsisiencies i eater version. My webate wines fi edocs
val also contain updaced source cove Gin C++ an Java), an erat ist, an alin to submit
bug reports,
Maw
Mami, Foi
jon of books in this seis. Some ae
The publishers wish to thank Arup Bhatachajee and Soumen Mukherjee for reviewing
‘he content ofthe Inventions Eton.
cuaprer I
Programming: A General
Overview
In this chaps, we discuss the sims and goals ofthis est and briefly review programing
concepts an discrete mathematics, We wl
+ See that howe 3 program performs for reasonably lrg input sat a important as ts
performance on moderate moun of put
+ Summarize the basic mathematical background needed forthe rest ofthe book
+ Billy review reewesion
+ summarize some important features of C+ that
sed throughout the text
1.1 What's This Book About?
Suppose you havea group of N numbers and would Mke to detennine the ith gest. This
\s Kou a the selection problem, Most students who have had programming couse
for to would have no dificult writing a program to solve tis problem, Thee are quite a
Few “abvious solutions
‘One way to sli this problem would be to read the N auraers ino an array sor the
array in decreasing order by seme simple algorhm such as bubble som, and then return
the element in postion k
‘A somtesthat beter algorithm might be to ead the ist element into an aay and
son them in decreasing order). Next, each remaningelement ead one by one. AS new
Clement series tt ignored fits smaller than the hh element n he stay Otherwie,
is placed in ts correct spot in the ray bumping one element out ofthe array When the
algorithm ends, the element in the ih postions returned a5 the answer
Both algorithm ae simpler code, and you are encouraged todo so, The natural ques
tions, then are: Which algoethm is better? And, more imporant, s either algorithm good
enough? A sinuladon sing a tandom fle of 30 milion elements and k= 15,000,000
voll show that nether algorhm finishes ina reasonable amount of time; each requires
"ver days of computer processing to teninat abet eventually with a correct answer)
An akeraive method, discussed in Chapter 7, gives a solution in abouts second. Thus,
although our proposed algorthns work, they cannot be considered good slgonthme,20
r234
yews
afwoanes
s/o a hg
afte ae
Figure 1.1 Sample word pazsle
because they are emily impractical for ipot sizes that acid algorithm can handle sna
reasonable amount of time
‘A second problem isto solve a popular word puzzle. The input consis of & w60-
Aimensional array of eters and ast of words. The objet sto ind the words he puck
‘These words may be horizontal, vera, or dagonal in any ircton. As an example, the
puzzle shown in Figure 11 contains the words ths, ew, fat and that. The word this begins
at row 1, column 1, or (1,1), and estends 10 (1.4); mo goes from (1,1) 10 (3.0 fat goes
from 4,1) to (2.3) and hat goes from (44) t0 QD.
Agin, there ar at east to ssightforward algorthms that solve the problem, For each
word inthe wordlist, we check each ordered triple (ow, column, erinttion forthe pres
‘ence ofthe word. This amounts to lts of nested for loops bu is basicly straightforward,
Alerativey foreach ordered quadruple ow clumn,orentaon, number of characters)
that doesnt runoff an end ofthe puzzle, we can test whether the word ct tin the
‘word ls. Again, this amounts to ls of nested for loop is posible to sve some time
ifthe maximum numberof characters in any word is known,
ris elately easy to code up ether method of solton an salve many ofthe el ie
puzales commonly published in magazines. These ypcally have 16 os, 16 clus, an
ADors0 words Suppose, however we consider the aration where nly the puzzle board is
given and the word hist i essenllyan English dictionary Bath of the solutions proposed
‘equi considerable time to solve this problem and therefore might not be acceptable
However, tis possible, even with a lage wor lst, to solve the problem very quickly
in important concept is tat, in many problems, wetng a working program isnot
good enough. Ilse progam sto be run ona lange dataset then the running ime becomes
an issue, Throughout this book we will se how to estimate the running time of a program
for large inputs and, more important, how to compare the runing times of two programs
without actually coding them. We wil sce techniques for drastically improving te speed
ofa program and for determining program botlentcks. These technics will enable us
find the section ofthe code on which to concentrate our optimization elon
1.2. Mathematics Review
‘This section iss some ofthe basic formulas you need to memorize, of beable to derive,
and reviews basi proof techniques.
|
|
|
12 Nata een a
1.2.1 Exponents
whyt axe
ax
oo a xt
IN aN
Wah a2!
1.2.2 Logarithms
‘in compute scence, ll logarithms are othe base 2 uns specified aberwise.
Definition 1.1
AF = Bifand only logy B= A
‘Several convenient equalities follow fom this definition.
‘Theorem 1.
lB 7
logy B= ES: ABC> OAH
Proof
Lex = loca log, 8. Then, by the definition of logs:
ruhins, CX = B, c Combining these three equalities yields
B= Ch = (CF Therefore, X = YZ, which implies Z = X/Y, proving the theorem,
Theorem 12
logAB = logA-+ log; A.B > 0
Proof
Let X = log, ¥ = loge, and Z = logAB, Then, assuming the deal base of 2,
DY = 4.2) = Band 2° = AB Combining the last three equalities yields
22" = AB = 2 Therefore, X-+Y = Z, which proves the theorem,
Some other useful formas, which cn al be derived in a similar manne, allow.
logs
log loge
logla®) = Blog
logX
0
log2=1, logi,024= 10, og ],048,376 = 20ChaperPropamming: A Gener! Overew
1.2.3 Series
The easiest formulas to remember are
and the companion,
ye
In the later forms, FO = A = 1. chen
Sra
and as N tends to 00, the sum approaches 1/
formulas
"We can derive the lst formula for SiEp A! (© < A <1) inthe following manner Let
Sethe sm. Then
A). These are the “geometric sees
DARA EAE AN A
Then
ASHALR EA HATED
Ie we subract these two equations (Which i permissible only fora convergent series)
‘rally ll the tems on the night side cance, lean
sas
‘which implies that
‘We can use this sae technique to compute SOS; 1/22 sum that occurs frequent
Went
and mukiply by 2, obtaining
a
2 3
asai4243
wetiege
Subtracting these two equations yields
Thus. $22
12 Mathematics Raven 2s
Another typeof common series in analyse isthe arithmetic eres. Any such seri can
‘be evaluated fromthe base formula
NED
roeaes
For instance, to ind the sum 2 4548-4 .-- + Gk— 1, rewnte tas 30142434
“+8)—(L+1414---4+ 1), whichis clearly 3+ 1)/2— ke Another way to remember
tists toad the frst and las terms (total 3k-+ 1), the second and nextlast tems (otal
3k + 1, and so on. Since there ate h/2of these pairs, the ttl sum sR + 1/2, which
‘isthe same answer as belo,
“The next ro formuls pop up now and then bt are fry uncommon,
When t= —1, the ater formula isnot valid. We then need the fllwing formu,
‘which ts used far more in computer scence than in her mathematical disciplines The
‘numbers Hy are knoen s the harmonic numbers, and the sim is known as a harmonic
sum, The err inthe following approximation tends to 0:37721366, hich s know
‘Euler’ constant
y= Zyo- Sy
1.2.4 Modular Arithmetic
We say that A is congruent to 8 modulo N, writen A= B (mod N), ICN’ divides
AB Inzutively. this means thatthe remainder the same when either A or B is
Aided by N. Ths, 81 = 61 = 1 (sid 10) Ae with equaly. EA = B nod N}, shen
A4-C 8 4C (mod Nand AD = BD (mod N)Chapter Pojaning: A Gener Overen
(ten, Ais @ prime number. that as, there are thre important theorems:
Firs, Ns prime, then ab = 0 (mod N) is ewe if and only ifa = 0 (rod N)
ov b = 0 (mod N), In ther word, i prime number N’ divides a product of two
number, detest least one ofthe two numbers
Second, if Nis prime, then the equation ax = 1 (mod N) bas a unique solution
(ened N) forall << N This saludo, 0 ~ x = Ns the mula inverse
“Thind,if.N i prime, then the equation 32 = a (mod 1) has either eva soltione
{mod N) for all a = Nor has no solutions
There ate many theorems that appyto molar arithmetie and some of them require
earaedinary proofs in number theory. We wil use modular arthmett sparingly. andl the
preceding cheers wil sie.
1.2.5 The P Word
The (wo most common ways of proving statements in daastractre analysis ae proof
‘by induction and proof by coneadiction (and occasionally preof by inumidation, used
by professors only). The best way of proving tha a theorems false is by exhib
counterexample,
Proof by Induction
[A proof by induction has two standard ports. The fs tp ie roving a base case, hats
‘establishing that theorem iste for some small (usually degenerate valet: this step
lest aay el. Next an ictive hypothesis is assumed. General this means hat
the theorem i assumed 10 be true forall cases up to some limit Using this assumption,
the theorem is then shown to be tne forthe next value, which is typically h-+ 1. Thi
proves the theorem (as long as is int.
‘Asan example, we prove thatthe Fibonacci numbers, Fy = 1, F, = 1,2 = 2.F
Fy 5... Fim Ft +A, satis F< (6/3) for 1 Some definitions have F
which sh the series) To do ths, we Bs verify thatthe theorem is tue forthe trivial
cases tis easy to very that Fj = 1 = 3/3 and F) = 2 ~ 25/9, this proves the bass
‘We assume thatthe theorem fs tre for = 1.2... thee the inductive hypothesis, To
prove the theorem, we need to show that Fig = /3)"). We have
tit
by dhe definition, and we can use the inductive hypothesis on the right-hand side,
obtaining
3,
Fun
Fa <9 46/3
= G95)! 4.G/s%G/3"4
= B/D) +G/2515/3"
which simplifies to
Fan O/ F9/2515/9)"
= aH 2515/38"
| <6,
|
proving the theorem.
‘Asaszcond example, we establish the following theorem,
“The prof sb induction, For the bass edly sen that the theorem sre when
N= Forthe induce hypothesis, asm tht the theorem se for 1 = k= WN
‘We wl eaubiah that under thie asumpion, the theorem tre for N+ 1. We have
Desoen!
| Applying the inductive hypothe, we obain
w+ aN +»
i NOE DANDY | ory ye
3
NaN
mo n[SNP sors]
Me 4 TNS
move pitves
_ ove vs DANED
~ 6
Thus,
Sie = We MIN v4 ules D+
2 ¢
proving the theorem,
Proof by Counterexample
The seen i = IP ase, The east ay to prove tis sro compute iy =
Weil
Proof by Contradiction
roof by contradiction proceeds by assuming thatthe theorem false ane showing that his
assumption implies that seme known propery is fae, and hence the orignal sumption
‘was erroneous. A classic example isthe proof that there ean infinite numberof primes. To
prove this, we assume thatthe theorem is fe, so that there is some lgest prime Fi. Let
y,Pa,-.-sPh be ll he primes in order and considerhaper Progamming: A General Ovenew
Ni
PaPys Pat
Clearly, N 1s lager than Py 39, by assumption, Nis not prime. However, none of
PisPhy so PadidesN exactly, because ther wl aleays bea remainder of 1. Thisisacon-
teadcton, because every umber s ether prime ora product of primes. Hence, the original
‘sumption, thot Fs the lagest prime, se, which implies thar the theorem sue
1.3 A Brief Introduction to Recursion
‘Most mathematical functions that we are fala wih are described by a simple formula
For instane, we can convert temperatures from Fahrenheit t Celsius by applying the
formula
«
(F329
Given this Formla, ts eval ro werte a C+ function; with declarations and braces
‘removed, the one-fne formula transits to one Ine of C+
‘Mathematical functions are sometimes define ina less standard form. Asan example,
swe can define 9 function f, vali om nonnegative integers, that sashes J(0) = D and
J) = 2fte~ 1) +32, Flom tis definition we see tha (1) = 1,f@) = 6,3) = 21,
nd f() = 58, A function that defined in terms of sl called reeursive. Cr allows
Factions to be recursive! I important to remember that what C+ provides is merely
an atemp to follow the secursive spint. No all mathemaealyreeusive functions are
ficient (orcorety} implemented by C5 simulation af recursion, The ideas thatthe
"ecusive function f ought tobe expressible in only afew line, jus like a nonsecursive
Fantom, Figure 1.2 shows the recursive implementation off
Lines 3 and 4 handle what is known as the base case, tht i, the value for
‘which the faction i diet known wathout resorting to recursion. Just as declaring
Jos) = Ye— 1) +. t meaningless, mathematically without including the fet that
‘l0) = 0. the recursive Cr fnetion doesnt make Sense without base case, Line 6 makes
the recursive cal
2 ane FC tne)
2
3 ilxo)
+ return 05
Ses
‘ retum 2* fe 1) exes
ra
Figure 1.2. & recursive function
ad ie. We ave dane 0 a lst the ae
"Qing euson freien aly
oe
|
15 Ali readucian to Recs
There ae several important and possibly confusing points about recursion, A common
question is: Isnt this just crculae loge? The answer is that although we ae defining
function in cerms of tl, we are not defining pariculr instance ofthe function in terms
of sel. In other words, evaluating (5) by computing f() wuld be circular. Evaluating
(3) by computing J is not crcular—unles, of couse, (3) is evaluated by eventually
{computing (3). The wo most mportant issues are probably the how and why questions
In Chapiee 3, the how an nh issues ae formally resolved. We wil gve an incomplete
description bere
Te turns out that recursive calls are handled no diferent fom any others Uf is called
withthe value of 4, hen line 6 requires the computation of 2 #3) +44. Ths, a calli
rade 1 compute 3). This regres the computation of 24/(2)+3+3, Therefore another
‘alls made to compute (2). This means that 2«/()-+2-#2 must be evaluated. To do 50,
{f)iscomputed as 24f(0)+ 161. Now, (@) must be evaluated, Since thisis a bse case, we
‘know a prior that f(O) =O. This enables the completion ofthe calculation for (1), which
Isnow seen tobe 1 Then (2). (3), and finally (4) canbe determined Al the bookkeeping
needed to keep tack of pening function calls (those stared but wating fora secutsve
call complete), long with ther variables, s done by the computer automaticaly. An
‘important point, however, is that recursive calls will ke on being made una hase case
is reached, For instance, an atterpe to evaluate f(—1) wil eso nels 0 f(—2).J(-3),
and soon. Since this wil never ge oa base case, the program wont be able o compute
‘he answer whichis undefined anyway). Occasional; a mich more subtle error i made,
‘whichis exhibited in Figure 3, The error in gute 13 is tht bad) 8 defined, byline
6, be bai(2). Obviously. this doesnt give any clue a 10 what bad() actly is, The
computer will hus repeatedly make calls to bad(2) in an atempt to resolve i values
Eventually, ts bookkeeping system will an out of space, an the program wl teminate
sbnormally: Generally, we would say that this fiction doesnt work for one special case
buts correct othersise. Ths sn ere ere, sine bas) als ba). Thus, bad) cannot
be evalusted either. Furthermore, ad(3) tae), and ba4() all make calls to be2). Since
bad2) isnot evaluable, none ofthese values ar either Infact, this program doesn work.
for any nonnegauve value of», except 0. With recursive programs, thete fo such thing
asa special ease
“These considerations lead to the rst wo fundamental rules of ecursion
1. Base cass. You must alvays have some base cases, which can be solved without
2. Maling ogres. For the eases that are to be solved recursively, the ecutive call mast,
lays be ta case that makes progres toward a base case,
fn taal it)
C
return bad a / 340) + n=
2
6
)
Figure 1.3. Anonvtminating recursive faction
aChaper 1 Proamming: A Gerral Overview
“Throughout this book, we wall use recursion solve problems. As an example ofa
honmtthematical use, consider large dictionary. Words in dictionaries ae defined in
tems of ether words. When we look up a word, we might not always understand the
fefntion, so we might have to look up words inthe defition. Likewise, we might nat
tundertand some of those so we might have to continue this earch ora wl, Because the
Alitonary ifn, evenly eer (1) we will come 1o a point where We understand all
ofthe words in some dfinion (and thus understand that definition and rerace our path
through the other definitions) or (2) we wil ind that he definition ae cxeular and we
ate stick, or that some word we ned tounderstana fora defnton isnt inthe conan:
(Our recursive strategy to understand words is as follows: If we know the meaning of a
‘word, then we ate done; others, we look the word up inthe dictionary. we understand
all she words in the definition, we ae done; otherwise, ve igure out what che definiion
rmeans by recurstely looking up the words we don know: Tis procekre wl terminate
ifthe dictionary is well defined but can loop indefinitely fa word iether not defined or
carelaly define.
Printing Out Numbers
Suppose we havea pastve integer, hat we wish to pint out, Our routine wil have the
Deading printut(n). Assume thatthe only UO routines avaiable wll ake a single-digit
‘number and output it We wil ell:his oucine pinta or example, printoiatt() will,
ouput as
Recursion provides avery clean solution to his problem. To print ovt 76234, we nese
to first prin out 7623 and then prin cut +. The second scp is easy accomplished with
the siatementgrintoigit(asi0), but the fist doesnt seem any simpler than the orginal
problem. Inded iti virally the same problem, so we can solve i eeusively with the
statement printout (0/0.
‘This tll us how to solve che general problem, but we sil need to make sure shat,
{he program doesnt loop indefinitely. Since we haven defined base case yet is lear
{Gat we il have something todo, Our base case wil be printbigt(o) * cls.
1.4.1 Basic class Syntax
‘class in C¥ consists of ts members, Thee members can be sther data of functions
‘The factions ae called member functions. Fach instance ofa clas isan abet. Each
‘object contains the data components specified inthe clas (unless the ta components are
static, «detail that can be sly ygnored for now) A member function Is used to act on
an objec. Ofen member function are called methods.
‘Asan example, Figure 1.5 is the Intel! class, Inthe fntCe cas, each instance
ofthe Itcett—an Intel objecr—contans a single data member named storeataue
Everything ele in this parcolr cas fsa metho, our example, ther ate four methods
Two of these methods are read and weite. The other ovo ae special methods known 35
constructors. Let us describe some key Feats,
us, notice che two labels public and private. These labels determine visilty of
class members, In this example, everything exept the storedtatue data mernber i abe,
Storedvatue i private. A member that is ublie may be acessed by any method in any
lass A member that is private may ony be acessed by methods init class. Typelly,
data members are declared private hus restctng acess to internal deals of the class,
while methods inzended for general use are made pubic. This is known as information
hiding. By using rivete data members, we can change the internal representation of the
ject without having an eflec on other parts ofthe program that use the object. Ths
's because the abjet i acessed through the uslte member functions, whose viewable
behavior remains unchanged, The users of the class do not ned to know internal dtl
of ow the oasis implemented. In many cases, having this acess lads to wouble. For
instance, a class tha stores dates using month, day, ane yea, by making the ont, day,
and yer private, we prohibit an outsider from sting ese data members to legal dates,
such as Feb 29,2013. However, some methods may be for internal use and canbe privat,
Ina cas, all members are private by detaul, so the inal ub snot optional
Second, we sce vo constructors. A constructor is 2 method that describes how an
instance ofthe class is constructed, Ifo constructor i exphitly defined, one that inti
izes the data members using language deus is automaticly generated The Intel) class
‘defines two.constrctors. The fst sealed i no parameters specified. The second scaled
‘fan nt parameters proved, an uses hat it toile the storedatue member
|
|
14 + hse
ad
2 "sh ctess for simulating an sntenernesory cel)
3
4 tags tncert
3
Pope
5
*constract the Intell.
initial value t8 8.
woo
neta)
12 { storedaue = 0; 1
B
BO
13+ Construct the ttcet
ip Inittal value 4s snitiavatue,
wy
18 antcett( nt Anstiavatve )
1) ( stareavatue » fnitsatvatany )
2»
2p
21" Retuen the stored value
Boy
Dh int reas)
2 (return storetvl
26
ap
28 Came the stored velue tox
Bo
50 void write tne x )
3 { storeaiatue = ay )
2
23 priate:
‘int storedvalue;
15 Acomplete declaration ofan Ite cass
1.4.2. Extra Constructor Syntax and Accessors
Although the clas works 25 writen, thet s some esta synt that makes for better code
Four changes ae shosen in Figure 1 (ve omit comments for brevity. The ferences ae
a follows
Default Parameters
‘The Intel) constructor usates the default parameters a resul here ae sill #0
Intel! constructors defined, One accepts an inttalvalve. The there the zeo-porameter
ety(Guper Progamming: A Ger Ovrew
onstrucor, which is implied because the one-parameter consiactor says. that
‘nitiatvalve is optional. The default valve of sgmfes that O is used sf no para
meter is provided. Delault parameters can be used in any function, but they are most
‘commonly used in consruciors.
Initialization List
The totCe consructor uss an initialization list (Figure 1.6, line 8) prior tothe body
ofthe constructor, The iialzaton lst is used to nile the data members drety [a
Figure 1.6, theres hardly a diference, but using initialization list instead ofan assignment
ststement inthe body saves ime i the case where the data members ar class iypes that
have complex intalizations. In some cass itis required. For instance, ifa dita member
's const (meaning that it is not changeable after the object has been constructed, then.
the data member’ value can only be intalized in the nialization list. Also, if a data
rember ie tself a cles type that does not have a zero-parameter consort Arms
be initialized in the intihztion lis.
Line 8 in Figure 1.6 uses the syntax
+ storestalel snsattatue }[ )
‘instead ofthe traditional
+ sornatelue(iniettvatue )[ )
‘The use of braces instead of poretheses i new in C+#L1 and is part ofa longer effort
to provide a uniform syntax for initialization everywhere, Genealy speaking, anywhere
you can initialize, you can do so by enclosing initiations in braces (hough there is one
Jmporiant exception n Section 144, relating co vectors)
1
2‘ lass for simulating an tetener menor cel
34
4 clase teen?
51
6
patie
lit Intel1( int snseittatue = 0)
8 Storeaatue} incialvalue | (1
9 nt reas) canst
to return staresvatues }
1 void write int x)
12 storesvaue = 45
6
Hy private
15 int storedatue;
sk
Figure 1.6 Inet) class with revisions
14 i+ ches
explicit Constructor
“The IntceNconsirucor[s exptictt. You should make all one-parameter constructors
‘explicit to avoid behind-the-senes ype conversions. Otherwise there ate somewhat,
lenient sues tha will allow type concersions without explicit casting operations, Usually,
‘his unwamed behavior that destroys stong typing andl can lead to hatd-o-find bugs
‘Asan example, consider the fllowing
Intern ohjs ff ob) $8 an ntcett
hy = 37; Shoulé not conte: type avenatch
The code fragment above consiructs an tntCelt object ab and then performs an assign.
‘ment statement. But the assignment statement should not work, because the righthand
side ofthe assignment operator isnot another Inte]. obfs write method should have
been used instead. However, C++ hs lenient rales, Normally a one-parameter constructor
defines an implicit type conversion, in which a temporary object e created that makes
an assignment (or parameter toa fusction) companble. In this case, the compiler would
tempt to convert
ots + 37; {Shoal rot comptes type mismatch
logcel) teporary = 375
bj temporary:
[Notice thatthe construction of the temporary can be performed by wsing the one
parameter constructor. The use of ep! est means thita one-parameter constructor ean
bbe used to generate an implicit temporary Thus, since faelTs constrictor is declared
fexpcit, the compiler will corel complain tha there is a ype mismatch,
Constant Member Function
‘A member function that examines but does not change the state of its object ian accessor
‘Armember function tha changes the state a mutator (becuse it mutates the sate ofthe
‘objet. In the typical collection cas, for instance, tsepty is an acessor, while makeEmty
In Ce, we can mark each member function as being an accessor o a mutator. Doing
sos an important part of the design process and should ot be ewe a simply a come
ment Indeed, there are important semantic consequences For insanec, mutsors cannot
be applied to constant objects. By default all member functions ae mutator, To make a
‘emer function an accessor, we must add the keyword canst ler the losing parenthesis
‘hat ends the parameter types. The const-ness spat ofthe signature cast cat be used
‘with many different meanings. The function declaration ean have const in three efferent
‘omiexts. Only the canst after a closing parenthesis sgmfes an accessor, Other uses are
described in Sections 1.5.3 and 13.4
ln the Inter class, read is clearly an accessor: it does ot change the sate ofthe
Intcel). Thus it made a constant member function at Ine 9, If 2 member funtionape Progamming: A General Overview
is marked as an accessor but has an implementation chat changes the value of any data
member, a comple err is generated?
1.4.3. Separation of Interface and Implementation
“The class in Figure 1.6 contains all the corect syntactic constructs However, C¥ iis
‘more conimon to separate the cas interface fom its implementation, The interac ists the
data and functions). The implementation provides implementations
lass and ts mem
‘ofthe funecions.
Figure 1.7 shows the class interface for Intel, Figure 18 shows the implementation
and Figure 1.9 shows aman routine that Uses the Ete). Some important points follow
Preprocessor Commands
The interface is typically placed in le that ends with Source coe that requis
rowed of the nerface must field te race le In our ese, this both the
Implementation fie and the le that contains min. Ocasonlly a complicated projet wl
have ining eter les, and there sth ange tat an tcface ght be ead vice
inthe cous of compiling fe. Thiscan be legal To quar against ths each heaer file
teste peproceso fo define a symbol when the das eras iad. Ts soon
Sn ihe fist vo tines in Figite 17. The symbol nae, Inet, shoul not appear
Sy xe fils; we contrac tome Slename. Te ist ine of he netae fle
‘stodef unten
fefing Intel M
+p
5 "+ & clase for simulating an Steger senry cel)
ey
7 clase tntcel)
5 I
°
patie
10 exptsett teat t( tne tniiatvatue = 0s
Fine rea} consts
12 vote mitet fat x Is
B
1 privat
15" sat storetalues
woe
18 tent
Figure 1.7 inter) clase interface in le ntCelLh
° Da mers on be mad abe ode hat conse sald met pp them,
j
|
4 corcases
nce “treet he
bose
4+" construct the Intell with inithaatue
sy
6 Intcerstnetel( tne sasetatvatue ) + storesatuel snstiatvatue)
at
°
wo
11 Return the stored vue
13 tne antcertssreadl ) const
wt
15 return stordtatues
we)
op
21 vald ineettsemitet int}
2 (
Pa
Figure 1.8 intr) class implememsation in ile IntClLepp
sing namespace stds
+
5 int int )
6
8
‘
Ineoatt
9 maritel $5
10 cut <= Cet contontes * ce areal) & en
12 retuen 0:
By
Figure 1.9 Program that uses intel! in fle TestCilepp
35Chaper Progamming: A Gens! Oven
tests whether the symbol i undefined, fo, we can process the file, Otherwise, we do not
process the file (by skipping tothe feng}, because we know that we have already read
the ie
‘Scope Resolution Operator
Inthe implementation fle, which typi ends in pp, ee, F €,each member Function
‘ust ide the clas that it part of Otherwise, t would be assumed thatthe funtion
is in global scope (and silos of ertors would esl), The stax is Classtane: reer
“The «ical the scope resolution operator
Signatures Must Match Exactly
‘The signature ofan implemented member function must match exactly the signature iste
inthe elas imerface. Recall that whether a member funetion i an accessor (va the const
athe end) ofa mutator i part ofthe signature. Thusan eror would result for example,
the erst was omitted from exactly one of the rea sighatues in Figures 7 and 18.
Note that delauke parameters are speed inthe interac only They are omated in the
‘mplentation.
Objects Are Declared Like Primitive Types
In classic C+, an object is declare just ike 2 primitive type. Thus the flowing ae legal
ddecarations of an Intell object
steel! bit 1 ero paraeter constructor
Inecert obj2( 12 )3// Ove paraneter constructor
(On heather and, the fllowing are incoret:
Inetett 2g3 = 37; // Constructor 1s expert
Inecel 8 )4// Funetion declaration
‘The declan of hii ill beans he opr constant.
would bel teen ler word n csc Cael tht see on
former constr mst set frentbsesto sii the ia ae The delrton
ferent sistio va arson ined ere sha taken praesent
iinet
Tis onfsion ohio iu att a ing rs
tas uh tat mang wth ao parameter in acento zation
Tne would rege parentheses with mo prs, bt the see sy wld he esa
entre forage tec. wecan inca wate
Intcelt ob315 jf Zero paraneter constructor, sane as before
icelt gel 12 1s // Ove parameter constructor, sane as before
cel) obs 15 // Zero paranetar constructor
‘The declaration of obi cer hecaseinilcatin with a zer- parameter constructor is
no longer s special syntax case; the iniialiation syle is uniform,
14 corcases
neue stores
tinelade “vector
sing nanespace sts
¢
2
5 int maint)
7 vectors» squares( 100
8
for(int 1 = 0: 6 « squres.size( Is #41)
0 squeresl i} = 09 ts
12 tor it $= 05 4 = squares Je 485)
B out ce ce # ce sqaresl 4] = endl
"
15 return 0;
we)
Figure 1.10. Using the vector class stores 100 squares anc ostpts them
1.4.4 vector and string
The Cr standard defines two classes: the vector and string, vector is intended to replace
‘he bul-n Cr ara. which causes no end of trouble. The problem wih the builen Co
aay i that it does not behave like a first-class object. For instance, buil-n ary cao.
be copied with »a built-in ara does ot remember how many ems it can store and its
Indexing operator doesnot check thatthe index is val, The bun string i simply an
array of characters, and thus hs the labiles of arrays lus a ew more, For instance,
does ne crrely compare wo builtin sings
‘The vector and string classes in the STL rest aris and strings first-class objec.
A vector knows how lage i is. Tro string objects canbe compared with =, and $0
‘om. Both vector and string can be copied with» possible, you should aid using the
bul-in C++ array and sering We discuss the bul array in Chapter 3 inthe content of
hosing how vector canbe implemented,
‘vector and string ae easy to use. The code in Figure 1. 10 creates vector that stores
fone hundted perfect squares and outputs them. Notice also that size is a method that
‘etuins the size ofthe vector nic feature ofthe vector that we explore in Chapter 3 is
that its easy to change is sze In many cases, the ima ie i a he vector Brows as
needed
(Cr has long allowed inital
om of ultsin C+ aerays:
nt aystonth J = (31, 28, 31, 30, 3, 90, 3 315 30, 315 38, 30 Is
"eas annoying that this syrax was not legal for vectors, In older C++, vetors were
‘ether inalized with size @ or possibly by specifying a size. So, for instance. we woul(ChaperProgammig: A Genel Overview
vectorcint> daysiotonth( 12 J: / a {} before CL
Gaystemontn( 0) = 315 daystontnt 1 } = 28; daytonontnl 2] = 315
fayetomontn{ 3) = 305 daysiniorent & } = 315 daysionontnl 5} + 30,
Anystvonthf 6 ] = 305 daystahontnt 7] = 35 aaystomontnl 81 =
‘aystmonthL 9] = 315 daystovontn 10 } = 305 daytetenth( 11] = 3
Cerny this aves sonnei ob dsied. +11 fies this problem and allows
vectorcint>daystfonth = (31, 28,9530, 31530, 325 31s 30s Sty 30, 3 bs
Requiring the +i he iilsation votes he spr of uniform iiazaton, since now
‘se wal have to remember when & would be appropri io use» Consequeth,Co#T1
ioallows (and some pref
vectorcnts dasliorth{ 3, 28 3, 30,3, 30,31, 31, 30,3, 30,31 Je
‘ih pia, however, comes ambguy as one sees with he deraton
vectorsnts dayintonth (12 Is
Isthisa vector ofsze 12, ort a vector of ze 1 witha single element 12 in positon
Gr Covtt es procedenceto the insist, son fact th sa vector of ie Lh 3
single lertent 12 in posion 0, and the intention so ialze a vector of size 12. the
LL Co¥ sya sing parentheses must be used
ectrsint> desta 125 Mast ove () ta eA constructor that tates #6
strings aso cay tous nd a al the eltonal and equality operators o compare
Ane sates of two stg. Thusstriestr2 is rei the vale af the ngs are these,
Slboas Tegth method hat returns the string length
As Figure 110 shows, he has operation on ars indexing wth Thus, the sum
cf hears canbe compte
tnt m= 05
for(int 12 8; 1 ¢squares.stze Js 44)
sam t= squares 15
‘he pater of accessing every element sunt in collection such a an aay ora
vectr uname using ary Indexing or ths purpose does not len express
the idiom. C++1] as a range for syntax for hs purpose The aoe fragment can be
vite sea a:
fort int x + squares)
tnmany eases, the delaaton ofthe ype i the range forstatemnt is unneeded snares
iS vetorcn ils bows that xine fo Be anit Thus C**T1 als lows the
tse ofthe reserved word eto to sig thatthe comypler all somatally infer the
appropri type
for( auto x + squares )
15 Co Dels
The range for loop is appropriate only ifevery stem isbsing accessed sequentially and only
ifthe indexis not needed, Thus, in Figue 1.10 the two Tops eannot be rere as range
for loops, because the index 1 aso being used for ether purposes, The range for loop,
as shown 30 far allows ony the viewing of tems; changing the items canbe done using
symax desribed in Seton 1.5.4,
1.5 C++ Details
Like any language, C>* has its share of details and language features, Some ofthese are
‘sessed inthis ection
1.5.1 Pointers
[A pointer variable sa varale that stores the adress where another object resides, Is
the fandantental mechanism used in many'data structures. Fr instance, o store ist of
tems, we could use a comjguous array, But insertion ino the midle of the contiguous
ray requires relocation of many tems. Rather than store the cllection in an ama. it
's common to store each item in a separate, noncomiguous piece of memory, which is
allocated 3s the program curs. Along With each abject isa link tothe newt object This
links pointer variable, because it storesa memary cation of another object. This ithe
classic ned Ist hat is hscosed in move detail in Chapter 3.
‘illustrate the operations tha apply to pointers, we rewrite Figure 1.90 dynamically
allocate the Inge. Ie must be emphasied that for a simple ite class, there no
pod reason to write the C+ code this way. We do tony to lsat dynamic memory
allocation ina simple context. Later iy the text, we will se more complicated cases,
ere this technique is useful and necessary. The new version i shown in Figure 1-11
Declaration
Une 3illstates the declaration of The* indicates that mis. pointer variable allowed
to point tan fate object. The value of mis the adress ofthe object that it points at
nt mast)
t
1
3
5 me new Intett( 015
6 mewriter $I
Fcout'ee "etl contents: " << moreudl ) << endl
°
2
sete mg
10 retuon 3
nd
Figure 1.11 rogom tat ses piste tote het comping eso odoCaper Progamming: A Genel Overien
fis unintilized at this point In C*4, no such check is performed to verify that mis
tssigned a vale prior to eing weed (however, several vendors make products that do
teidtional checks inchiding ths one). The use of uninalzed pointers typically crashes
programe, because they result in access of memory locations tht de not exis. In gener
tis a good tea t provide an intl value, eter by combining nes 3 and 5, or by
‘naling mto the spt pointe.
Dynamic Object Creation
Line 5 illasates how objets can be created dyzamically. In C+ new returns a pointer
to the newly created object. In C+# there ae several ways to ceate an object using is
zero-patameterconsructr. The fllowing would be legal
se new teal} (106
ms nar Intell Hef a2
rm new Intell; Prefered in this text
‘We generally se the last form because ofthe problem illustrate by of 8in Section 1.43.
Garbage Colleton and delete
in ome igs, en nob no ger fos 8 aj 1 toma
pboge callin he programme docs tae o worry about C# does not have
{Sop colkcon, When a aj that lately nev io Tonge elerenced, the
SStete operon ma be pple a he objet hugh a pate thers, heme
yt consumes st Cl he po ents Ti wns 4 memory
teak Menor kaks are unfunny, common oscenss fm many C¥ progr
Forty nny sour ol eo lke ane tomatic removed wih eae One
impo Tale ono ase ey avhen an abomate variable can be aed nad the
gal progam. tte osc by er bat stead slo var
Sb intharcase the mary orth Intel surly clas when he
whch us deed ree The nee operator kt tne 9 of ig 11
Assignment and Comparison of Pointers
Assignment and comparison of pointer vaable in C++ Based onthe vale ofthe pointe,
meaning the memory adress that stores, Thus two poner variables are equal if they
point at the same objec. IF hey pont at diferent objects, the pointer variables are not
qual, even if the objets being pointed tare themselves equal If ths and rs are pointer
‘ariables (of compatible types) then Thiers makes Ths point atthe same object that obs
pointsat*
Accessing Members of an Object through a Pointer
Ira pointer variable pots ata clas ype, then a (visble) member ofthe object being
pointed at can be accesed va the => operator This is ilustrted at lines 6 and 7 of
Figure 1.11
“Tough ict we we he and gy handed ig and se of nary opera
15 Ce Detas
Address-of Operator (8)
(One important operator isthe address-of operator & This operator returns the men
‘ony location where an object resides and i Uefa for implementing an alas test that i
ioussed in Section 1.5.6
1.5.2 Lvalues, Rvalues, and References
In addon o pointer types, C+* defines reference types. One ofthe major changes in
(C+#1 is the creation of a new reference type, known as an eva reference In oer to
aisuss value references, and the more standard hale reference we need to discuss the
concept of values and reales. Note that the precze rules are complen, and we provide
4 general description rather than focusing om the commer cases that are import in &
language specication and for compiler wes,
An Wale isan expression that identifies 2 nonemporary object. An aval isan
‘expression that identies a temporary objector ia value (suchas @ literal constant) not
associated wth any object
‘As examples, consider the follwing
vectorsteing=aer( 35
int ys
string te = foots
vectorsteings “pte = bars
With these declarations, arr, str, area), y, 2, ptr pte, Centra) ae all Wales,
‘Additionally » is also an value, although itis not a modifiable Walue. Asa general ale, if
you have mame for varable, itis an Kalue, regards of whether iis etiale
For the above declarations 2, oo", x1, strsubste(,1) at all vals. ad "fo" are
‘values because they are literals. Inuively xy is an vale because is value istemporaty
‘eis cerinly not x or y, but itis stored somewhere prior to being assigned to 2, Similar
logic applies fr ste sobstr(0,.
"Notice the consequence that there are some cases in which the result of function call
‘or operator cll can bean ualue (sinc *pr and aera] generate Walues) as does einerty
and othets where i can be an ealue; hence, the Ianguage sy allows a function call
‘or operaior overload to specify this In the return type and ths aspect is discussed tt
Section 1.5.4 Intuitively i the faneton all computes an expression whose vale does
‘ot exist prior to the ell and does noc exist once the calli finished unless its eopied
somewhere is ikely to bean real
Arelerence type allows us a defines new name for an existing value tn classic Cos,
‘reference can generally only ba name for an valu, since hasingateleence toa temporary
would lead the ability to acess an obec that has theoretically been declared asta fonget
heeded, and thus may have had its resources reclaimed for another object. However, in
(C+*11, we ean have two rypes of references ale references and ral relerencesChapter Popming: A Cental Ovniew
ln C¥411, an Wale reference is declared by placing an Baler some type. An blac
reference then becomes a synonym (ie, another name) for the object it references. For
string ste = “hel
String A rste =
Uf vate ts another ane for ote
Y) changes ste ta helTo™
2 Gn ate a te ae ee
sel an [a A ease we
‘string = str ey J] sViegal: stro" 1s not an Walue
SOUEETSE Eat 0,4 /) os Slate, et ee
ln C#+11, an rvalue reference is desared by placing an alter some type. An walue
reference has the sie characteristics as an ale reference except that, unlike an falue
teleence, an Wali reference canalsoreleence an rvalue (Le. a temporary), For stance,
fe
stron str = “hells
String AE bad = "hello" i) bess
String Ab badd = ste + 75 1) teal
String AL sub = strssubstr( 0, 435 Jf asst
Wheres value references have several clear ses in C+ the usltyof ral references Is
nos obvious. Several uses of fale references wil be diseased now, rae relerences are
deferred until Section 1.5.3.
Walue references use #1: aliasing complicated names
The simplest use, which we wil sein Chapter, isto use a local reference variable solely
for the purpose of renaming an objec that is Known by a complicated expression. The
code we vil eis smalar to the flowing
auto & vhichist = theLists{ mhash( x theLists.size( 1 J3
SFL find egin( whichList }, dl wbihlist ), 2) t= end whtcList ))
vnichat pus Baek)
[A reference variable is used 9 that the considerably more complex expression
thelist lnyash(s theists re())] doesnot have to be writen (and then evaluated) four
times. Simply sting
auto whehtist = eListsfmphash( xy theists.stze()) 15
‘would not work; st would ceste 8 copy. and then the push. back operation on the fst ne
‘woul be applied tothe copy noe te original
value references use #2: range for loops
A second use i nthe range for statement, Suppose we would lke to increment by 1 all
values ina vector. This is esy wth for lop:
far snt 4 = 05 4 arr }s_// potentially taf Ticent.
ve Steichen te Co)
‘These sjgnatures all convey dhe base Mea that the function tums an object ofan
appropriate ype that can be used by the aller, inal cases the result ofthe function cll is
snvvalue, However the call orandanttes has potential eficienis. The al oper Si
similaly has poten inefficiencies, though in C=*11 the cal i Nely to be very licenChapter Progamming ACeerl Oeniew
Laretype ranéonttent( const vectorstargetype> arr )
c
return arr{randoaine( 0, arrsize( ) =) 15
const Largetpe &randonttero{ const vectorsLargeipe> 8 arr}
1
3
bo
5
7
return arr randonin( 0, arrsize( ) = 1) Is
a
n vectorstargeTpe> ves
13 Largeype ftom = eandontent( ve Js 1 coy
14 Largerype tterd = randonten2( vee }: WY con
15 const Largelype & Sten)» randontena( vee Js // a copy
Figure 1.12. Two vetsons to obtain random items in an array; second version avoids
creation of a temporary LargeType abject, but only if aller accesses it with a constant
relerence
First, consider to implementations of raneniten. The fst implementation, shown
tn ines It of Figure 112 uses return-by-sale. As esl, the Largetype a the random
ray index wil be copied as pact of the return Sequence. This copy is dane because,
ener, tra expressions could be ralues (eg. return 4) and hence will net logically
vist bythe time the Function cal eins at lie 13, But iy tis ease, the ret type is
fa ale that wll eit long afer the function call returns, since arr isthe same a5 vec
“The second implementation shown at lines 6 lakes advantage of thls and uses returne
byconstantreference to avoid an immediate copy: However the caller must aso use a
constant reference to access the ren vali, as show at Tne 15; otherwise, cere val
sill ea copy. The constant reference signifies that we do nat want ta allow changes to be
rade by the caller by using the return value in this as it ts needed since ar self sa
non-mevifable vector. An altemative so use auto at line 15 to declare tn
Figu 1.13 illustrates smal ststion in which call by-vala was nficient in las
sle C+ due wo the creation and eventual cleanup of copy. Historically, C++ programmers
have gone to great extent to rewrite their code san vatual ay, using Techniques
Involving pointers or additional parameters that decrease readability and mainiainabiy,
tventally leading to programming ers. In C+*11, objets can define move semantis
that can be employed when reurm-bj-value is seen in effet, the result vector will be
‘moved to sun, and the vector implementation i optimized to allow dis oe done with
lige more than a pointer change. This means that partial Sutas shown in Figure 13 can
be expected to avoid unnecessary copying and no need any changes. The dtals on how
move seman are implemented ae discussed in Section 1.5.6, vector implementation
‘slscussed in Section 3.4. Notice thatthe move semantics can be called on result at ne
‘im Figure 113 but not on te returned expression at lie 3 in Figure I-12 Thsisacon-
sequence of the distinction between a temporary and 3 non temporary, andthe distinction
‘between an Walue vference and an rae eerence
15 Co Deas
1 vectorsintspartialSun const vectorsiat»& arr )
21
5 wwetoreints resale anrsae( ) )s
5 esate 0} = arrl 01:
© for ane f= ty te arrastzel Jy 4)
7 result) ] = result 1-17 eae 095
8
9 return rests
wy
12 vectorsint> vee,
14 wectorsint> suns = partitSun( vee )s // Coy in old Cis nove sn ceett
Figure 1.13. Returning ofa stackealocated value iy +421
In ation to the rtur-by-vale and retun-by-constant-reference idioms, functions
fan use returm-by-eference, This idiom is used in afew places to allow the caller of
function to have modifiable accesso the internal data representation of clas, Retrn-by-
reference in this contexts discussed in Secon 1.72 when we implementa simple mates
chase
1.5.5 std::swap and std: :move
“Throughout this section, we have discussed instances in which C+#11 allows the pro=
arammer to easily replace expensive copies with moves. Yet another example ofthis is
‘the implementation ofa swap routine. Swapping double is easly implemented with three
copies, as shown in Figure 114. However, although the same logic wore to sap larget
‘types, it comes wih a significant cst: Now the copies are very expensive However itis
easy fo see that there i no need to copy; what we atally want i to do moves instead
of copies. In C++11, if the righthand sie ofthe asignment operator (ot construct) is
an male, then if he abject supports moving, we can automatically void copies, In other
‘words i vectorstring supports lfcent moving. and fat ine 1D x wee an value, then
‘could be moved ito tap; similarly fy was an walue a ine 11 then it could be moved
Into y. vector does indeed support moving however, yy, and tp ae al hs at ines
10,11, 12 (remember, if an object has a name, ta fae). Figure 1.15 shows how
this problem is soled: an implementation of sap at lines 1-8 shows tha we cam use 8
{ast to treat the ght-hand side of lines 10-12 as rales, The syntax of a sae cast i=
daunting; orunatly, function ste: nove exits that converts any Wale (or ree nto an
‘value. Note that che name is misleading st: :mve doesn move anything: athe, makes
aval subject tobe moved. Use of st: emove is aso shown ina vevsed implementation of
Sop at ines 8-13 of Figure 1.15. The swap function sa: ssa is alsa part of the Standard
Library and wal wor for any pe.Chapter Progamming: A Cental Ovenien
1 vote suan( double Bx, double 8)
3 double tee = 5
3 yew
5 votd spt vectorstring & a, vectorestrig® By)
ot
10 vactoresteing> tmp =
ye tps
Boy
Figure 1.16 Swapping by three copies
1 void suap( vectorcstringy & x, vectorstring> y )
201
5 wnctorstringe tp = stati castevectorsstrigy B(x}:
Ske atatieesstevectorntring= BEC Ds
5 ye stabileastevectrcetring> AB( tap 95
6
8 vot aap( vectorcstring & x, seotorestriag> By)
ot
10 vectorsstring> tmp = sts imovel x}:
0 se stasenovel Is
12 ye stdrmovel to}:
Bo
Figure 1.15. Swapping hy these moves first with a typecast second using stove
1.5.6. The Big-Five: Destructor, Copy Constructor, Move
Constructor, Copy Assignment operator=, Move
Assignment operator=
In C+#1, clases come with Sve special fetions that are alteady ween for you. These
ae the destructor, copy constructor, move constructor, copy assigament operator,
Sn move assignment operator. Collectively these ae the bigfive, In many cases, you
‘an acept the default behavior provided by the compiler forthe big five. Sometimes you
Destructor
‘The detractors called whenever an object goes out of scope ori subjected to a delete.
‘yp, the only responsibilty ofthe destructor i offee up any resources cha were
15 C+ betas
acquired during the use of the object. This includes calling delete for any comespond:
ing news, closing any files that were opened, and so on. The desu simpy apples the
desirsctor on each data member,
Copy Constructor and Move Constructor
Tere ae two special constructor that ae required to construc anew object, ntalized
to the same sate as another objec of the same type. These ae the copy constrctr if the
‘visting object alu, and the move constructor ithe existing object an wale
(ce, a temporary tha is abou tobe destroyed anyway). For any objet, such aan Intel)
ale, a eapy construct or move constructor i ale in the fllowing instances:
+ delestion sth nilsson, such
nceld 8 = ctf apy eanetract $C 4s Teun; Hove construct Hf 48 ralue
Intcalh 8 (CIs // Gaby canstroct $C 42 Teas; Hove construct if Cis ralve
bot ne
ac 11 Assignmant operat, discussed later
+ an objet passed using call-by-valie (instead of by & or canst), whic, as mentioned
carer, should rarely be done anyway
+ an objet returned by value (instead of by or const 8). Again, a copy constructor is
Invoked if the object being returned fs an le, and a move constrictor invoked i
the abject being returned isan rae
By default, the copy constructor is implemented by applying copy constrictors to each
dita member in unm, For data members that are primitive sypes (or instance, it, dub,
‘oF pointers, simple assigment is done, This would be the eace fr the storedtale data
member n our Ince class. For data members that are themselves class abject, the omy
constructor ar move cansrctor, as appropiate, or ech data members class is applied
‘hs dts member
Copy Assignment and Move Assignment (operator=)
led when «is applied to two objects that ave both been
The assignment operator is.
previously constricted. Ihsrhs i intended co copy the sate of re ant Ths tis an
Ile, dis is done by using the copy assignment operator, if isi an ral (ie. ate
porary thats abou to be destroyed anyway thsi done by using the mave assignment
‘operator By default, the copy assignment operators implemented by applying the copy
assignment opeato teach data member in tn
Defaults
If we examine the Intel clas, we see that the defanls ate perfectly acceptable, 0 we
do not have to do anything. Theis often the case. If clase consists of data members
chat are exclusively primitive pes and objets for which the defaults make eens, the
class defaults will usually make sense. Thus a class whose data members are int, double,
vectorein, string, and even veetonertring> can acept the deft,Chapter Poyanming: A Cent Ovenien
“The main problem occus ina class that contains data member that pointe: We
well describe the problem and solusons in detain Chapter 3 for now, we can sketch
the problem. Suppose the cass contains a single data member that is «pointer. This
pointer points ats dynamically allocated object. The default desractor does nothing to
‘lata members that ae pointers (lor good reason—recll that we must dette ourselves).
Furthermore, the copy constructor and copy assignment operator both copy the value of
the pointe ater than the objects Being pointed at. Thus, we will have wo clas instances
thor consin pointers that point fo the stme object. This i a so-called shallow copy.
“ype, we would expecta deep copy in which clone ofthe ene abject stad, THs,
sa result, when a class contains poimters as data members, and decp semantics are imp
tant, se wyplelly must implement the dstucter, copy assignment, nd copy constactors
tureeies. Doing so removes the move defaults, 20 We alzo must implement move assign
rment and the move consiructor Asa general, ether you accept the desu forall ve
operations, or you should declare alle, and explicily define, defzlt use the keyword
sett), or disalfow each (use the Keyword delete), Generally we wil define al ve
Tor Ince, the signatures ofthese operations ate
inten 3 If Destructor
ntcell( conse tntcell & rhs) | Copy constructor
Intcet( tet? 8h rhe Is | Nove constrictor
ntcell & operator= (canst 1tGelt 8 As Js [Copy assignment
Inet) 8 operator= (Inte? Bb ths Uf Nove assignment
The rum type of operators aveference 19 the invoking object, so 35 wallow chained
assignments bec, Though it would scem that che return spe should hea const reetence,
503510 disallow nonsense such as (ab), that expression isn fact allowed in C+ even
for integer types. Hence, the reference eur type (rater than the const reference return
'ype) customarily used buc snot sel regutred by the language speciation
Ifyou write any ofthe big-fve, ic would be good pracce to explicitly consider all
the others, 3s the defaults may be invalid or inappropriate na simple example in which
debugging code i placed inthe destructor, no defult move operations wil be generated
‘And although unspecified copy operations are generated, that guarantee Is deprecated and
might not be ina future version of the language. Thus, i i best o explicitly list the
opy-and-move operations aa:
Inecali() ( covt << “Invoking destructor" << ends) / Bestructor
SntcetI( cont Intell rhs} = defies Uf Copy constructor
necell( cel ab es} = defaults 4 Nove constructor
Incell & operators (const Intnl! bbs ) = defeults Jf Copy asrtanane
InecelT 8 operator= (tate) ab rhs = defatt; 1] Move asstgonent
Alieraively, we could dsllow all copying and moving of Intell s|
ntcelt( cons tntce1t A rhs)» dete J[ No Copy canstrctor
Inet Intel? 26 rs} = deletes Uf Ne Nove constructar
Intell & operators (canst Intell brs } = deletes // No Copy ossigmant
Inet operator= (Intel) ab rhs ) = delete; 1 Wo Yove astaement
15 ci bets
Ifthe defalts make sense in the routines we we, we wil always accept them. However, if
‘the defaults do not make sens, we will need to implement the destructor, copy-and-move
constructors, and copy-and-move assignment operators. When the dela doesnot work,
{he copy asignment operator can generally be implemented by creating a copy using the
copy consructor and then swapping it with the esting abet. The move assignment
‘operator can generally be implemented by swapping member hy member.
When the Defaults Do Not Work
‘The most common station in which the defaults do not work occurs when data mem
beri pointer type and the pointer is allocated by some object member funcion (such
asthe constructor) Asan example, suppose we implement the ince? by dynamically
allocating an int, a shown in Figure 116, For simplicity, we do not eparite the interlace
and implementation
There are now numerous problems that are exposed in Figure 1.17. Fist, the out
put is three 4, even though logically only a should be 4. The problem is thatthe
‘etal copy assignment operator and copy constructor copy the pinrstoredalue. Thus
storia, b.staredvalue, nd e.staredvtue all point a the same ine vale. These
‘pies ate shallow the pointers rather than the points ae copied. second les obvious
problem isa memory leak. The st inal allocated by as constructor remains allocated
and needs tobe reclaimed. The jnt allocated by cs constructor is no longer elrenced by
ny pointe varabe. Ir also needs tobe reclaimed, but we no longer have a pote ot
To fx these problems, we implement the big-ive. The esl (again withour separation
of interface and implementation) is shown in Figure 1 18. As we ca see, once the destrc-
torts implemented, shallow copying would led to a programming eror: Two Intl?
objets would have storetatue posing atthe same tnt object, Once the Bist Ital?
tbjets destructor was invoked to reclaim the object that ks stredvalus potter was view-
ing, the second ince abject would have a sale storetatve pointer This ie why C+#1L
has deprecated the prior behavior that allowed default copy operations even ifa destructor
20
3 patie:
4 extiese ante tnt tnittalvaue = 0)
5 | oreaalue = new int inittlVatue
6
7 tnt reed) const
8 {return *storearatue: |
9 void writel jot # )
0 {sStorebvalue =a:
12 private
15 ine stared
wok
Figure 1.16. Data member isa ponte, defaults are no good.apter Poyenming:A Gener Oven
1 ome)
2
3 etett af 21s
4G ecern 6
3 retell es
5 aaitel &
9 cout e arash) ee endl < Buren) endl << cares) ents
0 return 6:
Roy
Figure 1.17, Simple funccion that exposes problems in Figure 1.16
‘The copy assignment operator at Ties 16-21 uses 2 standard idiom of checking for
aliasing at ine 18 (ie. a stleassignment, in which the cient is making seal obo)
nd then copying each data fed neuen a5 needed. On completion, it retums a reference
to self using “ths. In C+#11, copy assignment is olen writen using a copy-and-swap
fom, leading to an alternate implementation
16 Intend & operator» ( const Inte) & rhs Hf Cony assiaent
wt
is Inecalt copy = rs
is stdssuap( *ths, copy Js
20 return "this
a ,
Line 18 places copyof rs ino apy using the copy constructor Then this cory is swapped
imo “ths, placing the old contents ino copy. On return, a destructor is invoked fr eo,
leaning up the od memory For Inte this sa bc neice, but for other pes, espe
cally those with many complex imeractng data members, it ean be a reasonably good
daft. Novice that if sap were implemented using the basic copy algorithm in Fg
1L14, the copy-and-swap idiom would not work, becuse thee would be muna non-
terminating recursion In C**11 we havea basic expectation tht swapping is implemented
citer with three moves or by swapping member by member,
The move consructr at lines 13 and 14 moves the data representation from rs in
‘this: the i ses hs’ primitive data (including poincers) toa vali but easly destroyed
state, Note that i there is non-prmatve data then that data mst be moved in the in
talistion ist. For example, if there wot leo vectorstring> tans hen the consractor
woul be
Inter ter Abe) «stores stores
feel stint esters)
[rh stortvie = titer |
1 ore costar
15 t+ ets 33
i
gliestitce0( tnt tntiatate = 0)
T stores = en Int Sestateeaes
Inte} iy osserscar
Intcenn( coe tc & rs)
Tistoreseiue= en ine srstoreteae 5
Inecel( intel bobs} storseael Mesterafvaue | // ove constractor
Trvbsstoreatate = mllpty T
Intett & eperatare canst Uncath & te)
i
1 98 te eke)
1 Coy sessment
yy
Intel & operators (ntl ab 8)
i
suse storedatu, ste atordteae Js
nt yeaa) const
° I reure stores |
SI eld write ant =)
2 [storetaln = 85 |
3
wo “
Figure 1.18 Data member isa pointer; bg-ive is ween
Finally the move asignment opertor at lines 23-27 i implemented a5 a memberby
‘member swap. Note tha sometimes ts implemented asa single swap of ejects in the
sime manner asthe copy assignment operator, but that only works swap self is mple
‘mented a6 2 memberby-member swap. I swap is implemented as three moves, then we
‘vould have mutl nomterminating recursion.
1.5.7. Gstyle Arrays and Strings
The Ce language provides a built-in C-tyle anay type. To declare an array, arr of 10
smtegers, oe wre
tne serif 10 35Chaper Progaming: A Gener Overien
are is actually a poincerto memory thats lange enough to store 10 Ins, rather than
1 firat-clas ray type. Applying» to ara is ths an aempt to copy 180 pointe values
‘ather than the entre aay, and withthe declaration above, illegal, because arr i=
4 constant pointer. When arr is passed to a function, only the valve ofthe pointe i
‘passed; information about the sizeof the aey is los. Thus, the size must be passed as an
tuitions parameter. Thee is no index range checking, since the sz sunlnowen,
Inthe declaration above, the sizeof the aay must be known at compile time. A
‘rable enn replace 10 the size isunkowm, ve must explely declare a pointerand
allocate memory va nev]. For instance,
nt are? = noe intl 9 Js
"Now ar2 behaves lke are, except that is nota constant pointer. Thus, ican be made
to point at a lager block of memory. However, because memary has been dynamically
aloated, at some poinc must be feed with delete):
state [] aves
(Otherwise, a memory lak wil sul, ad the leak could be signfianr fhe ara sage
‘Buln Cyl stings ae implemented ae an rey of characters. To avoid having to
prs the length ofthe string, che special ull-terminator "0" used a5 a character that
‘Signals the logical end of the string. Sings are copied by strep. compared with sre,
land ther length can be determined by strlen, Ina chataters canbe accessed by
the array indexing operator. These strings have al the problems associated with ars,
including dificult memory management, compounded by the fat that when strings ane
‘copied ig assumed thatthe arget array i age enough to hol the result. When it sno,
dificult debugging ensues, often because room as not bee et forthe nul teria
“The standard vector cass and striag cass are implemented by hiding the behavior of
the built-in C-style aray and string. Chapter 3 discusses the veto clas implementation
leis almost always beter to use the veetar and string clas, but you may be forced to use
the Coyle when interacting with Mbrary routines that ae designed to work with atl C
and C+. talso i occasionally necessary (bu ths sare) to use the C-sle in section of
code that must be optimized for speed
1.6 Templates
Consider the problem of finding the largest tem sn an aeray of tems. A simple algorithm.
‘sthe sequential sen, in which me examine each item in oder, keeping tack ofthe maxi
‘un. Asstypical of many algorithms, the sequental scan algohm is type independent
By type independent, we mean that the logic ofthis algorithm does not depend on the
type of stems that te stored in the ara. Te same logic works fr an arty of integers,
floaing-point numbers, or any tye for whic comparison canbe meaningfully defined
Thoughout this text, we wll desonbe algorithms and data structures that ae type
‘independent When we write C++ code fora type-snependent algorithm or dts strict,
sve would prefer to write the code once athe than secode ifr each dileren ype
ee
16 Templates
In this section, we will desetbe how ype-independent algorithms (also known 38
generic algorithms) are writen in Ce using the template. We begin by discussing function
tempites, Then we examine class templates.
1.6.1 Function Templates
Function templates ae generally very easy to write. funtion template isnot an actual
function, but instead isa pattern fr what could become a function. igure 119 usa
2 fancion template fiwdfax. The line containing the tenglate declaration indicates tha
Caparabe isthe emplate argument Itcan be replaced by any type to generate unto,
Forinstance, fa cal to finds made with a vectorestring> as parameter, then function
wll be geneiated by replacing Carparabie ith sins,
Figure 1.20 lusts that function templates ate expanded antomatically a needed
Ic should e noe that an expansion foreach new type generates additional coc: thsi
known as code blot when it occurs in large projets. Note also that thecal fixed)
wil result na compile-time eror. This is Because when Comparables replaced by ince,
line 12 in Figure 1-19 becomes legal; there is no «function defined fo ital, Thus it
Is customary to include, prior to any template, comments that explain what assumptions
are made about the template argumens). This includes assumpxions about what kinds of
‘onstrcions are requited
Because template arguments can assume any class ype, when deciding on pramet
psssng and return-pssing conventions it shouldbe assumed that emplate arguments are
not primitive ypes. That is why we have recumed by constant eletence
[Not suprisingly: there are many arcane rules that deal wit function emplates. Mos of
the problems accu wien the template cannot provide an exact match forthe parameters
but can come close (chrough implicit type conversions). There must be ways to reslve
1
2 "+ meturn the maxinun Sten Sn array a
3% Assues ansize( ) > 0
const Comparable & Finan const vector& 2 )
© tatplate«typenane Conperabie=
Bt
9 tne mainder = 05
1 for€ Ame 4 ety $e acstee( 5 048)
2 6¢( af mecinder }= a0 41)
B antader = 15
14 retaen of masindex 5
Bo
Figure 1.19. fsnatex function template(ChaperProgarmig: A Gener Oveniew
nt aint)
2
5 wectorsints v1 375
4 ectoredoules ¥2( 404
5 wectonestring= ¥3( 0 5
& —ecoreintcel> wl 75 94
3 f Rittona cate to F111 Inthe vectors nt shown
°
10 cout ee Fatant vL}
5) class Henne
61
7 plies
8 explicit Maorycel( coast object snittalalue = Object! })
9s storedatue( nitiatvelue 11)
10 const Object & reat} const
n return staredslons
12 vovd write( const obgect 8)
1 storastolue = #5)
1 private
15 Object storetatues
ie
Figure 1.21, sonoryCel} class template without separation
|
j
|
16 Templates
1 ant ming)
21
3 Meorycettcint> ms
4 enorstellestring> helio" Is
5
© mtewitet 37)
7 bnritel m2. roadl + Sear Js
faut v = | Squaret 3.0 J, Square 2.0 Jy Smsrel 2.5.) 5
3
Deak ce “Largest squares * < finihox( ) <= end
35
36 return 05
an
Figure 1.25 comparable canbe a class ype, suchas Square
Figure 1.23 shows an example of a clas ype cha implements the functionality
required of Canara and illustrstes operator overloading. Operator overloading allows
ts to define the mesning of built-in operator The Square class represents 2 square
by storing the length of side and defines aperstore, The Square clas also provides a
zero-parameterconsiricor, operator, and copy constructor al by deful). Thus, has
‘enough to be used 35 Caparae in Finda
16 Temps
Figure 1.23 shows minimal implementation and also illustrates the widely used ior
for providing an output function for anew clas type, The idiom i Io provide a wualic
ember function, named prt, that skes an ostreanasa parameter. That gue member
fancion cam then be called by’ global, nonclas functton, eperstore, that accepts an
ostrear and an object o ouput
1.6.4 Function Objects
In Section 1.6.1, we showed how function templates canbe wed to write generic algo
rithms. As an esample, the funtion template in Figure 1.19 ean be used to find the
‘maxim item in am ary
However, the template has an important imitation: ft works ony for objects that
hve an operatore function defied, and i uses that operator as the basis forall com-
panson decisions. In many’ situations, his approach isnot fesible For instance, is
‘sretch to presume that a ectangle clas will implement opestore and even iit des, he
‘anpareTo method that it has might not be the one we want. For instance, given 2 2
by-10 rectangle and a S-by-5 rectangle, whichis the larger rectangle? The answer would
depend on whether we are using area oF width to decide. Or perhaps if we ate ty
ing to fr the rectangle through an opening, the lager rectangle is the rectangle with
‘he Larger minimum dimension. As a second example, if we wanted to find the max
imum string (alphabeviclly las) in an array of stings, the del eperatare does aot
‘gore case distinctions, 30 “ZEBRA would be considered to precede “alligator” alphabet
‘ell, which i probably not what we want. A third example would occur i we had an
may of pointers to objects (which would be common in advanced C++ programs that
sake use of feature known 2s inhertance, which we do not make mich us of this
i)
“The solution, in these cases, so rewrite Finda to accept a parameters an amy’ of
objets and a comparison function that explains how 10 decide which of two objects is
the Langer and which isthe smaller. In effect, the aay objects no longer know how to
compare themselves; instead, this information is completely decoupled rm the objets in
the ary
‘An ingenious way to pass functions as parameters sto notice tha an object contains
both data and member functions, 0 we can define class with no data and one member
Function, and pass an instanceof the class. In eft, 2 function is being passed by placing,
itinsde an object. This abject s commonly known as function object.
Figure 1.24 shows the simplest implementation ofthe function objet ides, fsnatax
takes a second parameter, which is 8 generic «ype. In order for the finn tem
Dive to expand without evr, the generic type must have 4 member function named
‘stessinan, which takes ro parameters of the Brs genric type (Object) and returns a
tol, Otherwise, an error will e generated a line 9 when the template expansion is
atempeed by the compiler line 25, we can sce tht fod i called by passing an
aay of string and an object that contains an SsLesthan method sith to sings as
parameters.
(Crt function object are implerneted using this base ida, but with some fancy syn=
‘ax. Firs, instead of using a function with a name, we use operator overloading, Instead
ofthe function being tsesstha, iti operator(). Second, when invoking aperator(),
nsCopter Poyanning:A Gent Oveniew
1 J) Generic fniran, with a funtion object, Version #
2 /f Precondition: size )> 0.
3 Yamplate
4 const chjoct Finda conse vectorcthject> & arr, Canparator exp }
54
S$ for int = ye aresizel Is Hh)
° fC enp.tstessthan( are{ manndex Jy are #1))
w ravine = 3
12 ratern are mainder }¢
Boy
4
wot
a paotte
18" bool tLessThan const string & hs, const string ohs ) const
» (return streaseem( thse str(), msve.str() © 41
Dok
22 int mint )
BI
24 wectorestring arr = AZEBRAY, "alligator", roeod!2e* Js
25 out findan( are, Caselnsnettivetnparel ) <= endl,
25
Bt
Figure 1.24. simplest idea of using fu
output i ZEBRA
1 abject aa second paramster to fino
cmp-operator()2,4) canbe shortened to empty) (in other words, ook ike a funtion
call,and consequently aperator() is known as the Funetion call operator). As result the
tame of the parameter can he changed to the more meaningful Ssessthas, andthe call,
| tsLesstan(y). Third, we can provide a version of fina that works without a func
tion object. The implementation dss the Standard Library fancion object template Tess
(defined in bead ile functional o generate a function objec that imposes the normal
Aefolt ordering, Figure 25 shows the implementation using the mote spi, somewhat
ype, C+ idioms,
in Chapter 4, we wil give an example ofa clas that needs o oder the tems stores.
‘We will wre most ofthe code using Comparable and show the adjustments needed to use
the function objects. Elsewhere inthe book, we will vod the deta of function objets 10
-ecp the cae as simple as possible, knowing thar tis nat dificl toad function objects
Ter
16 Templates a
| Generic findlan, with a tanctionebsect, CH syle
| Precnestion: a.st2e( } > 0,
Template
canst Object 8 indo const vectoreibject>& are, Comparator isLesthan )
‘nt maxinder = 0
for(int 1 = p< aresize( Js 48)
64( ssteesThan( ore mixinder 1, arr 4.)
return arr maxtoder
1
1 Generse Ca, using default ordering.
‘nce
tesplate
ont object & finatax const vectarconject> 6 arr)
fi
return finda arr, lesscoajeet } )s
1
ass CasetnsnasthveCopare
1
boo} operator( (coast steiap & hs, const string & rhe ) const
(return streaseen(ths.c str Js rhe str) ) <0 |
h
int maint)
'
vectorstring» are = | 22a
NVgtor", terocosilet
cout Finan arr, CasetnsensitiveCanpsre| J ) <= ends
aut << Fira arr) <= ends
return 05
,
Figure 1.25. Using fonction object C++ se, with a second version of Finda oxtput
‘= ZEBRA, then crocodileChapter! Popanaing:A Gener Overview
1.6.5. Separate Compilation of Class Templates
Like regular clases, class templates can be implemented either entirely in ther deel
fations, or we can separate the interac frm the implementation, However, complet
suppor: for separate compton of templates historically has boen weak and platform
specifi. Thus, in many’cases, he entire clas template with ts impememtaion pled in
‘single header file, Popular implementations of the Standard Library follow this strategy
to implement cles erplates
“Appenuis A describes the mechanics involved in the separate compilation of templates
The declaration of the interface fora template is exactly what you would expect: The
member functions end sith 2 single semicolon, instead of providing an implementation
[Bu as shown in Appendix A, the imiplementstion ofthe member hinctions can introduce
complistedlooking satay, especialy for complicated functions ike aperatom. Worse,
‘when compiling, the comple wl fen complain about missing functions, and avoking
{his problem requires pailorm-specfi solutions.
Consequently in the opline code tat accompanies the text, we implement al lass
templates entirely in ts declaration na single head le. We do So because it seems to be
‘he only way to avoid compilation problems across platforms. Inthe tet, when llstrating
‘the code, we provide the cas interac a if separate complation was in oder, since that
is easly presentable, but implementations ae shown asin the online code. Ina platform
specific manner, one can mechanically transform out sng hezder fle mplementtions
into separate compilision implementations if deste, See Appendix & for some of the
llrent scenarios that might app
1.7 Using Matrices
Several algorthms in Chapter 10 ws owo-dimensional areas, which ae popula known
fas anaices, The C# library dors not provide a matrix class However, «reason
ale matrix class can quickly be wien, The basic ia is 10 use a vector of eer
Doing this requites additional knowledge of operator overlosding. For the matrix, we
define operstor{], namely. the acry-indexing operator The matrix class given In
Figure 126
7.1 The Data Members, Constructor, and Basic
Accessors
‘The matrix i represented by an array data member that fs declared 19 be a veeter of
vectorctbject> The construcior fis constructs array as having rows entries each of ype
‘ectorethject that constructed with the ero parameter constrictor. Ths, We have rs
2eorength vectors of object.
“The body of the constrictor is then entered, an each row Is resized to have cts
columns, Thus the consrdcor terminates with what appears to be a two-dimensional
fray. The ninrows arid muneots accessors ate then easily implemented, a8 shown,
17 Using atic
‘aeine HATROH
include
sing manespace st
7 taptate typename obs
ot
so pote
atrin( t9t row, int cols) s arayt rows}
for( auto & ehsiou © array )
thistowsresize( cals)
'
satrin( wectorevctoredaecte> ¥ ) array)
a
satrin{ vectorevectoretjecte> Mk J: array( stscnove( ¥} |
0
const vector & operator] ( Snt row} const
{return array row Is 1
vectorsthject>& operator()( int row )
{return arrayl row |
tne mamrovst} const
{return array.size()s |
tnt mane) const,
(return namowst } 7 arrayl 0 esize( ) 05
wectorsvectoronjects> arrays
3s
Bh tendst
Figure 1.26 A complete atetx cass
1.72 operator[]
The idea of operator() is that if we have a matrix n, dhen aft) should return a vector
corresponding to row 4 of matrix IF this is done, then aft}{3} wll lve the entry in
position 3 for vector aff, using the normal vector indexing operator. Thus, the mata
operator(] retusa vectoethject rather than an dbect.hayes Progamming: A Genel Oven
‘We now know tha operatot) should reuen an entity of ype vetareonjet> shoul
we use return-by na, recur by-releence, of return -by-constant-elerence? Immeshtely
‘we eliminate return-byvalue, because the returned entity is lage But guarantced to exist.
afer the cll Thus, we are down to retumm-by-eerence or retur-by-constant-efe
Consider the following method (ignore the pasty ofalusing or incompanible 3:
nether of which aft the algorithm
ose capy( canst matrixcint>& from, mtriscint> & to )
t
for st = 0) 4 = tonnes Js +44)
tol 5] = tron §
)
In the copy function, we attempt @ copy each Yow mates fran ito the corresponding
row in matrix to. Clear} if aerator] recurs 2 constant reference, then to] cannot
sppearon the let side af the assignment statement Thus, Itappeas tha aperator() should
returna reference. However, we did ha, then an expression suchas fron{itof8] would
‘compile, since fron] wold not be a constant vector, eventhough fran was 2 constant
tmatrix, Tha cannot be allowed in a goed design,
So what we relly need is for operator) to return a constant reference for fre, but
2 plan reerence for to In ther words, we need wo versions of operator), which difer
‘only in theirrevurn types. That snot allowed, However, there isa loophole: Since member
function conseness (Le, whether a function isan accessor or a mutator is part of the
signature, we can have the accessor version of aperator(] return a constant reference, and
Ihave the mutator version return the simple rerence. Then, alls well Ths is shown in
Figure 1.26.
1.73 Big-Five
These at al ken care of automatically because the vetor has taken eae oft. Therefore,
this sal the ce needed fora fll functioning matrix class.
Summary
‘This chapter sets the stage forthe rest of the book. The time taken by a algorithm con
fronted with Inge amounts of input wil be an important entenion for deciding i i 3
good algorithm. (Of couse, correctness most important) We wil begin address these
FEsues in te nex chapter and will use the mathematics decuseed here oesablish a formal
rmocel
Exercises
1.1 Writes program to solve the selection problem. Let
‘he running me of your prograa for varios values of N.
1.2. White a program to solve the word pele problem,
12, Draw table showing
13
1a
1s
16
ay
1s
19
10
un
1a
——
eres 6s
‘White recursive routine printout) fora non-negative integer to printout digs.
Forexample for n= 76543, printdut() should print ou the digs 7,6, 6,8 and 3
(Cet allows statements ofthe form
tude fina
which reads ilame and inserts its contents in place of the inde statement.
Inde saternents may be nesied i ater words, the le lenane may lf com
tain an inde statement, but, obviously a ile ant inclade tet im any chain
‘Wire a program that reads in fle and outputs the file as modified by the Inne
‘Write recursive faction that retuens the number of s inthe binary represents
tion of. Use the fact that his is equal tothe numberof Os in the epresenttion
of N/2, plus LN seven,
‘Whe the routine srt the follwing declarations
void permute( const string & str Js
od permutel const String & Str, Int Tow, snt hgh Js
The fist routine i driver that calls the second and prints ll the permutations of|
the characters in string str I tre tae then the strings that ae outpaave abe,
4b, ba, bea, ca and ea. Use ecusion for the second routine
Prove the following formas
4 logAB = logA +-1og3a,8 > 0
log (4/8) = log ~ log. 4,8 > 0
Evaluate the ollosang sums:
Using prof by induction, show tat for
po NOE DAN D
6
hats 4 (od 9?
Le Fs be the Fbonacl numbers as deine in Seton 1.2. Prove the lowing
2s
b Fe 6 wih g = + 5/2
Grea proce closed-form expression for Fy
lune the sens
b 245484 46k)Chapter Programming: A Cenerl enon
113 Design a clas template, cottectia, that stores a collection of Oagects (i an arty),
slong withthe current size ofthe callecuon. Provide public functions sstmty
okey insert, nove and cantans, contains (x) tbr tr f and only fan
fuse that sequal tom present in the collection
LAA Design a clas template Orderecerecton, tht stores 3 collection of Caparabtes
{nan ary) along withthe corent sizeof the collection, Provide abc functions
‘sptynakelapty inset, ranove, finale, and Findon. finan Faas veturs
releences to the smallest and largest, respectively, aaparabte in the collection
Explain what canbe done i hese operations are performed on an empty collection
LAS) Define Rectangle class that provides getLength and getwidth. Using the tindlax
routines in Figore 25, write tate that crates an array of Rectangle and fins the
Tangs Rectang rst on the base of area and then onthe bass of perme.
LAG Forthenatrixclas, ada resize member function and zero-paramecer constructor,
References
‘There ate many good textbooks covering the mathematics reviewed inthis chapter. A smal.
subsets [1], (21, [3], 9), [14], and [16], Reference [9 is specifically geared toward the
analysis of agovthms, Ki the firs volume of «three-volume senes that will be eted
‘hroughout this text. More advanced matenal is covered in (6
‘Throughout this book, we wll assme a knowledge of C+. For dhe most pan, [15]
{describes the nal draft standard of C+#11, and, boing writen by the orginal designer of
(Cet, remains the mos authontative, Another standard reference i [10]- Advanced topes
fin C++ are discussed sn [5]. The two-part sees (11, 12] gies a great discussion of the
‘many pals in C++, The Sndard Template Library which we wil nvesigae throughout
this text, is decribed in (131. The material in Secuons 14-17 is meant to serve as an
‘overview of the features that we wil use in this text We also assume familiarity with
Pointers and recursion (the reason summary in this chapter is meant 10 be a quick.
feview), We wil tempt to provide ints on their use where appropiate throughout the
textbook, Readers not familiar wth these should consult (17) or any good imermediate
programming texto.
‘General programming syle discussed in several books. Some ofthe classics ae [4
Triana (81
1. M0. Alberton and JP Hutchinson, Disete Mathematics ih Algorids, John Wiley Se
Sons, NewYork, 1988,
2. Z Base, Math Companion for Computer Scene, Reston Publishing Co Reston, Vi, 1982,
3. R.A, Brun, rahcoryCombinors, Sth ed, Pearson, Boson, Mass, 2008.
4. Dita, A Discipline of Prgranmng, Pence Hall, Englewood Clis, NJ, 1976.
5B. Eke, Thinking n C+, 2d, Prentice Hal, Englewood Chis NJ, 2002.
© RL Graham, D.€, Knuth, and O. Paahni, Corte Mathematics, Addison-Wesley
Reading. Mast 198,
1. Gries, The Scene of Pogramming,Springe Yering New Yor, 1981
1
|
Petree,
'B.W Kernighan and P J. Pauger, The Elements ofPrograning Sve, 28 el, MeGraw-Hl
New York 1978,
D.E.Kinuth, The rt of Compuer Programing, Vl I: Fundamental Algrins, 34 ed
‘Addison ese, Reaing, Mess, 1997
SB. Lippman, | Lajl and BE Moo, CH Pune, Sth ed, Pearson, Boson, Mass, 2013,
§ Moyes 30 pac Hos pve Pron and Ds, 3. An ee,
exon, Mas, 2005,
5. Meyers, Mae fective Cr 35 New Ws to Inprve Your Programs and Ces, Addison.
‘Wesley, Reading, Mass, 1996,
DR Musser, G J Durge, and A. Sa, STL Tuoi ond Reference Gude CH Progaming
with he Stand Template Lira, 2d ed, Addon. Wesley, Reading Mase, 2001
FS. Robens and B.Tesman, Applied Cambinators, 24 ed, Prentice Hal, Englewood Chis,
NJ. 2003,
BStroustep, The C++ Programming Language, 4th ed, Peateon, Boson, Mis, 2013
‘A. Tucker, Applied Cmbistorc, the, john Wiky& Sos, New Yrs, 2012.
M.A, Wes, lgonms, Data Stracares, and Problem Sing with C¥, 2a ed, Adon
Wesley. Reding, Mass, 2000
o