1 csc211 data structures lectures 4 & 5 container classes instructor: prof. xiaoyan li...

93
1 CSC211 Data Structures Lectures 4 & 5 Lectures 4 & 5 Container Classes Container Classes Instructor: Prof. Xiaoyan Li Instructor: Prof. Xiaoyan Li Department of Computer Science Department of Computer Science Mount Holyoke College Mount Holyoke College

Upload: lawrence-sweetland

Post on 22-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

11

CSC211 Data Structures CSC211 Data Structures

Lectures 4 & 5Lectures 4 & 5Container ClassesContainer Classes

Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan LiDepartment of Computer Science Department of Computer Science

Mount Holyoke CollegeMount Holyoke College

Page 2: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

22

Review of Lecture 2&3Review of Lecture 2&3

A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value Semantics

More on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading

Page 3: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

33

How to Use Items in a Namespace?How to Use Items in a Namespace?

Three ways to use the items in a Three ways to use the items in a namespacenamespace using namespace main_savitch_2A;using namespace main_savitch_2A; using main_savitch_2A::point;using main_savitch_2A::point; main_savitch_2A::point p1;main_savitch_2A::point p1;

Can we use Can we use a using directive in a header a using directive in a header file ?file ?

Can we use it before an #include directive?Can we use it before an #include directive?

Page 4: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

44

How to Use Items in a Namespace? (Example?)How to Use Items in a Namespace? (Example?)

namespace foo { int bar; double pi; }

using namespace foo;

int* pi; pi = &bar;

Page 5: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

55

More about NamespaceMore about Namespace

Default namespaceDefault namespace Namespaces are hierarchical. Namespaces are hierarchical.

Within the hypothetical namespace food::fruit, Within the hypothetical namespace food::fruit, the identifier orange refers to food::fruit::orange the identifier orange refers to food::fruit::orange if it exists,if it exists,

or if not food::orange if it exists. or if not food::orange if it exists. If neither exist, orange refers to an identifier in If neither exist, orange refers to an identifier in

the default namespacethe default namespace

Page 6: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

66

Class as type of parameterClass as type of parameter

Page 7: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

77

Class as type of parameterClass as type of parameter

A class can be used as the type of a A class can be used as the type of a function’s parameter, just like any function’s parameter, just like any other data typeother data type Value parametersValue parameters Reference parametersReference parameters Const reference parametersConst reference parameters

Page 8: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

88

Operator OverloadingOperator Overloading

Page 9: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

99

Operator OverloadingOperator Overloading

Overloading arithmetic operationsOverloading arithmetic operations Overloading binary comparison operationsOverloading binary comparison operations Overloading input/output functionsOverloading input/output functions Friend functions – when to useFriend functions – when to use

Page 10: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1010

A A container class container class is a data is a data type that is capable of type that is capable of holding a collection of holding a collection of items.items.

In C++, container classes In C++, container classes can be implemented as a can be implemented as a class, along with member class, along with member functions to add, remove, functions to add, remove, and examine items.and examine items.

Container ClassesContainer Classes

Data StructuresData Structuresand Other Objectsand Other ObjectsUsing C++Using C++

Page 11: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1111

BagsBags

For the first example, For the first example, think about a bag.think about a bag.

Page 12: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1212

BagsBags

For the first example, For the first example, think about a bag.think about a bag.

Inside the bag are Inside the bag are some numbers.some numbers.

Page 13: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1313

Initial State of a BagInitial State of a Bag

When you first begin When you first begin to use a bag, the bag to use a bag, the bag will be empty.will be empty.

We count on this to be We count on this to be the the initial stateinitial state of any of any bag that we use.bag that we use.

THIS BAGIS

EMPTY.

Page 14: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1414

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

I AMPUTTING THE

NUMBER 4INTO THE

BAG.

Page 15: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1515

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

THE 4 ISIN THEBAG.

Page 16: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1616

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

The bag can hold The bag can hold many numbers.many numbers.

NOW I'MPUTTINGANOTHER

NUMBER IN THE BAG --

AN 8.

Page 17: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1717

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

The bag can hold The bag can hold many numbers.many numbers.

THE 8 ISALSO IN

THE BAG.

Page 18: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1818

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

The bag can hold The bag can hold many numbers.many numbers.

