Upload
phungkhue
View
219
Download
0
Embed Size (px)
Citation preview
1@Feng HU, 2016@Feng HU, 2016
CSC212 Data Structure
- Section FG
Lectures4&5ContainerClasses
Instructor:FengHUDepartmentofComputerScience
CityCollegeofNewYork
2@Feng HU, 2016
ContainerClasses
•Acontainerclassisadatatypethatiscapableofholdingacollectionofitems.
• InC++,containerclassescanbeimplementedasaclass,alongwithmemberfunctionstoadd,remove,andexamineitems.
Data Structuresand Other ObjectsUsing C++
3@Feng HU, 2016
Bags
• Forthefirstexample,thinkaboutabag.
4@Feng HU, 2016
Bags
• Forthefirstexample,thinkaboutabag.
• Insidethebagaresomenumbers.
5@Feng HU, 2016
InitialStateofaBag
• Whenyoufirstbegintouseabag,thebagwillbeempty.
• Wecountonthistobetheinitialstate ofanybagthatweuse.
THIS BAGIS
EMPTY.
6@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
I AMPUTTING THE
NUMBER 4INTO THE
BAG.
7@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
THE 4 ISIN THEBAG.
8@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
NOW I'MPUTTING
ANOTHERNUMBER IN THE BAG --
AN 8.
9@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
THE 8 ISALSO IN
THE BAG.
10@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
• Wecaneveninsertthesamenumbermorethanonce.
NOW I'MPUTTING ASECOND 4
IN THEBAG.
11@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
• Wecaneveninsertthesamenumbermorethanonce.
NOW THEBAG HASTWO 4'S
AND AN 8..
12@Feng HU, 2016
ExaminingaBag
• Wemayaskaboutthecontentsofthebag.
HAVEYOU GOTANY 4's
?
YES,I HAVETWO OFTHEM.
13@Feng HU, 2016
RemovingaNumberfromaBag
• Wemayremoveanumberfromabag.
THIS4 IS
OUTTAHERE!
14@Feng HU, 2016
RemovingaNumberfromaBag
• Wemayremoveanumberfromabag.
• Butweremoveonlyonenumberatatime. ONE 4 IS
GONE, BUTTHE OTHER4 REMAINS.
15@Feng HU, 2016
HowManyNumbers
• Anotheroperationistodeterminehowmanynumbersareinabag. IN MY OPINION,
THERE ARE TOO MANY NUMBERS.
16@Feng HU, 2016
SummaryoftheBagOperations
➊Abagcanbeputinitsinitial state,whichisanemptybag.➋Numberscanbeinserted intothebag.➌Youmaycount howmanyoccurrenceofacertainnumberareinthebag.❹Numberscanbeerased fromthebag.❺Youcancheckthesize ofthebag(i.e.howmanynumbersareinthebag).
17@Feng HU, 2016
Thebag Class
• C++classes(introducedinChapter2)canbeusedtoimplementacontainerclasssuchasabag.
• Theclassdefinitionincludes:
class bag
✔ The heading of the definition
18@Feng HU, 2016
Thebag Class
• C++classes(introducedinChapter2)canbeusedtoimplementacontainerclasssuchasabag.
• Theclassdefinitionincludes:
class bag{public:
bag( );
✔ The heading of the definition✔A constructor prototype
19@Feng HU, 2016
The bag Class
❐ C++ classes (introduced in Chapter 2) can be used to implement a container class such as a bag.
❐ The class definition includes:
class bag{public:
bag( );void insert(...void erase(......and so on✔ The heading of the definition
✔A constructor prototype✔ Prototypes for public
member functions
20@Feng HU, 2016
The bag Class
❐ C++ classes (introduced in Chapter 2) can be used to implement a container class such as a bag.
❐ The class definition includes:
class bag{public:
bag( );void insert(...void erase(......and so on
private:
};
✔ The heading of the definition✔A constructor prototype✔ Prototypes for public
member functions✔ Private member variables
We’ll look at privatemembers later.
21@Feng HU, 2016
Thebag’sDefaultConstructor
• Placesabagintheinitialstate(anemptybag)
bag::bag( )// Postcondition: The bag has been initialized// and it is now empty. {. . .
}
22@Feng HU, 2016
Theinsert Function
• Insertsanewnumberinthebag
void bag::insert(const int& new_entry)// Precondition: The bag is not full.// Postcondition: A new copy of new_entry has // been added to the bag.{
. . .}
23@Feng HU, 2016
Thesize Function
• Checkshowmanyintegersareinthebag.
int bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{
. . .}
24@Feng HU, 2016
Thesize Function
• Checkshowmanyintegersareinthebag.
size_t bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{
. . .}
25@Feng HU, 2016
Thecount Function
• Countshowmanycopiesofanumberoccur
size_t bag::count(const int& target) const// Postcondition: The return value is the number// of copies of target in the bag.{
. . .}
26@Feng HU, 2016
Theerase_one Function
• Removes(erase)onecopyofanumber
void bag::erase_one(const int& target)// Postcondition: If target was in the bag, then// one copy of target has been removed from the// bag; otherwise the bag is unchanged.{
. . .}
27@Feng HU, 2016
TheHeaderFileandImplementationFile
• Theprogrammerwhowritesthenewbagclassmustwritetwofiles:
• bag1.h,aheaderfilethatcontainsdocumentationandtheclassdefinition
• bag1.cxx,animplementationfilethatcontainstheimplementationsofthebag ’smemberfunctions
bag’s documentation
bag’s class definition
Implementations of thebag’s member functions
28@Feng HU, 2016
Documentationforthebag Class
• Thedocumentationgivesprototypesandspecifications forthebagmemberfunctions.
• Specificationsarewrittenasprecondition/postcondition contracts.
• Everythingneededtouse thebag classisincludedinthiscomment.
bag’s documentation
bag’s class definition
Implementations of thebag’s member functions
29@Feng HU, 2016
Thebag ’sClassDefinition
• Afterthedocumentation,theheaderfilehastheclassdefinitionthatwe’veseenbefore:
bag’s documentation
bag’s class definition
Implementations of thebag’s member functions
class bag{public:
bag( );void insert(...void erase(......and so on
private:…};
30@Feng HU, 2016
TheImplementationFile
• Aswithanyclass,theactualdefinitionsofthememberfunctionsareplacedinaseparateimplementationfile.
• Theimplementationsofthebag’smemberfunctionsareinbag1.cxx.
bag’s documentation
bag’s class definition
Implementations of thebag’s member functions
31@Feng HU, 2016
AQuiz
① YesIcan.② No.NotunlessIseetheclass
definitionforthebag .③ No.Ineedtoseetheclass
definitionforthebag ,andalsoseetheimplementationfile.
Suppose that a Mysterious Benefactor provides you with the bag class, but you are only permitted to read the documentation in the header file. You cannot read the class definition or implementation file. Can you write a program that uses the bag data type ?
32@Feng HU, 2016
AQuiz
① YesIcan.Youknowthenameofthenewdatatype,whichisenoughforyoutodeclarebag variables.Youalsoknowtheheadingsandspecificationsofeachoftheoperations.
Suppose that a Mysterious Benefactor provides you with the Bag class, but you are only permitted to read the documentation in the header file. You cannot read the class definition or implementation file. Can you write a program that uses the bag data type ?
33@Feng HU, 2016
Usingthebag inaProgram
• Hereistypicalcodefromaprogramthatusesthenewbag class:
bag ages;
// Record the ages of three children:ages.insert(4);ages.insert(8);ages.insert(4);
34@Feng HU, 2016
ImplementationDetails
• Theentriesofabagwillbestoredinthefrontpartofanarray,asshowninthisexample.
[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .
An array of integers
4 8 4
We don't care what's inthis part of the array.
35@Feng HU, 2016
ImplementationDetails
• Theentriesmayappearinanyorder.Thisrepresents thesamebagasthepreviousone...
An array of integers
4 4 8
We don't care what's inthis part of the array.
[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .
36@Feng HU, 2016
ImplementationDetails
• ...andthisalsorepresentsthesamebag.
An array of integersWe don't care what's in
this part of the array.
[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .
8 4 4
37@Feng HU, 2016
ImplementationDetails
• Wealsoneedtokeeptrackofhowmanynumbersareinthebag.
An array of integers
8 4 4
We don't care what's inthis part of the array.
An integer to keeptrack of the bag's size
3
[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .
38@Feng HU, 2016
AnExercise
Use these ideas to write a list of private member variables could implement the bag class. You should have two member variables. Make the bag capable of holding up to 20 integers.
You have 60 secondsto write the declaration.
39@Feng HU, 2016
AnExercise
class bag{public:
...private:
int data[20];size_t used;
};
One solution:
40@Feng HU, 2016
AnExercise
A more flexible solution:
class bag{public:
static const size_t CAPACITY = 20;...
private:int data[CAPACITY];size_t used;
};
41@Feng HU, 2016
TheInvariantofaClass
• Tworulesforourbagimplementation• Thenumberofitemsinthebagisstoredinthemembervariableused;
• Foranemptybag,wedon’tcarewhatisstoredinanyofdata;foranon-emptybag,theitemsarestoredindata[0]throughdata[used-1], andwedon’tcarewhatarestoredintherestofdata.
• Therulesthatdictatehowthemembervariablesofa(bag)classareusedtorepresentavalue(suchasabagofitems)arecalledtheinvariant of the class
42@Feng HU, 2016
TheInvariantofaClass
• Theinvariant of the class isessentialtothecorrectimplementationoftheclass’sfunctions
• Insomesense,• theinvariantofaclassisacondition thatisanimplicit partofeveryfunction’s postcondition
• And (exceptfortheconstructors)itisalsoanimplicit partofeveryfunction’sprecondition.
43@Feng HU, 2016
TheInvariantofaClass
• PreconditionandPostcondition• contractforeachfunction,foruseofthefunction• documentpre- andpost- intheheaderfile
• Theinvariant of the class • implicit partofpre- andpost- soisnotusuallywrittenasanexplicit partofpre- andpost-
• abouttheprivatemembervariables,thusforimplementation,butnotforhowtousethem
• documentedintheimplementationfile•ValueSemantics
• bothforimplementationandforuse• documentedintheheaderfile
44@Feng HU, 2016
AnExampleofCallinginsert
void bag::insert(const int& new_entry)
Before calling insert, wemight have this bag b:
2
[ 0 ] [ 1 ] [2] . . .
8 4b.data
b.used
45@Feng HU, 2016
AnExampleofCallinginsert
void Bag::insert(int new_entry)
b.data
b.used
We make a function callb.insert(17)
What values will be inb.data and b.countafter the member function finishes ?
2
[ 0 ] [ 1 ] [2] . . .
8 4
void bag::insert(const int& new_entry)
46@Feng HU, 2016
AnExampleofCallinginsert
void Bag::insert(int new_entry)
After calling b.insert(17),we will have this bag b:
3
[ 0 ] [1] [ 2 ] . . .
8 4 17
void bag::insert(const int& new_entry)
b.data
b.used2
[ 0 ] [ 1 ] [2] . . .
8 4
47@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
What is the “appropriatelocation” of the data array ?
48@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
data[used] = new_entry;used++;
49@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
data[ used++] = new_entry;
50@Feng HU, 2016
Summary
•Acontainerclassisaclassthatcanholdacollectionofitems.
•ContainerclassescanbeimplementedwithaC++class.
• Theclassisimplementedwith• aheaderfile(containingdocumentationandtheclassdefinition)bag1.h and
• animplementationfile(containingtheimplementationsofthememberfunctions)bag1.cxx.
•OtherdetailsaregiveninSection3.1,whichyoushouldread,especiallytherealbagcode
51@Feng HU, 2016
OutlineforLecture5
•Bagclassdefinition/implementationdetails• Inlinefunctions
• constructor,size• Otherbasicfunctions
• insert,erase_one,erase,count• Moreadvancedfunctions
• operators+,+=,-
• TimeAnalysis• Big-O
• Introductiontosequence
52@Feng HU, 2016
TheOtherbag Operations
•ReadSection3.1fortheimplementationsoftheotherbagmemberfunctions• suchasoperatorsappend (+=)andunion (+)
•Remember:Ifyouarejustusing thebag class• thenyoudon’tneedtoknowhowtheoperationsareimplemented.
• Laterwewillreimplement thebagusingmoreefficienttechniques.
•We’llalsohaveafewotheroperationstomanipulatebags.
53@Feng HU, 2016
AppendOperator+=
void bag::operator+=(const bag& addend)// Precondition: size( ) + addend.size( ) <= CAPACITY.// Postcondition: Each item in addend has been added to this bag.
{size_t i;assert(size( ) + addend.size( ) <= CAPACITY);for (i = 0; i< addend.used; ++i){
data[used] = addend.data[i];++used;
}}
// calling program: a += b; (OKAY)// Question : What will happen if you call: b += b;
54@Feng HU, 2016
AppendOperator+=
void bag::operator+=(const bag& addend)// Precondition: size( ) + addend.size( ) <= CAPACITY.// Postcondition: Each item in addend has been added to this bag.// Library facilities used: algorithm, cassert{
assert(size( ) + addend.size( ) <= CAPACITY);
copy(addend.data, addend.data + addend.used, data + used);used += addend.used;
}
// copy (<beginning location>, ending location>, <destination>);// Question : Can you fix the bug in the previous slide without using copy ?
55@Feng HU, 2016
UnionOperator+
// NONMEMBER FUNCTION for the bag class:bag operator+(const bag& b1, const bag& b2)// Precondition: b1.size( ) + b2.size( ) <= bag::CAPACITY.// Postcondition: The bag returned is the union of b1 and b2.// Library facilities used: cassert{
bag answer;
assert(b1.size( ) + b2.size( ) <= bag::CAPACITY);
answer += b1; answer += b2;return answer;
}
// calling program: c =a+b; // Question : what happens if you call a =a+b ?
56@Feng HU, 2016
SubtractOperator-
// Prototype: NONMEMBER friend FUNCTION for the bag class:// bag operator-(const bag& b1, const bag& b2);// Postcondition: For two bags b1 and b2, the bag x-y contains all the
items of x, with any items from y removed// Write your implementation// HINTS:// 1. A friend function can access private member variables of a bag// 2. You cannot change constant reference parameters// 3. You may use any member functions of the bag class such as// b1.count(target); // how many target is in bag b1?// b1.erase_one(target); // target is an integer item// b2.size(); // size of the bag b2;// bag b3(b2); // automatic copy constructor//
57@Feng HU, 2016
SubtractOperator-
// NONMEMBER friend FUNCTION for the bag class:bag operator-(const bag& b1, const bag& b2)// Postcondition: For two bags b1 and b2, the bag x-y contains all the
items of x, with any items from y removed{
size_t index;bag answer(b1); // copy constructorsize_t size2 = b2.size(); // use member function sizefor (index = 0; index < size2; ++index){
int target = b2.data[index]; // use private member variableif (answer.count(target) ) // use function count
answer.erase_one(target); // use function erase_one}return answer;
}
58@Feng HU, 2016
OtherKindsofBags
• Inthisexample,wehaveimplementedabagcontainingintegers.• Butwecouldhavehadabagoffloatnumbers,abagofcharacters,abagofstrings ...
Suppose you wanted one of these other bags. How much would you need to change in the implementation ?Section 3.1 gives a simple solution usingthe C++ typedef statement.
59@Feng HU, 2016
TimeAnalysisoftheBagClass
• count– thenumberofoccurrence• erase_one– removeonefromthebag• erase– removeall• +=- append• b1+b2- union• insert– addoneitem• size– numberofitemsinthebag
60@Feng HU, 2016
What’sthemostimportant,then?
•ConceptofContainerClasses• thebagclassisnotparticularlyimportant
•Otherkindsofcontainerclasses• sequence – similartoabag,bothcontainabunchofitems.Butunlikeabag,theitemsinasequenceisarrangedinorder.
• willbethetopicofoursecondassignment– payingattentiontothedifferences
• index– havecurrent,next,last,etc• memberfunctionsandtheirimplementation(e.g.insert,attach)• timeanalysis(insert)
61@Feng HU, 2016
AfterClass…
• Assignment2• DueWednesday,Sept28• Reading:Chapter3,Section3.2-3.3• especiallythesequencecode
• Self-TestExercises• 1,3,5,10,11,14,18-24
• Readingfornextlecture• Chapter4,Section4.1-4.2
62@Feng HU, 2016
Summary
•Acontainerclassisaclassthatcanholdacollectionofitems.
•ContainerclassescanbeimplementedwithaC++class.
• Theclassisimplementedwith• aheaderfile(containingdocumentationandtheclassdefinition)bag1.h and
• animplementationfile(containingtheimplementationsofthememberfunctions)bag1.cxx.
•OtherdetailsaregiveninSection3.1,whichyoushouldread,especiallytherealbagcode
63@Feng HU, 2016
THE END
Presentation copyright 1997, Addison Wesley LongmanFor use with Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.
Some artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc.) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc., Archive Arts, Cartesia Software, Image ClubGraphics Inc., One Mile Up Inc., TechPool Studios, Totem Graphics Inc.).
Students and instructors who use Data Structures and Other Objects Using C++ arewelcome to use this presentation however they see fit, so long as this copyright notice remains intact.
This lecture was modified from the authors’ presentation, with new conventions provided in the second edition (2001) of the textbook and other minor changes -- Feng HU, 2016, CCNY