150 Chapter 9 T emplates and Con tainers Define The - - PDF document

150 chapter 9 t emplates and con tainers define the
SMART_READER_LITE
LIVE PREVIEW

150 Chapter 9 T emplates and Con tainers Define The - - PDF document

150 Chapter 9 T emplates and Con tainers Define The template mec hanism in C is p erhaps one of the more complex features of the language ++ A that has no corresp ondence in Ja v a. T emplates allo w class


slide-1
SLIDE 1 150
slide-2
SLIDE 2 Chapter 9 T emplates and Con tainers The template mec hanism in C ++ is p erhaps
  • ne
  • f
the more complex features
  • f
the language Define A template al lows a class
  • r
function to b e p ar ameter- ize d by a typ e that has no corresp
  • ndence
in Ja v a. T emplates allo w class denitions
  • r
functions to b e parameterized b y t yp es
  • r
v alues, in m uc h the same w a y that a function denition can b e executed with a v ariet y
  • f
dieren t v alues. The template mec hanism is p erformed at compile time, and p ermits a great deal
  • f
t yp e c hec king to b e p erformed statically , and eliminates man y
  • f
the run-time casts that t ypically p
  • pulate
Ja v a programs (and consume Ja v a execution time). A ma jor use
  • f
templates is as a to
  • l
to dev elop a ric h set
  • f
data structure,
  • r
con tainer abstractions. In this c hapter w e will rst explain the template mec hanism, con trasting it with v arious dieren t tec hniques in Ja v a. The c hapter will then conclude with a description
  • f
the Standard T emplate Library ,
  • r
STL. The STL is the ma jor data structure library used b y C ++ programs. 9.1 T emplate Classes T emplate classes are p erhaps b est explained using an example. Consider the follo wing de- nition, whic h is a generalization
  • f
the b
  • x
data structure w e dev elop ed in earlier c hapters: template <class T> class box f public: box ( ) f g box (T v) : val(v) f g box (box<T> & right) : val(right.val) f g T value() f return val; g 151
slide-3
SLIDE 3 152 CHAPTER 9. TEMPLA TES AND CONT AINERS void
  • perator
= (T right) f val = right; g void
  • perator
= (box<T> & right) f val=right.val; g private: T val; g; The new b
  • x
is a template class. That means that the t yp e b
  • x
itself is incomplete, it cannot b y itself b e used to create instances. Instead, the parameter (T, in this case) m ust b e lled in with a sp ecic t yp e b efore an instance can b e created. A class template giv es the programmer the abilit y to dene a data t yp e in whic h some t yp e information is purp
  • sely
left unsp ecied, to b e lled in at a later time. One w a y to think
  • f
this is that the class denition has b een parameterized in a manner similar to a pro cedure
  • r
function. Just as sev eral dieren t calls
  • n
the same function can all pass dieren t argumen t v alues through the parameter list, dieren t instan tiations
  • f
a parameterized class can ll in the t yp e information in dieren t w a ys. Within the class b
  • dy
the v ariable T can b e used as a t yp e name. Th us, w e can declare v ariables
  • f
t yp e T, ha v e functions that return a T v alue, and so
  • n.
(Note that T is simply an iden tier, and that an y
  • ther
iden tier name could ha v e b een used.) T
  • create
an
  • b
ject w e m ust rst sp ecify a v alue for T. F
  • r
example, the follo wing creates a b
  • x
that will hold an in teger, and a b
  • x
that will hold a double precision v alue: box<int> ib; box<double> db; ib = 7; db = 3.14; box<int> ibtwo = 4; // can b e initialized in constructor ib = ibtwo; int x = ib.value(); The t yp es asso ciated with template classes are scrupulously c hec k ed at compile time. An attempt to use a v alue incorrectly will result in a compile time error: ib = 2.7; // error
  • cannot
assign real to in t Probably the most common use for template classes, although b y no means the
  • nly
  • ne,
is to create con tainer classes. The STL, describ ed in Section 9.3, is
  • ne
suc h collection
  • f
classes. F
  • r
example, the list data structure represen ts the abstraction
  • f
a link ed list, but do es not itself sp ecify the particular t yp e
  • f
elemen ts it will con tain. Instead, the elemen t t yp e is sp ecied b y a template parameter: list<int> ilist; // create a list
  • f
in tegers
slide-4
SLIDE 4 9.1. TEMPLA TE CLASSES 153 list<double> dlist: // create a list
  • f
real n um b ers list<Animal > alist; // create a list
  • f
p
  • in
ters to animals ilist.push front(7); // add an elemen t to fron t
  • f