We can even insert We can even insert the same number the same number more than once.more than once. NOW I'M

PUTTING ASECOND 4

IN THEBAG.

Page 19: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

1919

Inserting Numbers into a BagInserting Numbers into a Bag

Numbers may be Numbers may be inserted into a bag.inserted into a bag.

The bag can hold The bag can hold many numbers.many numbers.

We can even insert We can even insert the same number the same number more than once.more than once.

NOW THEBAG HASTWO 4'S

AND AN 8..

Page 20: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2020

Examining a BagExamining a Bag

We may ask about We may ask about the contents of the the contents of the bag. bag.

HAVEYOU GOTANY 4's

?

YES,I HAVETWO OFTHEM.

Page 21: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2121

Removing a Number from a BagRemoving a Number from a Bag

We may remove a We may remove a number from a bag. number from a bag.

THIS4 IS

OUTTAHERE!

Page 22: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2222

Removing a Number from a BagRemoving a Number from a Bag

We may remove a We may remove a number from a bag.number from a bag.

But we remove only But we remove only one number at a one number at a time. time.

ONE 4 ISGONE, BUTTHE OTHER4 REMAINS.

Page 23: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2323

How Many NumbersHow Many Numbers

Another operation is Another operation is to determine how to determine how many numbers are in a many numbers are in a bag.bag.

IN MY OPINION, THERE ARE TOO MANY NUMBERS.

Page 24: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2424

Summary of the Bag OperationsSummary of the Bag Operations

A bag can be put in its A bag can be put in its initial stateinitial state, , which is an empty bag.which is an empty bag.

Numbers can be Numbers can be insertedinserted into the bag. into the bag. You may You may countcount how many occurrence of how many occurrence of

a certain number are in the bag.a certain number are in the bag. Numbers can be Numbers can be erasederased from the bag. from the bag. You can check the You can check the sizesize of the bag (i.e. of the bag (i.e.

how many numbers are in the bag).how many numbers are in the bag).

Page 25: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2525

The bag ClassThe bag Class

C++ classes (introduced in C++ classes (introduced in Chapter 2) can be used to Chapter 2) can be used to implement a container class implement a container class such as a such as a bagbag..

The class definition includes:The class definition includes:

class bag

The heading of the definition

Page 26: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2626

The bag ClassThe bag Class

C++ classes (introduced in C++ classes (introduced in Chapter 2) can be used to Chapter 2) can be used to implement a container class implement a container class such as a bag.such as a bag.

The class definition includes:The class definition includes:

class bag{public: bag( );

The heading of the definition A constructor prototype

Page 27: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2727

The bag ClassThe bag Class

C++ classes (introduced in C++ classes (introduced in Chapter 2) can be used to Chapter 2) can be used to implement a container class implement a container class such as a such as a bag..

The class definition includes: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 28: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2828

The bag ClassThe bag Class

C++ classes (introduced in C++ classes (introduced in Chapter 2) can be used to Chapter 2) can be used to implement a container class implement a container class such as a such as a bagbag..

The class definition includes:The class definition includes:

class bag{public: bag( ); void insert(... void erase(... ...and so onprivate:

};

The heading of the definition A constructor prototype Prototypes for public member functions Private member variables

We’ll look at privatemembers later.

We’ll look at privatemembers later.

Page 29: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

2929

The bag’s Default ConstructorThe bag’s Default Constructor

Places a bag in the initial state (an empty Places a bag in the initial state (an empty bag)bag)

bag::bag( )// Postcondition:{ . . .

}

Page 30: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3030

The bag’s Default ConstructorThe bag’s Default Constructor

Places a bag in the initial state (an empty Places a bag in the initial state (an empty bag)bag)

bag::bag( )// Postcondition: The bag has been initialized// and it is now empty. { . . .

}

Page 31: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3131

The insert FunctionThe insert Function

Inserts a new number in the bagInserts a new number in the bag

void bag::insert(const int& new_entry)// Precondition:// Postcondition:{

. . .}

Page 32: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3232

The insert FunctionThe insert Function

Inserts a new number in the bagInserts a new number in the bag

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 33: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3333

The size FunctionThe size Function

Checks how many integers are in the bag.Checks how many integers are in the bag.

int bag::size( ) const//Precondition: //Postcondition: {

. . .}

Page 34: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3434

The size FunctionThe size Function

