Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data...
Transcript of Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data...
![Page 1: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/1.jpg)
1@Feng HU, 2016@Feng HU, 2016
CSC212 Data Structure
- Section FG
Lectures4&5ContainerClasses
Instructor:FengHUDepartmentofComputerScience
CityCollegeofNewYork
![Page 2: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/2.jpg)
2@Feng HU, 2016
ContainerClasses
•Acontainerclassisadatatypethatiscapableofholdingacollectionofitems.
• InC++,containerclassescanbeimplementedasaclass,alongwithmemberfunctionstoadd,remove,andexamineitems.
Data Structuresand Other ObjectsUsing C++
![Page 3: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/3.jpg)
3@Feng HU, 2016
Bags
• Forthefirstexample,thinkaboutabag.
![Page 4: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/4.jpg)
4@Feng HU, 2016
Bags
• Forthefirstexample,thinkaboutabag.
• Insidethebagaresomenumbers.
![Page 5: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/5.jpg)
5@Feng HU, 2016
InitialStateofaBag
• Whenyoufirstbegintouseabag,thebagwillbeempty.
• Wecountonthistobetheinitialstate ofanybagthatweuse.
THIS BAGIS
EMPTY.
![Page 6: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/6.jpg)
6@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
I AMPUTTING THE
NUMBER 4INTO THE
BAG.
![Page 7: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/7.jpg)
7@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
THE 4 ISIN THEBAG.
![Page 8: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/8.jpg)
8@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
NOW I'MPUTTING
ANOTHERNUMBER IN THE BAG --
AN 8.
![Page 9: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/9.jpg)
9@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
THE 8 ISALSO IN
THE BAG.
![Page 10: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/10.jpg)
10@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
• Wecaneveninsertthesamenumbermorethanonce.
NOW I'MPUTTING ASECOND 4
IN THEBAG.
![Page 11: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/11.jpg)
11@Feng HU, 2016
InsertingNumbersintoaBag
• Numbersmaybeinsertedintoabag.
• Thebagcanholdmanynumbers.
• Wecaneveninsertthesamenumbermorethanonce.
NOW THEBAG HASTWO 4'S
AND AN 8..
![Page 12: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/12.jpg)
12@Feng HU, 2016
ExaminingaBag
• Wemayaskaboutthecontentsofthebag.
HAVEYOU GOTANY 4's
?
YES,I HAVETWO OFTHEM.
![Page 13: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/13.jpg)
13@Feng HU, 2016
RemovingaNumberfromaBag
• Wemayremoveanumberfromabag.
THIS4 IS
OUTTAHERE!
![Page 14: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/14.jpg)
14@Feng HU, 2016
RemovingaNumberfromaBag
• Wemayremoveanumberfromabag.
• Butweremoveonlyonenumberatatime. ONE 4 IS
GONE, BUTTHE OTHER4 REMAINS.
![Page 15: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/15.jpg)
15@Feng HU, 2016
HowManyNumbers
• Anotheroperationistodeterminehowmanynumbersareinabag. IN MY OPINION,
THERE ARE TOO MANY NUMBERS.
![Page 16: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/16.jpg)
16@Feng HU, 2016
SummaryoftheBagOperations
➊Abagcanbeputinitsinitial state,whichisanemptybag.➋Numberscanbeinserted intothebag.➌Youmaycount howmanyoccurrenceofacertainnumberareinthebag.❹Numberscanbeerased fromthebag.❺Youcancheckthesize ofthebag(i.e.howmanynumbersareinthebag).
![Page 17: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/17.jpg)
17@Feng HU, 2016
Thebag Class
• C++classes(introducedinChapter2)canbeusedtoimplementacontainerclasssuchasabag.
• Theclassdefinitionincludes:
class bag
✔ The heading of the definition
![Page 18: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/18.jpg)
18@Feng HU, 2016
Thebag Class
• C++classes(introducedinChapter2)canbeusedtoimplementacontainerclasssuchasabag.
• Theclassdefinitionincludes:
class bag{public:
bag( );
✔ The heading of the definition✔A constructor prototype
![Page 19: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/19.jpg)
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
![Page 20: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/20.jpg)
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.
![Page 21: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/21.jpg)
21@Feng HU, 2016
Thebag’sDefaultConstructor
• Placesabagintheinitialstate(anemptybag)
bag::bag( )// Postcondition: The bag has been initialized// and it is now empty. {. . .
}
![Page 22: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/22.jpg)
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.{
. . .}
![Page 23: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/23.jpg)
23@Feng HU, 2016
Thesize Function
• Checkshowmanyintegersareinthebag.
int bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{
. . .}
![Page 24: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/24.jpg)
24@Feng HU, 2016
Thesize Function
• Checkshowmanyintegersareinthebag.
size_t bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{
. . .}
![Page 25: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/25.jpg)
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.{
. . .}
![Page 26: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/26.jpg)
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.{
. . .}
![Page 27: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/27.jpg)
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
![Page 28: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/28.jpg)
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
![Page 29: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/29.jpg)
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:…};
![Page 30: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/30.jpg)
30@Feng HU, 2016
TheImplementationFile
• Aswithanyclass,theactualdefinitionsofthememberfunctionsareplacedinaseparateimplementationfile.
• Theimplementationsofthebag’smemberfunctionsareinbag1.cxx.
bag’s documentation
bag’s class definition
Implementations of thebag’s member functions
![Page 31: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/31.jpg)
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 ?
![Page 32: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/32.jpg)
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 ?
![Page 33: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/33.jpg)
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);
![Page 34: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/34.jpg)
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.
![Page 35: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/35.jpg)
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 ] . . .
![Page 36: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/36.jpg)
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
![Page 37: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/37.jpg)
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 ] . . .
![Page 38: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/38.jpg)
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.
![Page 39: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/39.jpg)
39@Feng HU, 2016
AnExercise
class bag{public:
...private:
int data[20];size_t used;
};
One solution:
![Page 40: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/40.jpg)
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;
};
![Page 41: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/41.jpg)
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
![Page 42: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/42.jpg)
42@Feng HU, 2016
TheInvariantofaClass
• Theinvariant of the class isessentialtothecorrectimplementationoftheclass’sfunctions
• Insomesense,• theinvariantofaclassisacondition thatisanimplicit partofeveryfunction’s postcondition
• And (exceptfortheconstructors)itisalsoanimplicit partofeveryfunction’sprecondition.
![Page 43: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/43.jpg)
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
![Page 44: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/44.jpg)
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
![Page 45: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/45.jpg)
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)
![Page 46: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/46.jpg)
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
![Page 47: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/47.jpg)
47@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
What is the “appropriatelocation” of the data array ?
![Page 48: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/48.jpg)
48@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
data[used] = new_entry;used++;
![Page 49: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/49.jpg)
49@Feng HU, 2016
Pseudocodeforbag::insert
➊ assert(size( ) < CAPACITY);➋ Placenew_entry intheappropriatelocationofthedata
array.
➌ Addonetothemembervariablecount.
data[ used++] = new_entry;
![Page 50: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/50.jpg)
50@Feng HU, 2016
Summary
•Acontainerclassisaclassthatcanholdacollectionofitems.
•ContainerclassescanbeimplementedwithaC++class.
• Theclassisimplementedwith• aheaderfile(containingdocumentationandtheclassdefinition)bag1.h and
• animplementationfile(containingtheimplementationsofthememberfunctions)bag1.cxx.
•OtherdetailsaregiveninSection3.1,whichyoushouldread,especiallytherealbagcode
![Page 51: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/51.jpg)
51@Feng HU, 2016
OutlineforLecture5
•Bagclassdefinition/implementationdetails• Inlinefunctions
• constructor,size• Otherbasicfunctions
• insert,erase_one,erase,count• Moreadvancedfunctions
• operators+,+=,-
• TimeAnalysis• Big-O
• Introductiontosequence
![Page 52: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/52.jpg)
52@Feng HU, 2016
TheOtherbag Operations
•ReadSection3.1fortheimplementationsoftheotherbagmemberfunctions• suchasoperatorsappend (+=)andunion (+)
•Remember:Ifyouarejustusing thebag class• thenyoudon’tneedtoknowhowtheoperationsareimplemented.
• Laterwewillreimplement thebagusingmoreefficienttechniques.
•We’llalsohaveafewotheroperationstomanipulatebags.
![Page 53: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/53.jpg)
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;
![Page 54: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/54.jpg)
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 ?
![Page 55: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/55.jpg)
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 ?
![Page 56: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/56.jpg)
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//
![Page 57: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/57.jpg)
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;
}
![Page 58: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/58.jpg)
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.
![Page 59: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/59.jpg)
59@Feng HU, 2016
TimeAnalysisoftheBagClass
• count– thenumberofoccurrence• erase_one– removeonefromthebag• erase– removeall• +=- append• b1+b2- union• insert– addoneitem• size– numberofitemsinthebag
![Page 60: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/60.jpg)
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)
![Page 61: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/61.jpg)
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
![Page 62: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/62.jpg)
62@Feng HU, 2016
Summary
•Acontainerclassisaclassthatcanholdacollectionofitems.
•ContainerclassescanbeimplementedwithaC++class.
• Theclassisimplementedwith• aheaderfile(containingdocumentationandtheclassdefinition)bag1.h and
• animplementationfile(containingtheimplementationsofthememberfunctions)bag1.cxx.
•OtherdetailsaregiveninSection3.1,whichyoushouldread,especiallytherealbagcode
![Page 63: Data Structure - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture04-05-Container.pdf · Data Structure -Section FG Lectures ... Data Structures and Other Objects Using C++ @Feng HU,](https://reader030.fdocuments.us/reader030/viewer/2022021802/5b758f1f7f8b9a634c8d9166/html5/thumbnails/63.jpg)
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