list int x = ilist.front(); // extract rst elemen t from list Con trast this with the w a y collections are implemen ted in Ja v a. In Ja v a, the v alues held b y a collection class are stored in v ariables declared as Object. There are t w
  • ma
jor problems with the Ja v a approac h: 1. It means that non
  • b
ject v alues, suc h as primitiv e t yp es (in teger and the lik e) cannot b e stored in Ja v a collections. This is the ma jor reason the Ja v a language pro vides wrapp er classes, suc h as Integer. 2. It means that when a v alue is remo v ed from a Ja v a collection, it m ust b e cast bac k to the appropriate t yp e. Notice that there are no cast
  • p
erations in the ab
  • v
e example. When w e remo v e an elemen t from the list ilist, the compiler kno ws already that it is an in teger, and not a double
  • r
an animal
  • r
an y
  • ther
sort
  • f
v alue. By using templates, the language allo ws truly reusable, general-purp
  • se
comp
  • nen
ts to b e created and manipulated with a minim um
  • f
dicult y and y et still retain t yp e safet y , whic h is an imp
  • rtan
t goal
  • f
strongly t yp ed languages. On the
  • ther
hand, Ja v a can easily main tain heterogeneous collections, that is, collections
  • f
v alues
  • f
v arious dieren t t yp es. Suc h collections are more dicult to represen t in C ++ . The k eyw
  • rd
class in the template parameter list is somewhat misleading, since the v alue can b e an y t yp e quan tit y , not simply a class v alue. (The sligh tly more descriptiv e k eyw
  • rd
Note The keywor d t yp e- name is a r e- c ent addition to the C ++ language t yp ename can b e used instead
  • f
class, ho w ev er this is a recen t c hange to C ++ and as y et not supp
  • rted
b y man y compilers). F
  • r
example, w e created b
  • x
v alues using the int t yp e as a template parameter, whic h is not a class t yp e. Other primitiv e v alues can also b e used as template parameters. F
  • r
example, the follo wing creates a bit arra y with a giv en n um b er
  • f
bit v alues. template <int s> class bitSet f public: set (int index) f ... g test (int index) f ... g void
  • perator
= (bitSet<s> & right); protected: // assume 16 bits p er w
  • rd
int data [ (s + 15)/ 16 ];
slide-5
SLIDE 5 154 CHAPTER 9. TEMPLA TES AND CONT AINERS g; T
  • manipulate
a bit arra y w e simply ll the template argumen t v alue with an in teger quan tit y: bitSet<25> a; a.set(17); // set p
  • sition
17 if (a.test(i)) ... A bit arra y can b e assigned to another bit arra y
  • f
the same size, but not to an arra y with a smaller n um b er
  • f
v alues: bitSet<25> b; bitSet<30> c; a = b; //
  • k,
will execute assignmen t
  • p
erator a = c; // pro duces compile time error, sizes don't matc h 9.1.1 T emplate Metho ds When template metho ds are written separately from the class denition, they m ust also b e b e parameterized b y the template argumen t: template <int s> void bitSet<s>::operat
  • r
= (bitSet<s> & right) f // rst compute the data v ector size int max = (s + 15) / 16; // then cop y all the data elds in to
  • ur
arra y for (int i = 0; i < max; i++) data[i] = right.data[i]; g Notice that the class name bitSet has b een qualied b y the template argumen t s. This is not simply a metho d in class bitSet, but is a metho d in bitSet<s>. 9.2 T emplate F unctions In addition to classes,
  • rdinary
functions can also b e giv en template denitions. A simple example is the follo wing, whic h is a function to determine the maxim um
  • f
t w
  • quan
tities:
slide-6
SLIDE 6 9.2. TEMPLA TE FUNCTIONS 155 template <class T> T max (T left, T right) f // return largest v alue if (left < right) return right; else return left; g The function max can b e used with an y data t yp e that implemen ts the <
  • p
erator. Since the <
  • p
erator can b e
  • v
erloaded for user dened data t yp es, this is p
  • ten
tially an innite Note T emplate function typ es wil l b e inferr e d fr
  • m
the ar gument values, and ne e d not b e sp e cie d by the pr
  • gr
am- mer set
  • f
p
  • ssibilities.
int i = max(3, 4); double d = max(3.14, 4.7); // assume comparison has b een dened for class anOb ject AnObject a, b; AnObject c = max(a, b); // mixing t yp es will not w
  • rk
int i = max(2, a); // will pro duce compiler error A feature to note is that it is not necessary to explicitly declare the t yp es that will b e used with an in v
  • cation
  • f