Checks how many integers are in the bag.Checks how many integers are in the bag.

int bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{

. . .}

Page 35: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3535

The size FunctionThe size Function

Checks how many integers are in the bag.Checks how many integers are in the bag.

size_t bag::size( ) const// Postcondition: The return value is the number// of integers in the bag.{

. . .}

Page 36: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3636

The count FunctionThe count Function

Counts how many copies of a number occurCounts how many copies of a number occur

size_t bag::count(const int& target) const//Precondition://Postcondition: {

. . .}

Page 37: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3737

The count FunctionThe count Function

Counts how many copies of a number occurCounts how many copies of a number occur

size_t bag::count(const int& target) const// Postcondition: The return value is the number// of copies of target in the bag.{

. . .}

Page 38: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3838

The erase_one FunctionThe erase_one Function

Removes (erase) one copy of a numberRemoves (erase) one copy of a number

void bag::erase_one(const int& target)//Precondition: //Postcondition: {

. . .}

Page 39: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

3939

The erase_one FunctionThe erase_one Function

Removes (erase) one copy of a numberRemoves (erase) one copy of a number

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 40: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4040

The Header File and Implementation FileThe Header File and Implementation File

The programmer who writes The programmer who writes the new the new bagbag class must write class must write two files:two files:

bag1.hbag1.h, a header file that , a header file that contains documentation and contains documentation and the class definitionthe class definition

bag1.cxxbag1.cxx, an implementation , an implementation file that contains the file that contains the implementations of the implementations of the bagbag ’s ’s member functionsmember functions

bag’s documentation

bag’s class definition

Implementations of thebag’s member functions

Page 41: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4141

Using the bag in a ProgramUsing the bag in a Program

Here is typical code from a Here is typical code from a program that uses the new program that uses the new bagbag class: class:

bag ages;

// Record the ages of three children:ages.insert(4);ages.insert(8);ages.insert(4);

Page 42: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4242

Documentation for the bag ClassDocumentation for the bag Class

The documentation gives The documentation gives prototypes and prototypes and specificationsspecifications for the bag for the bag member functions.member functions.

Specifications are written as Specifications are written as precondition/postcondition precondition/postcondition contracts.contracts.

Everything needed to Everything needed to useuse the the bagbag class is included in this class is included in this comment.comment.

bag’s documentation

bag’s class definition

Implementations of thebag’s member functions

Page 43: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4343

The bag ’s Class DefinitionThe bag ’s Class Definition

After the documentation, After the documentation, the header file has the class the header file has the class definition that we’ve seen definition that we’ve seen before:before:

bag’s documentation

bag’s class definition

Implementations of thebag’s member functions

