Eric Roberts CS 106B February 11 2013 Contest Results The CS106B Random Writer Contest February 2013 Honorable Mention Brad Girardeau WordBased Tom Sawyer Honorable Mention Alexander Hsu Hamlet with Semantics ID: 182521
Download Presentation The PPT/PDF document "Template Structures" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Template Structures
Eric Roberts
CS 106B
February 11, 2013Slide2
Contest Results
The CS106B
Random Writer Contest
February 2013
Honorable Mention: Brad Girardeau (Word-Based Tom Sawyer)
Honorable Mention: Alexander Hsu (Hamlet with Semantics)
Honorable Mention: Alan
Kaptanoglu
(Paradise Lost)
Honorable Mention: Annette
Mullaney
(Sky High) Slide3
Shakespearean Sonnets
Awakes my heart; So true a fool is love,
thus shall excuse my jade,— A crow that flies
in heaven’s sweetest air. So shall I live,
as a dream. When wasteful war shall statues
overturn, And darkly bright, are themselves
as stone, Unmoved, cold, and times of
your memory. ’Gainst death, and lusty leaves quite gone, But when my glass shows me myself indeed
Beated and chopp’d with tanned antiquity, Mine eye my heart think that we before have heard them told. LXXVII Thy merit hath my pen,
—As ’twixt vows, and he in them I read; And
needy nothing
trimm’d
in jollity, And
sable curls, all bare, is of my speaking breast.
Runner-
Up #1
— Allan
RaventosSlide4
Winds of Democracy
And the winds of the north, from the great lakes,
and all the weapons of tyrants let loose,
but it will certainly come in use;
when the fire-flashing guns have fully alerted me,
and play with the measureless light.
Child: father what is that you express in your eyes?
It seems to me there are other men in other lands yearning and thoughtful, it seems to me if i could be content with all if i
thought them their own finale? This now is too lamentable a face for a man, and i looking up at the stars, and of each of us inevitable; each of us, for those being born.
Democracy!
Runner-
Up #2
— Tri DaoSlide5
Chicken-Heart Tom
breath would live near Tallapoosa’s
were thrust from it passed on Coosa’s
homesick that was no answer TOM dodged
for us all comb me
becuz
I never budgedfinished and then added: Poor Huck Finn’s
finally asked—dimly dreading Ben’swere thrown into secondary importancehumiliated and all this If you got your Nanceby a little by Tom lay waiting anxiety
like But at his name they turn his moietyon the cussed smothery houses Who artsaid go out of himself —chicken-heart
Runner-
Up #3
— Tommy TruongSlide6
Bob Dylan’s Random Writer Blues
F
Em/b
Well, he peak of the sun ’cause tonight
Dm F
an’ we gazed upon the road,
C Ammake promised that seaport town
C Fcalled on me to youF Em/bwith a pain that
i could not feel so sad.Dm Fdead man,C Amwhen
i’m
all alone one nights;
C F
forty-one days, all
i
gotta take a change possessed F Cby no special all rightG A
and cast off like crossin’ the bay of mexicoC Em/b
fanning to do whatever young,G Dforever you gotta do is survive,
F Em/bWell, he’s a weird monkey, very funky.
Dm F
i
said for his age, he’s wild
C Am
my only prayer for him in the children
C F
who could give,
F
Em/b
we walked together,
Dm F
we’ll climb that hill no matter what gets in the dark does die
C Am
as the monks
C F
the
c.i.o
.
F C
by no special all right
G A
and cast off like crossin’ the bay of mexicoC Em/bfanning to do whatever young,G Dforever you gotta do is survive, F Em/bWell, tell me no lies.Dm Fare you one questions burning of the hangin’ on the bowery slumsC Amto those clothes and you’ll come baby, here’s too many booksC Fshe gone with a golden rule.F Em/byou always rightDm Fon a night longC Amlistenin’ for the wheel, took off her when he said, "that’s mine."C Fjoey, joey, F Cby no special all rightG Aand cast off like crossin’ the bay of mexicoC Em/bfanning to do whatever young,G Dforever you gotta do is survive
First Place
— Jack MarisSlide7
Midterm Histogram
N
=
388
Median = 53.0/60Mean = 50.3/60
59–60
55–58
53–5451–5247–50
44–4641–4337–4034–36
25–33
00–24
A+
A
A–
B+
BB–C+
CC–DNP
64
109
35
33
44
27
19
16
10
23
8Slide8
Templates
One of the most powerful features in C++ is the template facility, which makes it possible to define functions and classes that work for a variety of types
.
template <typename
placeholder
>
where
placeholder
is an identifier that is used to stand for a specific type when the definition following the template specification is compiled.
The
most common form of a template specification isSlide9
Templates in Functions
Templates can be used before a function definition to create a generic collection of functions that can be applied to values of various types
.
The compiler will generate the code for many different versions of
max
, one for each type that the client uses.
The function max can be used only with types that implement the
> operator. If you call max on some type that doesn’t
, the compiler will signal an error.
template <
typename
ValueType
>
ValueType
max(ValueType v1, ValueType v2) {
return (v1 > v2) ? v1 : v2;}
The
following code, for example, creates a template for
the
max
function, which returns the larger of its two arguments: Slide10
Exercise: Rewrite
sort
as a Template
Rewrite the following code so that it sorts any type that implements the
< operator:
void
s
ort(int
array[], int n) {
for
(
int
lh = 0; lh
< n; lh+
+) { int
rh = lh;
for
(
int
i
=
lh
+
1;
i
<
n
;
i
+
+) {
if (array[i] < array[rh]) rh = i; } swap(array[lh], array[rh]); }}void swap(int & x, int & y) { int tmp = x; x = y; y
= tmp;}Slide11
Templates in Class Definitions
Templates are more commonly used to define generic classes. When they are used in this way, the
template
keyword must appear before the class definition and before each of the implementations of the member functions.
The most inconvenient aspect of using templates to create generic classes is that the compiler cannot process them correctly unless it has access to both the interface and the implementation at the same time. The effect of this restriction is that the .
h files for template classes must contain
both the prototypes and the corresponding code.To emphasize the conceptual separation between the interface and the associated implementation,
you should make sure to include an appropriate comment before the private section and the implementation warning casual clients away from the details.Slide12
A Template Version of the
Stack
ClassThe first step in writing the template version of the Stack class is to add the template keyword to the interface just before the class definition:
template <
typename
ValueType>
class
Stack
{
. . .
body of the class
. . .
};
Once you have made this change, each instance of the specific type (formerly
char in the
CharStack
class) must be replaced by the
ValueType
placeholder for the generic type, as in
ValueType
*elements;
or
void
push(ValueType
value);Slide13
Implementing the Template Class
The final change necessary to implement the template class is to add
template
declarations to
every method body, as in the following updated version of the constructor:
template <
typename
ValueType>
Stack<ValueType>::Stack(
) {
capacity = INITIAL_CAPACITY;
count = 0;
elements =
new ValueType[
capacity];}
Because of the restrictions that C++ imposes on template types, the implementations of the methods need to be included as part of the
stack.h header.Slide14
Assignment and Copy Constructors
There is one remaining issue about creating new abstract classes that is extremely important in practice, which is how such objects behave if you copy them using assignment or by passing them by value to parameters in methods.
The
crux of the problem is that copying an abstract data object typically needs to copy the underlying data and not just the fields directly accessible in the object. Unfortunately, the default interpretation in C++ is to copy only the top-level fields, which can lead to serious errors
.
Even though the text includes an extensive discussion of the issues surrounding assignment and copy constructors, we won’t hold you responsible for these topics in CS106B. If, however, you are applying for a job that requires you to use C++, you absolutely need to review this material.Slide15
Shallow
vs.
Deep Copying
Suppose that you have
a Stack<int> containing three elements as shown in the diagram to the right.A
shallow copy allocates new fields for the object itself and copies the information from the original. Unfortunately, the dynamic array is copied as an address, not the data.
A deep copy also copies the contents of the dynamic array and therefore creates two independent structures
elements
1000
capacity
100
count
3
10
20
30
1000
.
.
.
elements
1000
capacity
100
count
3
elements
2000
capacity
100
count
3
10
20
30
2000
.
.
.Slide16
Implementing Deep Copy Semantics
When you are defining a new abstract data type in C++, you typically need to define two methods to ensure that copies are handled correctly:
The operator
operator=
, which takes care of assignmentA copy constructor
, which takes care of by-value parameters
These methods have well-defined signatures and structures, and the easiest thing to do is simply to copy the code on the next slide, adapting it as necessary to account for the specific instance variables that need to be copied in the underlying representation.Slide17
/* Code to support deep copying for the
Stack class
*/
template <
typename
ValueType>
Stack<ValueType>::Stack(const
Stack & src) {
deepCopy(src);}
template <
typename
ValueType
>
Stack<ValueType> & Stack<
ValueType>::operator=(const Stack & src) { if (this != &
src) { if (elements != NULL) delete[] elements;
deepCopy(src); }
return *this;
}
template <
typename
ValueType
>
void Stack<
ValueType
>::
deepCopy(const
Stack &
src
) {
count = capacity =
src.count
;
elements = (capacity == 0) ? NULL : new
ValueType[capacity
];
for (
int
i = 0; i < count; i++) { elements[i] = src.elements[i]; }}Code to Implement Deep CopyingSlide18
The End