a template function, as it is with template classes. Instead, the necessary t yp es are inferr e d from the t yp es giv en b y the argumen ts. If a single unam biguous meaning is not p
  • ssible,
as in the last statemen t sho wn ab
  • v
e, then the compiler will pro duce an error message. T emplate functions are not expanded un til they are used, at whic h p
  • in
t an instance
  • f
W arning Err
  • rs
in template functions ar e
  • ften
dicult to tr ac e b ack to the
  • rigi-
nating state- ment the function with the correct argumen t t yp es will b e created. Often template functions
  • p-
erate b y using
  • ther
template functions, and so
  • n
man y lev els deep. An error, for example, using argumen t v alues that do not supp
  • rt
all the necessary
  • p
erations (for instance, using max with argumen ts that do not recognize the <
  • p
erator), will b e rep
  • rted
is relation to the expanded template function, not in reference to the function in v
  • cation
that caused the template to b e expanded. Because
  • f
this, an error in a template function ma y b e v ery dicult to trace bac k to the
  • riginating
statemen t.
slide-7
SLIDE 7 156 CHAPTER 9. TEMPLA TES AND CONT AINERS 9.3 The Standard T emplate Library The Standard T emplate Library ,
  • r
STL, is a collection
  • f
useful con tainer classes for com- mon data structures, suc h as lists and stac ks. It includes the follo wing: v ector Resizeable arra y list Link ed list deque Double ended v ector set and m ultiset Ordered set map and m ultimap Key ed dictionary stac k last-in, rst
  • ut
collection queue rst-in, rst
  • ut
collection priorit y queue
  • rdered
access collection Manipulation
  • f
the con tainers is facilitated b y a to
  • l
called an iterator. An iterator is a generaization
  • f
a memory p
  • in
ter, used to access elemen ts in a con tainer without kno wledge
  • f
the in ternal represen tation for the con tainer, similar to the class Enumeration in Ja v a. Finally , the STL is unique in pro viding a large collection
  • f
generic algorithms, whic h are functions manipulated b y means
  • f
iterators, not tied to an y single con tainer. Eac h
  • f
these features will b e describ ed in the sections that follo w. 9.3.1 Con tainers Space do es not p ermit a complete exp
  • sition
  • f
all the STL classes, instead in this section w e will simply con trast those con tainers whic h are most closely similar to the standard con tainers in Ja v a, and
  • utline
the ma jor areas
  • f
dierence. V ectors Lik e the Ja v a V ecto r data t yp e, the class vecto r (note lo w er case v) represen ts a dynamically W arning The ve ctor data typ e has lower c ase v, un- like the V e c- tor data typ e in Java resizable arra y . Unlik e the Ja v a class, the C ++ class m ust b e pro vided with a template parameter that describ es the elemen t t yp e: vector<int> a; vector<double> b(10); // initially ten elemen ts Note that data structures are generally declared as
  • rdinary
v ariables. It is not necessary to allo cate a con tainer class using the new
  • p
erator except in sp ecial circumstances, suc h as when the con tainer m ust
  • utliv
e the con text in whic h it is declared. Figure 9.1 compares metho ds in the vecto r data t yp e to the Ja v a equiv alen ts. The C ++ class pro vides a v ariet y
  • f
dieren t constructors, including
  • nes
that set the initial size, and a constructor that sets the initial size and pro vides a default initial v alue. Elemen t access and mo dication in the C ++ v ersion is b
  • th
pro vided b y the subscript
  • p
erator, whereas
slide-8
SLIDE 8 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 157
  • p
eration C++ Java equivalent Creation v ector<T> v; v = new V ector(); v ector<T> v(in t size); v ector<T> v(size, initial v alue); v ector<T> v(oldv ector); Elemen t access v[index] elemen tA t(index) First elemen t fron t() rstElemen t() Last elemen t bac k() lastElemen t() size size() size() empt y test empt y() isEmpt y() set size resize(newsize) setSize(newsize) capacit y capacit y() capacit y() set capacit y reserv e(newsize) ensureCapacit y(newsize) add to fron t push fron t(v alue) insertElemen tA t(v alue, 0) add to bac k push bac k(v alue) addElemen t(v alue) insert at p
  • sition
insert(iterator, v alue) insertElemen tA t(v alue, p
  • sition)
c hange at p
  • sition
v[p
  • sition]
= v alue setElemen tA t(v alue, p
  • sition)
Remo v e last elemen t p
  • p
bac k() none Remo v e from p
  • sition
erase(iterator) remo v eElemen tA t(p
  • sition)