class bag{public: bag( ); void insert(... void erase(... ...and so onprivate:…};

Page 44: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4444

The Implementation FileThe Implementation File

As with any class, the As with any class, the actual definitions of the actual definitions of the member functions are member functions are placed in a separate placed in a separate implementation file.implementation file.

The The implementations implementations of of the the bagbag’s member ’s member functions are in functions are in bag1.cxxbag1.cxx..

bag’s documentation

bag’s class definition

Implementations of thebag’s member functions

Page 45: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4545

A QuizA Quiz

Suppose that a Mysterious Suppose that a Mysterious Benefactor provides you Benefactor provides you with the bag class, but you with the bag class, but you are only permitted to read are only permitted to read the documentation in the the documentation in the header file. You cannot header file. You cannot read the class definition or read the class definition or implementation file. Can implementation file. Can you write a program that you write a program that uses the uses the bagbag data type ? data type ?

Yes I can.Yes I can.No. Not unless I see the No. Not unless I see the

class definition for the class definition for the bagbag ..

No. I need to see the No. I need to see the class definition for the class definition for the bagbag , and also see the , and also see the implementation file.implementation file.

Page 46: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4646

A QuizA Quiz

Suppose that a Mysterious Suppose that a Mysterious Benefactor provides you Benefactor provides you with the Bag class, but you with the Bag class, but you are only permitted to read are only permitted to read the documentation in the the documentation in the header file. You cannot header file. You cannot read the class definition or read the class definition or implementation file. Can implementation file. Can you write a program that you write a program that uses the uses the bagbag data type ? data type ?

Yes I can.Yes I can.

You know the name of the You know the name of the new data type, which is new data type, which is enough for you to declare enough for you to declare bagbag variables. You also variables. You also know the headings and know the headings and specifications of each of specifications of each of the operations.the operations.

Page 47: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4747

Using the bag in a ProgramUsing the bag in a Program

Here is typical code from a Here is typical code from a program that uses the new program that uses the new bagbag class: class:

bag ages;

// Record the ages of three children:ages.insert(4);ages.insert(8);ages.insert(4);

Page 48: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4848

Implementation Details Implementation Details

How to store the entries of a bag?How to store the entries of a bag?

An array of integersAn array of integers

Page 49: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

4949

Implementation DetailsImplementation Details

The entries of a bag The entries of a bag will be stored in the will be stored in the front part of an array, front part of an array, as shown in this as shown in this example. example.

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

An array of integersAn array of integers

4 8 4

We don't care what's inWe don't care what's inthis part of the array.this part of the array.

Page 50: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5050

Implementation DetailsImplementation Details

The entries may The entries may appear in any order. appear in any order. This represents the This represents the same bag as the same bag as the previous one. . . previous one. . .

An array of integersAn array of integers

4 4 8

We don't care what's inWe don't care what's inthis part of the array.this part of the array.

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

Page 51: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5151

Implementation DetailsImplementation Details

. . . and this also . . . and this also represents the same represents the same bag.bag.

An array of integersAn array of integersWe don't care what's inWe don't care what's inthis part of the array.this part of the array.

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

8 4 4

Page 52: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5252

Implementation DetailsImplementation Details

We also need to keep track of how We also need to keep track of how many numbers are in the bag.many numbers are in the bag.

An array of integersAn array of integers

8 4 4

We don't care what's inWe don't care what's inthis part of the array.this part of the array.

An integer to keepAn integer to keeptrack of the bag's sizetrack of the bag's size

3

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

Page 53: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5353

An ExerciseAn Exercise

Use these ideas to write a Use these ideas to write a list of private member list of private member variables could implement variables could implement

the the bagbag class. You class. You should have two member should have two member variables. Make the bag variables. Make the bag capable of holding up to capable of holding up to 20 integers.20 integers.

You have 60 secondsto write the declaration.

Page 54: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5454

An ExerciseAn Exercise

class bag{public: ...private: int data[20]; size_t used;};

One solution:One solution:

Page 55: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5555

An ExerciseAn Exercise

A more flexible solution:A more flexible solution:

class bag{public: static const size_t CAPACITY = 20; ...private: int data[CAPACITY]; size_t used;};

Page 56: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5656

The Invariant of a ClassThe Invariant of a Class

Two rules for our bag implementationTwo rules for our bag implementation The number of items in the bag is stored in the The number of items in the bag is stored in the

member variable member variable usedused;; For an empty bag, we don’t care what is stored in any For an empty bag, we don’t care what is stored in any

of of datadata; for a non-empty bag, the items are stored in ; for a non-empty bag, the items are stored in datadata[0] through [0] through datadata[[usedused-1], and we don’t care what -1], and we don’t care what are stored in the rest of are stored in the rest of datadata..

The rules that dictate how the member variables The rules that dictate how the member variables of a (bag) class are used to represent a value (such of a (bag) class are used to represent a value (such as a bag of items) are called the as a bag of items) are called the invariant of the invariant of the classclass

Page 57: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5757

The Invariant of a ClassThe Invariant of a Class

The The invariant of the class invariant of the class is essential to is essential to the correct implementation of the class’s the correct implementation of the class’s functionsfunctions

In some sense, In some sense, the invariant of a class is a condition that is an the invariant of a class is a condition that is an implicitimplicit part of every function’s postcondition part of every function’s postcondition

And (except for the constructors) it is also an And (except for the constructors) it is also an implicitimplicit part of every function’s precondition. part of every function’s precondition.

Page 58: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5858

The Invariant of a ClassThe Invariant of a Class

Precondition and PostconditionPrecondition and Postcondition contract for each function, for use of the functioncontract for each function, for use of the function document pre- and post- in the header filedocument pre- and post- in the header file

The The invariant of the class invariant of the class implicitimplicit part of pre- and post- so is not usually written as part of pre- and post- so is not usually written as

an an explicitexplicit part of pre- and post- part of pre- and post- about the private member variables, thus for about the private member variables, thus for

implementation, but not for how to use themimplementation, but not for how to use them documented in the implementation filedocumented in the implementation file

Value SemanticsValue Semantics both for implementation and for useboth for implementation and for use documented in the header filedocumented in the header file

Page 59: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

5959

An Example of Calling insertAn Example of Calling insert

void bag::insert(const int& new_entry)

Before calling insert, weBefore calling insert, wemight have this bag b:might have this bag b:

2

[ 0 ][ 0 ] [ 1 ][ 1 ] [2][2] . . .. . .

8 4b.datab.data

b.usedb.used

Page 60: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6060

An Example of Calling insertAn Example of Calling insert

void Bag::insert(int new_entry)

b.datab.data

b.usedb.used

We make a function callWe make a function callb.insert(17)b.insert(17)

What values will be inb.data and b.countafter the member function finishes ?

2

[ 0 ][ 0 ] [ 1 ][ 1 ] [2][2] . . .. . .

8 4

void bag::insert(const int& new_entry)

Page 61: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6161

An Example of Calling insertAn Example of Calling insert

void Bag::insert(int new_entry)

After calling b.insert(17),After calling b.insert(17),we will have this bag b:we will have this bag b:

33

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] . . .. . .

8 4 1717

void bag::insert(const int& new_entry)

b.datab.data

b.usedb.used2

[ 0 ][ 0 ] [ 1 ][ 1 ] [2][2] . . .. . .

8 4

Page 62: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6262

Pseudocode for bag::insert (try it yourself first)Pseudocode for bag::insert (try it yourself first)

Page 63: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6363

Pseudocode for bag::insertPseudocode for bag::insert

assert(size( ) < CAPACITY);assert(size( ) < CAPACITY);

Place Place new_entrynew_entry in the appropriate location in the appropriate location of the of the datadata array. array.

Add one to the member variable Add one to the member variable countcount..

What is the “appropriatelocation” of the data array ?

Page 64: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6464

Pseudocode for bag::insertPseudocode for bag::insert

assert(size( ) < CAPACITY);assert(size( ) < CAPACITY);

Place Place new_entrynew_entry in the appropriate location in the appropriate location of the of the datadata array. array.

Add one to the member variable Add one to the member variable countcount..

data[used] = new_entry;used++;

Page 65: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6565

Pseudocode for bag::insertPseudocode for bag::insert

assert(size( ) < CAPACITY);assert(size( ) < CAPACITY);

Place Place new_entrynew_entry in the appropriate location in the appropriate location of the of the datadata array. array.

Add one to the member variable Add one to the member variable countcount..

data[ used++] = new_entry;

Page 66: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6666

A container class is a class that can hold a collection A container class is a class that can hold a collection of items.of items.

Container classes can be implemented with a C++ Container classes can be implemented with a C++ class.class.

The class is implemented with The class is implemented with a header file (containing documentation and the class a header file (containing documentation and the class

definition) definition) bag1.hbag1.h and and an implementation file (containing the implementations of an implementation file (containing the implementations of

the member functions) the member functions) bag1.cxxbag1.cxx.. Other details are given in Section 3.1, which you Other details are given in Section 3.1, which you

should read, especially the real should read, especially the real bag codebag code

Summary Summary

Page 67: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6767

Outline for Lecture 5 (Next Lecture)Outline for Lecture 5 (Next Lecture)

Bag class definition/implementation detailsBag class definition/implementation details Inline functionsInline functions

constructor, sizeconstructor, size Other basic functions Other basic functions

insert, erase_one, erase, countinsert, erase_one, erase, count More advanced functions More advanced functions

operators +, +=, -operators +, +=, -

Time Analysis Time Analysis Big-O Big-O

Introduction to sequence Introduction to sequence

Page 68: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6868

Before Lecture 5Before Lecture 5

Reading Assignment: Chapter 3Reading Assignment: Chapter 3

Reminder: Programming assignment 1 is Reminder: Programming assignment 1 is due on Wednesdaydue on Wednesday

Page 69: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

6969

Outline for Lecture 5Outline for Lecture 5

Bag class definition/implementation detailsBag class definition/implementation details Inline functionsInline functions

constructor, sizeconstructor, size Other basic functions Other basic functions

insert, erase_one, erase, countinsert, erase_one, erase, count More advanced functions More advanced functions

operators +, +=, -operators +, +=, -

Time Analysis Time Analysis Big-O Big-O

Introduction to sequence Introduction to sequence

Page 70: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7070

Review: Container Classes Review: Container Classes

Page 71: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7171

A container class is a class that can hold a A container class is a class that can hold a collection of items.collection of items.

Container classes can be implemented with a C++ Container classes can be implemented with a C++ class.class.

The class is implemented with The class is implemented with a header file (containing documentation and the class a header file (containing documentation and the class

definition) definition) bag1.hbag1.h and and an implementation file (containing the implementations an implementation file (containing the implementations

of the member functions) of the member functions) bag1.cxxbag1.cxx.. Other details are given in Section 3.1Other details are given in Section 3.1

Review: Container Classes Review: Container Classes

Page 72: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7272

Review : Invariants of a classReview : Invariants of a class

Precondition and PostconditionPrecondition and Postcondition

The The invariant of the class invariant of the class

Value SemanticsValue Semantics

Page 73: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7373

Review : Invariants of a classReview : Invariants of a class

Precondition and PostconditionPrecondition and Postcondition contract for each function, for use of the functioncontract for each function, for use of the function document pre- and post- document pre- and post- in the header filein the header file

The The invariant of the class invariant of the class implicitimplicit part of pre- and post- so is not usually written as part of pre- and post- so is not usually written as

an an explicitexplicit part of pre- and post- part of pre- and post- about the private member variables, thus for about the private member variables, thus for

implementation, but not for how to use themimplementation, but not for how to use them documented documented in the implementation filein the implementation file

Value SemanticsValue Semantics both for implementation and for useboth for implementation and for use documented documented in the header filein the header file

Page 74: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7474

Default Constructor and Basic bag OperationsDefault Constructor and Basic bag Operations

bag()bag() {used = 0;}{used = 0;}

size_t size() const size_t size() const {return used;}{return used;}

class bag{public: static const size_t CAPACITY = 20; bag(); size_t size() const; bool erase_one(const int& entry); ...private: int data[CAPACITY]; size_t used;};

Page 75: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7575

Default Constructor and Basic bag OperationsDefault Constructor and Basic bag Operations

bag()bag() {used = 0;}{used = 0;}

size_t size() const size_t size() const {return used;}{return used;}

class bag{public: static const size_t CAPACITY = 20; bag() {used =0;} size_t size() const {return used;} bool erase_one(const int& entry); ...private: int data[CAPACITY]; size_t used;};

Question: What are Question: What are inline functions?inline functions?

Page 76: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7676

More bag OperationsMore bag Operations

void bag::erase(const int& target) void bag::erase(const int& target) void bag::insert(const int& entry) void bag::insert(const int& entry)

{assert(size()<CAPACITY);{assert(size()<CAPACITY); data[used]=entry;data[used]=entry; used++;used++;}}

bool bag::erase_one(const int& target)bool bag::erase_one(const int& target) size_t bag::count(const int& target) constsize_t bag::count(const int& target) const

Page 77: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7777

Append Operator +=Append Operator +=

void bag::operator+=(const bag& addend)// Precondition:// Postcondition:

{

}

Page 78: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7878

Append Operator +=Append Operator +=

void bag::operator+=(const bag& addend)// Precondition: size( ) + addend.size( ) <= CAPACITY.// Postcondition: Each item in addend has been added to

this bag.

{

}

Page 79: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

7979

Append Operator +=Append Operator +=

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; // Question : What will happen if you call: b += b;// Solution : Can you fix the bug in the code?

Page 80: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8080

Append Operator +=Append Operator +=

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>);

Page 81: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8181

Union Operator +Union Operator +

// NONMEMBER FUNCTION for the bag class:bag operator+(const bag& b1, const bag& b2)// Precondition:// Postcondition:

{

}

Page 82: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8282

Union Operator +Union Operator +

// 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.

{

}

Page 83: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8383

Union Operator +Union Operator +

// 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 ?// Question : why operator+ is a nonmember function ?

Page 84: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8484

Subtract Operator -Subtract Operator -

// bag operator-(const bag& b1, const bag& b2);//precondition: //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 (ask yourself the following questions:)

1. If there is one copy of a target (say 4) in b2 but multiple copies of 4 in b1, how many copies of the target will be in the resulting bag?

2. If there is one copy of a target in b2, but the target is not in b1, how will it affect the resulting bag?

3. Is operator- a member function, nonmember function or friend function?

Page 85: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8585

Subtract Operator -Subtract Operator -

// 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 (3 minutes)// 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 86: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8686

Subtract Operator -Subtract Operator -

// 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 size for (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 87: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8787

Other Kinds of BagsOther Kinds of Bags

In this example, we have implemented a In this example, we have implemented a bag containing bag containing integersintegers..

But we could have had a bag of But we could have had a bag of float float numbersnumbers, a bag of , a bag of characterscharacters, a bag of , a bag of stringsstrings . . . . . .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 88: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8888