cop y v ector<T> v(oldv ector); clone() create iterator b egin() elemen ts() end() Figure 9.1: Comparison
  • f
v ector metho ds
slide-9
SLIDE 9 158 CHAPTER 9. TEMPLA TES AND CONT AINERS Ja v a uses t w
  • dieren
t metho ds for these t w
  • activities.
In the metho ds that refer to an in ternal p
  • sition
within the v ector the Ja v a metho ds generally use an in teger index, while the C ++ v ersions use an iterator v alue (see Section 9.3.2). A cop y ,
  • r
clone, is formed in Ja v a using an explicit metho d, while in C ++ the same action is p erformed using a cop y constructor. One imp
  • rtan
t dierence b et w een the Ja v a abstraction and the C ++ v ersion is that attempting to access an elemen t that is
  • ut
  • f
range will alw a ys raise an exception in Ja v a, W arning Like arr ays and strings, ve c- tors do not che ck for
  • ut
  • f
r ange in- dex values ho w ev er the C ++ data abstraction p erforms no run-time c hec ks. It is p
  • ssible
that an
  • ut
  • f
range index v alue w
  • uld
not b e detected, and garbage v alues w
  • uld
b e returned
  • n
access,
  • r
an unkno wn lo cation mo died
  • n
elemen t set. An alternativ e metho d, at, do es p erform a run-time range c hec k, and generates a sf
  • ut
  • f
range error for illegal index v alues. The Ja v a class pro vides a metho d (contains) that can b e used to determine whether
  • r
not a sp ecic v alue is held b y the con tainer, and another (removeElement(val)) to remo v e an elemen t b y giving its v alue, rather than p
  • sition.
The C ++ v ersion has no similar metho ds, although
  • ne
  • f
the generic algorithms (see Section 9.3.3) can b e used for this purp
  • se.
If this
  • p
eration is common, the set data abstraction is a preferable alternativ e to using a v ector. Link ed list The list pro v es most
  • f
the same features as the vecto r data t yp e, adding metho ds that allo w insertions and remo v als from the fron t
  • f
the con tainer, as w ell as from the bac k. In addition, insertions
  • r
remo v als from the middle are p erformed in constan t time, rather than the O (n) time required b y the v ector data t yp e. a list link link link link ?
  • Deque
The deque is an in teresting data abstraction, that can b e though t
  • f
as a pair
  • f
v ectors placed bac k to bac k, mo ving in
  • pp
  • site
directions. This arrangemen t p ermits ecien t (constan t time) insertion to either end, ho w ev er slo w er linear insertion in to the middle. Ho w ev er, the deque is a more space ecien t structure than is a list.
slide-10
SLIDE 10 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 159 Set The set data t yp e main tains elemen ts in
  • rder,
and thereb y p ermits v ery ecien t (that is, Note While a set in mathemat- ics do es not im- ply
  • r
der, the set data typ e maintains its values in
  • r-
der logarithmic) time insertion, remo v al, and inclusion test for v alues. In ternally , it is imple- men ted b y a balanced binary tree.
  • A
A U
  • A
A U
  • A
A U
  • @
@ R Map A map is a k ey/v alue structure, similar to the Ja v a Dictiona ry
  • r
Hashtable data t yp es. The Define A map is an in- dexe d c
  • l
le c- tion, similar to the Java Dictionary map data t yp e is parameterized b y t w
  • template
argumen ts,
  • ne
for the k ey t yp e and a second for the v alue t yp e. Op erations
  • n
maps are implemen ted using a data t yp e called a pair, whic h is a k ey/v alue com bination. Iterators, for example, yield pair v alues. The k ey elemen t in the pair is
  • btained
using the function rst, and the v alue eld is found using the metho d second. An
  • ptional
third argumen t (required in some C ++ compiler implemen tations) is a function
  • b
ject used to compare k ey v alues to eac h
  • ther.
(F unction
  • b
jects will b e discussed in Section 9.3.4.) The case study in graph manipulation, Chapter 15, illustrates the use
  • f
the map data t yp e. Stac k and Queue A stack is a linear structure that allo ws insertions and remo v als
  • nly
from
  • ne
end, while a queue inserts elemen ts from
  • ne
end and remo v es them from the
  • ther:
6 ?
slide-11
SLIDE 11 160 CHAPTER 9. TEMPLA TES AND CONT AINERS The stac k and queue data structures in the STL are in teresting in that they are adapters, Define A n adapter is a softwar e c
  • mp
  • nent
that changes the in- terfac e to an-
  • ther
c
  • mp
  • nent
built
  • n
top
  • f
an underlying data t yp e, suc h as a v ector
  • r