Time Analysis of the Bag ClassTime Analysis of the Bag Class

Default constructor Default constructor count – the number of occurrencecount – the number of occurrence

erase_one – remove one from the bagerase_one – remove one from the bag

erase – remove all erase – remove all

Page 89: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

8989

Time Analysis of the Bag ClassTime Analysis of the Bag Class

+= - append+= - append

b1+b2 - unionb1+b2 - union

insert – add one item insert – add one item

size – number of items in the bagsize – number of items in the bag

Page 90: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

9090

What’s the most important, then?What’s the most important, then?

Concept of Container ClassesConcept of Container Classes the bag class is not particularly importantthe bag class is not particularly important

Other kinds of container classesOther kinds of container classes sequencesequence – similar to a bag, both contain a bunch of – similar to a bag, both contain a bunch of

items. But unlike a bag, the items in a sequence is items. But unlike a bag, the items in a sequence is arranged in order.arranged in order.

will be the topic of our will be the topic of our second assignmentsecond assignment– paying – paying attention to the differences attention to the differences

index – have current, next, last, etcindex – have current, next, last, etc member functions and their implementation (e.g. insert, attach)member functions and their implementation (e.g. insert, attach) time analysis (insert)time analysis (insert)

Page 91: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

9191

A Quiz: Implement a member function of