a link ed list. The template argumen t used in the constructor sp ecies the underlying con tainer: stack< vector<int> > stackOne; stack< list<anObject > > stackTwo; queue< deque<double> > queueOne; Note the separating space b et w een the t w
  • righ
t angle brac k ets, man y C ++ compilers will rep
  • rt
spurious compiler errors if the space is
  • mitted
(confusing the angle brac k ets for the righ t shift
  • p
erator). The metho d names for the stack abstraction are similar to those used b y the Ja v a Stack class. Priorit y Queue The priorit y queue data t yp e pro vides rapid access to the largest elemen t in a collection, and rapid remo v al
  • f
this elemen t. Lik e the stac k, it is built as an adaptor
  • n
top
  • f
another con tainer, t ypically a v ector
  • r
a list. Tw
  • template
argumen ts are used with a priorit y queue. The rst is the underlying con tainer, while the second is a function
  • b
ject that is used to compare elemen ts. 9.3.2 Iterators The concept
  • f
an iterator in the STL is similar in purp
  • se
to the idea
  • f
an Enumeration in Ja v a, but diers in the particulars
  • f
use. This is p erhaps b est illustrated b y an example. Imagine that v is a v ector
  • f
in teger v alues. W e could compute the sum
  • f
the v alues in Ja v a using the follo wing co de fragmen t: int sum = 0; for (Enumeration e = v.elements(); e.hasMoreElement s( ); ) f Object val = e.nextElement(); Integer iv = (Integer) val; sum += iv.intValue(); g The same idea w
  • uld
b e written using iterators as follo ws: int sum = 0; vector<int>::iter at
  • r
start = v.begin(); vector<int>::iter at
  • r
stop = v.end(); for ( ; start != stop; ++start) sum += start;
slide-12
SLIDE 12 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 161 Sev eral dierences should b e noted. Because the STL con tainers use template denitions, it is not necessary to cast the
  • b
ject to the prop er t yp e after it is remo v ed from the con tainer. The template prop ert y
  • f
the STL also means that con tainers can store primitiv e t yp es, suc h as in tegers, and do not need the wrapp er classes necessitated b y the Ja v a v ersion. A dieren t iterator data t yp e is pro vided b y eac h con tainer, th us to create an iterator it is necessary to rst sp ecify the con tainer t yp e. Most imp
  • rtan
tly , while en umerations w
  • rk
as a single v alue, iterators m ust alw a ys b e manipulated in pairs, using a b eginning and an ending iterator. One w a y to understand iterators is to note that they are designed to b e equiv alen t, and compatible, with con v en tional p
  • in
ters. Just as p
  • in
ters can b e used in a v ariet y
  • f
w a ys in traditional programming, iterators are also used for a n um b er
  • f
dieren t purp
  • ses.
An iterator can b e used to denote a sp ecic v alue, just as a p
  • in
ter can b e used to reference a sp ecic memory lo cation. On the
  • ther
hand, a p air
  • f
iterators can b e used to describ e a r ange
  • f
v alues, in a manner analogous to the w a y in whic h t w
  • p
  • in
ters can b e used to describ e a con tiguous region
  • f
memory . Imagine, for example, an arra y that is b eing used to represen t a dec k
  • f
pla ying cards. Tw
  • p
  • in
ter v alues can b e used to denote the b eginning and ending
  • f
the dec k: ca rd[0] ca rd[1] ca rd[2] ... ca rd[50] ca rd[51] # # # # # # ca rds ca rds+1 ca rds+2 ca rds+50 ca rds+51 ca rds+52 If w e need to represen t the b eginning and end
  • f
the memory space, w e can use the v alues ca rds and ca rds+52. In the case
  • f
iterators, ho w ev er, the v alues b eing describ ed are not necessarily ph ysically in sequence, but rather are logically in sequence, b ecause they are deriv ed from the same con tainer, and the second follo ws the rst in the
  • rder
elemen ts are main tained b y the collection.
slide-13
SLIDE 13 162 CHAPTER 9. TEMPLA TES AND CONT AINERS A A A A A A U
  • *
@ @ @ @ @ I
  • ?
  • The
con v en tion used b y the con tainer classes in the standard library is to return, in resp
  • nse
to the mem b er function named b egin(), an iterator that accesses the rst elemen t in the collection. An iterator denoting the end
  • f
the collection is yielded b y the mem b er function end(). Con v en tional p
  • in
ters can sometimes b e nul l, that is, they p
  • in
t at nothing. Iterators, as w ell, can fail to denote an y sp ecic v alue. Just as it is a logical error to dereference and use a n ull p
  • in
ter, it is an error to dereference and use an iterator that is not denoting a v alue. When t w
  • p
  • in
ters that describ e a region in memory are used in a C ++ program, it is Note Iter- a- tors pr
  • duc
e d by c
  • ntainers
  • ften
c
  • me
in p airs. The b e ginning it- er ator is r e- turne d by the function b e- gin, the ending it- er ator by the function end con v en tional that the ending p
  • in
ter is not considered to b e part
  • f
the region. W e see this in the picture
  • f
the ca rds arra y , where the arra y is describ ed as extending from ca rds to ca rds+52, ev en though the elemen t at ca rds+52 is not part
  • f
the arra y . Instead, the p
  • in
ter v alue ca rds+52 is the p ast-the-end v alue { the elemen t that is the next v alue after the end
  • f
the range b eing describ ed. Iterators are used to describ e a range in the same manner. The second v alue is not considered to b e part
  • f
the range b eing denoted. Instead, the second v alue is a p ast-the-end elemen t, describing the next v alue in sequence after the nal v alue
  • f
the range. Sometimes, as with p
  • in
ters to memory , this will b e an actual v alue in the con tainer. Other times it ma y b e a sp ecial v alue, sp ecically constructed for the purp
  • se.
The v alue returned b y the mem b er function end() is usually
  • f
the latter t yp e, b eing a sp ecial v alue that do es not refer to an y elemen t in the collection. In either case, it is nev er legal to try to dereference an iterator that is b eing used to sp ecify the end
  • f
a range. (An iterator that do es not denote a lo cation, suc h as an end-of-range iterator, is
  • ften
called an invalid iterator). An examination
  • f
a t ypical algorithm will help illustrate ho w iterators are used. The generic function named nd() can b e used to determine whether
  • r
not a v alue
  • ccurs
in a collection. It is implemen ted as follo ws:
slide-14
SLIDE 14 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 163 template <class iterator, class T> iterator find (iterator first, iterator last, T & value) f while (first != last && first != value) ++first; return first; g The follo wing sho ws ho w w e could use this algorithm to searc h for a v alue b eing held b y a con v en tional C ++ arra y: int data[100]; ... int
  • where
= find(data, data+100, 7); Alternativ ely , the follo wing declares a new v ariable, then searc hes for the v alue 7 in a list
  • f
in tegers, assigning the resulting iterator to the v ariable: list<int>::iterat
  • r
where = find(aList.begin () , aList.end(), 7); The resulting v alue is either the end-of-list iterator (equal to the v alue returned b y the function end())
  • r
it represen ts the lo cation
  • f
the rst 7 in the list. As with con v en tional p
  • in
ters, the fundamen tal
  • p
eration used to mo dify an iterator W arning When use d as p airs, the se c
  • nd
iter a- tor must al- ways b e r e ach- able fr
  • m
the rst is the incremen t
  • p
erator (op erator ++). When the incremen t
  • p
erator is applied to an iterator that denotes the nal v alue in a sequence, it will b e c hanged to the \past the end" v alue. An iterator j is said to b e r e achable from an iterator i if, after a nite sequence
  • f
applications
  • f
the expression ++i, the iterator i b ecomes equal to j. Ranges can b e used to describ e the en tire con ten ts
  • f
a con tainer, b y constructing an iterator to the initial elemen t and a sp ecial \ending" iterator. Ranges can also b e used to describ e subsequences within a single con tainer, b y emplo ying t w
  • iterators
to sp ecic v alues. Whenev er t w
  • iterators
are used to describ e a range it is assumed, but not v eried, that the second iterator is reac hable from the rst. Errors can
  • ccur
if this exp ectation is not satised. The nd() algorithm illustrates three requiremen ts for an iterator:
  • An
iterator can b e compared for equalit y to another iterator. They are equal when they p
  • in
t to the same p
  • sition,
and are
  • therwise
not equal.
  • An
iterator can b e dereferenced using the
  • p
erator, to
  • btain
the v alue b eing de- noted b y the iterator. Dep ending up
  • n
the t yp e
  • f
iterator and v ariet y
  • f
underlying con tainer, this v alue can also sometimes b e used as the target
  • f
an assignmen t in
  • rder
to c hange the v alue b eing held b y the con tainer.
slide-15
SLIDE 15 164 CHAPTER 9. TEMPLA TES AND CONT AINERS
  • An
iterator can b e incremen ted, so that it refers to the next elemen t in sequence, using the
  • p
erator ++. What mak es iterators p
  • ssible
is the fact that these c haracteristics can all b e pro vided with new meanings in a C ++ program, since the b eha vior
  • f
the giv en functions can all b e mo died b y
  • verlo
ading the appropriate
  • p
erators (see Chapter 7). There are t w
  • ma
jor categories
  • f
iterator constructed b y the con tainers in the stan- dard library . The t yp es list, set and map pro duce bi-dir e ctional iterators. These iterators recognize the incremen t and decremen t
  • p
erators (the latter mo ving the iterator b ackwar ds
  • ne
elemen t), but cannot b e randomly accessed. The t yp es vecto r, string and deque,
  • n
the
  • ther
hand, generate r andom-ac c ess iterators, whic h p ermit the subscript
  • p
erator and the addition
  • f
in teger v alues to an iterator (analogous to adding an in teger v alue to a p
  • in
ter, as with the expression ca rds+52). Some
  • f
the generic algorithms dep end up
  • n
this subscripting abilit y , and therefore cannot b e used with lists
  • r
sets. 9.3.3 Generic Algorithms One
  • f
the most in teresting features
  • f
the STL is the separation b et w een the con tainer Define A generic algo- rithm is a softwar e al- gorithm that c an b e use d with many dier- ent c
  • l
le ction classes abstractions themselv es and algorithms that can b e used with the con tainers. By separating the t w
  • and
pro viding a ric h collection
  • f
algorithms that w
  • rk
  • nly
through iterators, the same algorithms can b e used with a v ariet y
  • f
dieren t con tainers,
  • r
indeed with normal arra ys and regular memory p
  • in
ters. These functions are termed generic algorithms, since they are generic to a wide v ariet y
  • f
uses. Once again, the template mec hanism is the k ey to sp ecializing the generic algorithm for use in an y particular situation. W e sa w
  • ne
example generic algorithm in the nd pro cedure describ ed earlier. This algorithm p erforms a linear searc h to lo cate a v alue within a collection. Other algorithms are used to initialize the elemen ts in a con tainer, to p erform a v ariet y
  • f
dieren t searc hes, to transform the v alues in a con tainer in place, to remo v e elemen ts,
  • r
to reduce a collection to a single v alue. An example algorithm that pro duces an in-place transformation is the function ran- dom shue. This randomly rearranges the v alues in the collection. Using this, w e could randomly sh ue the card v alues describ ed earlier as follo ws: random shuffle (cards, cards+52, randomizer); The randomizer used b y this algorithm m ust b e a random n um b er generator, written in the form
  • f
a function
  • b
ject, to b e describ ed in the next section. 9.3.4 F unction Ob jects F unctions are not really rst class v alues in C ++ (or in man y
  • ther
languages, for that Define A F unction Ob- je ct is an
  • b-
je ct that c an b e use d in the fashion
  • f
a function
slide-16
SLIDE 16 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 165 matter). One cannot ha v e a v ariable that holds a function, for example 1 . Y et man y
  • f
the generic algorithms m ust b e sp ecialized b y passing a function as an argumen t. The STL gets around this little problem in an in teresting fashion. F unction in v
  • cation
is considered b y C ++ to b e just another
  • p
erator, in this case the paren thesis
  • p
erator. Lik e almost all
  • p
erators, this can b e
  • v
erloaded b y a class. Th us, the programmer can mak e an
  • bje
ct that can b e used as if it w ere a function. One example is the random n um b er generator used in the example ab
  • v
e. This could b e written as follo ws: class randomInteger f public: unsigned int
  • perator
() (unsigned int max) f // compute rand v alue b et w een and max unsigned int rval = rand(); return rval % max; g g; randomInteger randomizer; // create an instance
  • f
class The paren thesis
  • p
erator denes a \function-lik e" in terface that tak es a single in teger argumen t. Using this v alue, and a real system-pro vided random n um b er generator named rand, 2 the function computes a p
  • sitiv
e random n um b er b et w een and the maxim um v alue. Another example will further illustrate this idea. The generic algorithm nd if lo cates the rst elemen t in a collection that satises a predicate supplied b y the user. Supp
  • se
w e wish to nd the rst v alue larger than 12. W e could write a sp ecial \larger than 12" function, but let us generalize this to a \larger than x" function, where the v alue x is sp ecied when an instance
  • f
the class is created. W e can do this as follo ws: class LargerThan f public: // constructor LargerThan (int v) f val = v; g // the function call
  • p
erator bool
  • perator
() (int test) f return test > val; g private: 1 It is imp
  • rtan
t to b e precise here. One can, in C ++ , ha v e a p
  • in
ter to a function, but that is not the same as ha ving a function v alue. 2 See Section A.8 in App endix A.2 for a discussion
  • f
the standard libraries.
slide-17
SLIDE 17 166 CHAPTER 9. TEMPLA TES AND CONT AINERS int val; g; Creating an instance
  • f
LargerThan giv es us a function-lik e
  • b
ject that will test an argumen t v alue to see if it is larger than whatev er v alue w as sp ecied b y the constructor. Using this, w e could nd the rst elemen t in a list that is larger than 12 using the follo wing function in v
  • cation:
LargerThan tester(12); // create the predicate function list<int>::iterat
  • r
found = find if (aList.begin(), aList.end(), tester); if (found != aList.end()) printf("element is %d", found); // found suc h a v alue else printf("no element larger than 12"); The nd if generic algorithm tak es a collection sp ecied b y a pair
  • f
iterators, and returns an iterator that indicates the rst elemen t that matc hes the sp ecication, returning the end
  • f
range iterator is no suc h elemen t is found. By testing the result against the ending iterator w e can tell whether
  • r
not the searc h w as a success. If it w as successful, w e can dereference the resulting iterator to nd the actual v alue. If the
  • nly
use for a function
  • b
ject is as an argumen t to a generic algorithm, as in the example sho wn ab
  • v
e, then the creation
  • f
the function
  • b
ject can
  • ften
b e replaced b y the creation
  • f
a nameless temp
  • r
ary v alue. A nameless temp
  • rary
is created b y simply naming the class t yp e for the temp
  • rary
v alues along with the argumen ts to b e used in the constructor that will initialize the temp
  • rary:
LargerThan(12) // creates an instance
  • f
LargerThan The creation
  • f
this temp
  • rary
can b e p erformed directly in the argumen t list for the generic algorithm, yielding a v ery concise description: list<int>::iterat
  • r
found = find if (aList.begin(), aList.end(), LargerThan(12)); Another common use for function
  • b
jects is in the template parameter list for con tainers. F
  • r
the map and p rio rit y queue data t yp es, as w ell as
  • thers,
an
  • ptional
template argumen t describ es the algorithm to b e used in comparison b et w een elemen ts. This algorithm m ust b e describ ed as a function
  • b
ject. F
  • r
example, in Chapter 15 w e presen t a case study that uses a map to represen t a graph data t yp e. F
  • r
k eys this data t yp e uses primitiv e C ++ strings, i.e., p
  • in
ters to c haracters. Since the default implemen tation
  • f
p
  • in
ter comparison
slide-18
SLIDE 18 9.3. THE ST AND ARD TEMPLA TE LIBRAR Y 167 is not what w e wish in this case, another algorithm m ust b e dened. This is pro vided b y the follo wing class description: class charCompare f // compare t w
  • c
haracter literal v alues public: bool
  • perator
() (const char
  • left,
const char
  • right)
const f return strcmp(left, right) < 0; g g; A cha rCompa re tak es t w
  • c
haracter p
  • in
ter v alues, and compares the strings they refer- ence. Using this, the desired data t yp e is then declared as a structure that uses c haracter p
  • in
ters as k eys, holds in tegers as v alues, and uses the c harCompare function
  • b
ject to compare k ey v alues: typedef map <const char , unsigned int, charCompare> cityInfo; W
  • rking
together, con tainers, iterators, algorithms and function
  • b
jects pro vide a set
  • f
p
  • w
erful to
  • ls
that can nd use in almost an y non trivial program. T est Y
  • ur
Understanding 1. Ho w is the description
  • f
a template class dieren t from the description
  • f
a normal C ++ class? 2. Ho w is the creation
  • f
an instance
  • f
a template class dieren t from the creation
  • f
a normal C ++ v alue? 3. Using a con tainer class in Ja v a frequen tly necessitates the use
  • f
run-time casts. Ho w do es the template mec hanism eliminate the need for these casts? 4. What is a template function? Ho w are the template argumen t t yp es for a template function determined? 5. What do the initials STL stand for? 6. What are some
  • f
the w a ys that the vecto r data t yp e in C ++ diers from the V ecto r data t yp e in Ja v a? In what w a ys are they similar? 7. Wh y are the stack, queue, and p rio rit y queue data t yp es kno wn as adaptors? 8. What is a past-the-end v alue? Ho w is suc h a v alue used in an iterator lo
  • p?
slide-19
SLIDE 19 168 CHAPTER 9. TEMPLA TES AND CONT AINERS 9. What is a generic algorithm? 10. What is a function
  • b
ject? Ho w is suc h a v alue created? Ho w is it used in conjunction with generic algorithms?