the bag class (you have 5 – 10 minutes)

A Quiz: Implement a member function of

the bag class (you have 5 – 10 minutes)

bool bag::erase_one(const int& target)bool bag::erase_one(const int& target)

Page 92: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

9292

After Class…After Class…

Assignment 2 (online tonight)Assignment 2 (online tonight) due Thursday, Sep 28due Thursday, Sep 28 Reading: Chapter 3, Section 3.2-3.3Reading: Chapter 3, Section 3.2-3.3 especially the especially the sequence codesequence code

Self-Test ExercisesSelf-Test Exercises 1,3, 5,10,11,14,18-241,3, 5,10,11,14,18-24

Reading for next lecture Reading for next lecture Chapter 4, Section 4.1-4.2Chapter 4, Section 4.1-4.2

Page 93: 1 CSC211 Data Structures Lectures 4 & 5 Container Classes Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

9393

THE ENDTHE END

Presentation copyright 1997, Addison Wesley LongmanPresentation copyright 1997, Addison Wesley LongmanFor use with For use with Data Structures and Other Objects Using C++Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.by Michael Main and Walter Savitch.

Some artwork in the presentation is used with permission from Presentation Task ForceSome artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc.) and Corel Gallery Clipart Catalog (copyright(copyright New Vision Technologies Inc.) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc., Archive Arts, Cartesia Software, Image ClubCorel Corporation, 3G Graphics Inc., Archive Arts, Cartesia Software, Image ClubGraphics Inc., One Mile Up Inc., TechPool Studios, Totem Graphics Inc.).Graphics Inc., One Mile Up Inc., TechPool Studios, Totem Graphics Inc.).

Students and instructors who use Students and instructors who use Data Structures and Other ObjectsData Structures and Other Objects Using C++ Using C++ arearewelcome to use this presentation however they see fit, so long as this copyright notice welcome to use this presentation however they see fit, so long as this copyright notice remains intact.remains intact.

This lecture was modified from the above noticed presentation with new This lecture was modified from the above noticed presentation with new conventions provided in the second edition (2001) of the textbook and conventions provided in the second edition (2001) of the textbook and other minor changes -- Z. Zhu, 2002-2006, CCNYother minor changes -- Z. Zhu, 2002-2006, CCNY