COSC 220 Computer Science II Data Structures and

  • Slides: 66
Download presentation
COSC 220 Computer Science II: Data Structures and Algorithm Analysis n Instructor: Dr. Enyue

COSC 220 Computer Science II: Data Structures and Algorithm Analysis n Instructor: Dr. Enyue (Annie) Lu n Office room: HS 114 n Office hours: http: //faculty. salisbury. edu/~ealu/schedule. htm n Email: ealu@salisbury. edu n Course information: n Website: http: //faculty. salisbury. edu/~ealu/COSC 220/cosc 220. html n Myclasses@SU 1

Prerequisite: n Computer Science I (COSC 120) with a grade of C or better;

Prerequisite: n Computer Science I (COSC 120) with a grade of C or better; and n Discrete Mathematics (MATH 210) with a grade of C or better. MATH 210 may be taken concurrently. n If you have any question about prerequisite, talk to you instructor n DON’T TAKE THE COURSE IF YOU DON’T SATISFIED THE PREREQUISITE 2

Course overview n Chapters 14 -20, handouts n ADT, C++ classes/objects, APIs, pointers and

Course overview n Chapters 14 -20, handouts n ADT, C++ classes/objects, APIs, pointers and dynamic memory, object composition, operator overloading n Inheritance and abstract classes n Exceptions, STL containers, template classes, vectors n list container, iterators n Linked lists n Stacks, Queues and priority queues n Recursion n Binary trees n Introduction to Algorithms 3

Chapter 1 Introduction to Data Structure 4

Chapter 1 Introduction to Data Structure 4

Outline ADT’s Classes -Declaration -Private/Public Sections -Constructor (default constructor, member initialization list) -Constant member

Outline ADT’s Classes -Declaration -Private/Public Sections -Constructor (default constructor, member initialization list) -Constant member function -Argument (constant reference argument) -inline function -anonymous object Separate Compilation and Namespaces API 5

Data Structure n A data structure is a systematic way of organizing and accessing

Data Structure n A data structure is a systematic way of organizing and accessing data. n Programmer-defined data structures bundle data with operations that manipulate the data. n Data examples: n Primitive data type (part of a language definition) n Structure that groups together different but related data types (defined by a user/programmer) n The structures, called containers have operations to access, insert, and remove items from the collection. n When a user wants to define their own data structure, a model called ADT (abstract data type) is usually created first 6

Abstract Data Type (ADT) n A model used to understand the design of a

Abstract Data Type (ADT) n A model used to understand the design of a data structure. n n The type of data stored The operations that support them n “Abstract” implies that ADT is implementation- independent. It describes “what” instead of “how” n n A class with a well-defined interface, but implementation details are hidden from other classes Interfaces of a class: prototypes for public methods, plus descriptions of their behaviors n For an ADT, we need to create a representation of the data and an implementation for the operations 7

Abstract Data Types ADT Operation Description n operation. Name: Action statement that specifies the

Abstract Data Types ADT Operation Description n operation. Name: Action statement that specifies the input parameters, the type of operation on the elements of the data structure, and the output parameter n Preconditions: Necessary conditions that must apply to the input parameters and the current state of the object to allow successful execution of the operation. n Postconditions: Changes in the data of the structure caused by the operation. 8

C++ class n C++ class construct provides a physical realization of an ADT n

C++ class n C++ class construct provides a physical realization of an ADT n C++ class construct syntax n Class declaration n A blueprint of user defined data type n “what” in terms of programming language n Class implementation n Build the class according to “blueprint” in programming language 9

Classes Declaration ( class. Nme. h) 10

Classes Declaration ( class. Nme. h) 10

Classes ( Private/Public Sections) n The public and private sections in a class declaration

Classes ( Private/Public Sections) n The public and private sections in a class declaration allow program statements outside the class different access to the class members. “private” can be omitted if it goes before “public”. Anything before “public” is “private” by default n Everything defined in class can be accessed by all class members n Only things defined in “public” can be accessed by programs outside the class n 11

Classes ( Private/Public Sections) 12

Classes ( Private/Public Sections) 12

Classes ( Private/Public Sections) n Public members of a class are the interface of

Classes ( Private/Public Sections) n Public members of a class are the interface of the object to the program. n Any statement in a program block that declares an object can access a public member of the object 13

Classes ( Private/Public Sections) n The private section typically contains the data values of

Classes ( Private/Public Sections) n The private section typically contains the data values of the object and utility functions that support class implementation. n Only member functions of the class may access elements in the private section. 14

Class implementation (member function) (class. Name. cpp) return. Type class. Name: : function. Name(argument

Class implementation (member function) (class. Name. cpp) return. Type class. Name: : function. Name(argument list) { <C++ statements> } n The symbol ": : " signals the compiler that the function is a member of the class. n The statements in the function body may access all of the public and private members of the class. n The “: : ” operator allows you to code a member function like any other free function. 15

Constant member function n If an operation does not change any the data in

Constant member function n If an operation does not change any the data in the object, append the keyword “const” to the prototype n Compiler outputs an error message whenever a statement attempts to update a data member int get. Hour( )const; 16

Accessors and Mutators n Accessor: a member function that gets a value from a

Accessors and Mutators n Accessor: a member function that gets a value from a class’s member variable but does not change it n Mutators: a member function that stores a value in a class’s member variable or change the value of member variable in some other way 17

Avoiding stale data n Stale data: An item whose value is dependent on other

Avoiding stale data n Stale data: An item whose value is dependent on other data and that item is not updated when the other data are changed n e. g. area of the rectangle 18

Value Argument: Passing Data by Value n A function call makes a copy of

Value Argument: Passing Data by Value n A function call makes a copy of the contents of the actual argument and assigns it to the formal argument n Parameter cannot access the original argument n Changes to the parameter in the function do not affect the value of the argument back in the calling function 19

Reference Argument: Using Reference Variables as Parameters n Passing location of the actual argument

Reference Argument: Using Reference Variables as Parameters n Passing location of the actual argument n allow a function to access the parameter’s original argument. Changes to the parameter are also made to the argument. n Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument n Allows the function to modify values stored in the calling environment n Provides a way for the function to ‘return’ > 1 value 20

Passing by Reference n A reference variable is an alias for another variable n

Passing by Reference n A reference variable is an alias for another variable n Defined with an ampersand (&) void get. Dimensions(int&, int&); n Changes to a reference variable are made to the variable it refers to n Use reference variables to implement passing parameters by reference 21

Reference Variable Notes n Each reference parameter must contain & n Space between type

Reference Variable Notes n Each reference parameter must contain & n Space between type and & is unimportant n Must use & in both prototype and header n Argument passed to reference parameter must be a variable – cannot be an expression or constant n Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value n constant reference: the function has read-only access to the data. time 24 duration(const time 24& t); 22

Inline function n A member function can be implemented inside the class declaration by

Inline function n A member function can be implemented inside the class declaration by using inline code. The semicolon (; ) in the function prototype is replaced by the function body. n The compiler inserts the statements in the function body in place of the function, avoiding the function call and return mechanism. n n The process provides efficiency at the expense of increased code size. 23

Constructor n A special member function that initialize the object n Has the same

Constructor n A special member function that initialize the object n Has the same name as class name n Has no return type ( not even void ) n is called when an object is created, Called automatically n Programmers can create a constructor that takes arguments: n indicate parameters in prototype( if used ) definition n provide arguments when object is created: 24

Default constructor n a constructor that can be called with no arguments. class Fred

Default constructor n a constructor that can be called with no arguments. class Fred { public: Fred(); // Default constructor: can be called with no args . . . }; n a constructor that can take arguments, provided they are given default values: class Fred { public: Fred(int i=3, int j=5); // Default constructor: can be called with no args . . . }; 25

Member Initialization List n Optional member initialization list of data- member (initial value): to

Member Initialization List n Optional member initialization list of data- member (initial value): to assign initial values to the data members time 24: : time 24(int h, int m): hour(h), minute(m) { …… } 26

Destructor n A special member function automatically called when n n an object is

Destructor n A special member function automatically called when n n an object is destroyed Destructor name is ~classname, Has no return type; takes no arguments If constructor allocates dynamic memory, destructor should release it Only 1 destructor per class, i. e. , it cannot be overloaded All classes have default destructor given by the language n Programmers can overwrite the default destructor 27

Anonymous object n Anonymous object: the object is not associated with an identifier in

Anonymous object n Anonymous object: the object is not associated with an identifier in a declaration time 24: : duration(const time 24& t) { // convert current time and time t to minutes int curr. Time = hour * 60 + minute; int t. Time = t. hour * 60 + t. minute; // if t is earlier than the current time, throw an exception if (t. Time < curr. Time) throw range. Error( "time 24 duration(): argument is an earlier time"); else // create an anonymous object as the return value return time 24(0, t. Time-curr. Time); } 28

Use of C++ classes in programs n Include the header file of class n

Use of C++ classes in programs n Include the header file of class n Define an object of type “class. Name” n Use dot operator to access the public member functions n Example: Class rectangle (d_rect. h) 29

The time 24 ADT n Consider a data structure that uses integer values for

The time 24 ADT n Consider a data structure that uses integer values for hours and minutes to represent the time of data in a 24 hour clock n n Hours are in the range 0 to 23 Minutes are in the range 0 to 59 n Data members: n Hours (0 -23) n Minutes (0 -59) n Operations: accept data, carry out calculation, return a value. 30

The time 24 ADT n add. Time(m): update the current time by adding m

The time 24 ADT n add. Time(m): update the current time by adding m minutes and adjust the hours and minutes to fall in their specified range n Postcondition: the new time is m minutes later Operation: (a) 9 30 10 20 add. Time (50) Time (Before) Time (After) 31

The time 24 ADT n duration(t): Time t is an input parameter. Measure the

The time 24 ADT n duration(t): Time t is an input parameter. Measure the length of time from the current time to time t and return the result as a time 24 value. n (b) Precondition: Time t must not be earlier than the current time Operation: duration (t ) 14 45 Current Time 16 15 Time t 1 30 Return time 32

The time 24 ADT n read. Time(): Input from the keyboard the hours and

The time 24 ADT n read. Time(): Input from the keyboard the hours and minutes for time 24 object, using the format hh: mm n Postcondition: Set the hour and minute values of the time to hh and mm respectively. If either of the values is out of its designated range, the operation makes the appropriate adjustments. For instance, input 9: 75 is stored as 10: 15 n write. Time(): display on the screen the current time in the form hh: mm n get. Hour(): return the hour value for the current time n get. Minute(): return the minute value for the current time 33

Runtime execution of the time 24 function add. Time() 34

Runtime execution of the time 24 function add. Time() 34

n Class time 24 (d_time 24. h) n time 24 API 35

n Class time 24 (d_time 24. h) n time 24 API 35

Instance and Static Members n instance variable: a member variable in a class. Each

Instance and Static Members n instance variable: a member variable in a class. Each object has its own copy. n static variable: one variable shared among all objects of a class n static member function: can be used to access static member variable; can be called before any objects are defined

static member variable 1) Declare with keyword static : class Int. Val { public:

static member variable 1) Declare with keyword static : class Int. Val { public: int. Val(int val = 0) { value = val; val. Count++; } int get. Val(); void set. Val(int); private: int value; static int val. Count; }

static member variable 2) Define outside of class: int Int. Val: : val. Count

static member variable 2) Define outside of class: int Int. Val: : val. Count = 0; 3) Can be accessed or modified by any object of the class: Int. Val val 1, val 2; val. Count 2 val 1 value val 2 value

static member function n Declared with static before return type: static int get. Val()

static member function n Declared with static before return type: static int get. Val() { return val. Count; } n Can only access static member data n Can be called independent of objects: cout << "There are " << Int. Val: : get. Val() << " objectsn"; n Example 1: Tree. h, Prog 14 -1,

Separate Compilation and Namespaces 40

Separate Compilation and Namespaces 40

Separate Compilation n C++ allows you to divide a program into parts n Each

Separate Compilation n C++ allows you to divide a program into parts n Each part can be stored in a separate file n Each part can be compiled separately n A class definition can be stored separately from a program. n This allows you to use the class in multiple programs 41

ADT n An ADT is a class defined to separate the interface and the

ADT n An ADT is a class defined to separate the interface and the implementation All member variables are private n The class definition along with the function and operator declarations are grouped together as the interface of the ADT n Group the implementation of the operations together and make them unavailable to the programmer using the ADT n 42

The ADT Interface n The interface of the ADT includes n The class definition

The ADT Interface n The interface of the ADT includes n The class definition n The declarations of the basic operations which can be one of the following n n n Public member functions Friend functions Ordinary functions Overloaded operators The function comments 43

The ADT Implementation n The implementation of the ADT includes n The function definitions

The ADT Implementation n The implementation of the ADT includes n The function definitions n n The public member functions The private member functions Non-member functions Private helper functions Overloaded operator definitions n Member variables n Other items required by the definitions n 44

Separate Files n In C++ the ADT interface and implementation can be stored in

Separate Files n In C++ the ADT interface and implementation can be stored in separate files The interface file stores the ADT interface n The implementation file stores the ADT implementation n 45

A Minor Compromise n The public part of the class definition is part of

A Minor Compromise n The public part of the class definition is part of the ADT interface n The private part of the class definition is part of the ADT implementation n This would hide it from those using the ADT n C++ does not allow splitting the public and private parts of the class definition across files n The entire class definition is usually in the interface file 46

Running The Program n Basic steps required to run a program: (Details vary from

Running The Program n Basic steps required to run a program: (Details vary from system to system!) n Compile the implementation file n Compile the application file n Link the files to create an executable program using a utility called a linker n Linking is often done automatically 47

Why Three Files? n Using separate files permits n The ADT to be used

Why Three Files? n Using separate files permits n The ADT to be used in other programs without rewriting the definition of the class for each n Implementation file to be compiled once even if multiple programs use the ADT n Changing the implementation file does not require changing the program using the ADT 48

Reusable Components n An ADT coded in separate files can be used over and

Reusable Components n An ADT coded in separate files can be used over and over n The reusability of such an ADT class n Saves effort since it does not need to be n n Redesigned Recoded Retested Is likely to result in more reliable components 49

Multiple Classes n A program may use several classes n Each could be stored

Multiple Classes n A program may use several classes n Each could be stored in its own interface and implementation files n Some files can "include" other files, that include still others It is possible that the same interface file could be included in multiple files n C++ does not allow multiple declarations of a class n The #ifndef directive can be used to prevent multiple declarations of a class n 50

Introduction to #ifndef n To prevent multiple declarations of a class, we can use

Introduction to #ifndef n To prevent multiple declarations of a class, we can use these directives: #define DTIME_H adds DTIME_H to a list indicating DTIME_H has been seen n #ifndef DTIME_H checks to see if DTIME_H has been defined n #endif If DTIME_H has been defined, skip to #endif n 51

Using #ifndef n Consider this code in the interface file: false true #ifndef DTIME_H

Using #ifndef n Consider this code in the interface file: false true #ifndef DTIME_H #define DTIME_H < The Digital. Time class definition goes here> #endif The first time a #include "dtime. h" is found, DTIME_H and the class are defined n The next time a #include "dtime. h" is found, all lines between #ifndef and #endif are skipped n 52

Why DTIME_H? n DTIME_H is the normal convention for creating an identifier to use

Why DTIME_H? n DTIME_H is the normal convention for creating an identifier to use with ifndef It is the file name in all caps n Use ' _ ' instead of '. ' n n You may use any other identifier, but will make your code more difficult to read 53

Namespaces n A namespace is a collection of name definitions, such as class definitions

Namespaces n A namespace is a collection of name definitions, such as class definitions and variable declarations If a program uses classes and functions written by different programmers, it may be that the same name is used for different things n Namespaces help us deal with this problem n 54

Standard Namespace n The standard namespace: std n Most common library features live in

Standard Namespace n The standard namespace: std n Most common library features live in the std namespace; to use them you need to prepend “std: : ” onto their names: e. g. , std: : cout, std: : cin, std: : endl, std: : string, std: : vector<string>, . . . n. . . or. . . you can cheat, and put this line near the beginning of your files: using namespace std; 55

The Using Directive n #include <iostream> places names such as cin and cout in

The Using Directive n #include <iostream> places names such as cin and cout in the std namespace n The program does not know about names in the std namespace until you add using namespace std; (if you do not use the std namespace, you can define cin and cout to behave differently) 56

The Global Namespace n Code you write is in a namespace n it is

The Global Namespace n Code you write is in a namespace n it is in the global namespace unless you specify a namespace n The global namespace does not require the using directive 57

Name Conflicts n If the same name is used in two namespaces n The

Name Conflicts n If the same name is used in two namespaces n The namespaces cannot be used at the same time n Example: If my_function is defined in namespaces ns 1 and ns 2, the two versions of my_function could be used in one program by using local using directives this way: { using namespace ns 1; my_function( ); } { using namespace ns 2; my_function( ); } 58

Scope Rules For using n A block is a list of statements enclosed in

Scope Rules For using n A block is a list of statements enclosed in { }s n The scope of a using directive is the block in which it appears n A using directive placed at the beginning of a file, outside any block, applies to the entire file 59

§- Application Programming Interface: Application Programming Interface - Allows other programmers to use the

§- Application Programming Interface: Application Programming Interface - Allows other programmers to use the public interface of the class without having to view the technical details of the class declaration or implementation. 60 60

API ( Constructor ) CLASS class. Name Constructors “<file>. h” class. Name(<arguments>); Initializes the

API ( Constructor ) CLASS class. Name Constructors “<file>. h” class. Name(<arguments>); Initializes the attributes of the object Postconditions: Initial status of the object 61

API ( Operations ) CLASS class. Name Operations “<file>. h” return. Type function. Name(argument

API ( Operations ) CLASS class. Name Operations “<file>. h” return. Type function. Name(argument list); Description of the action of the function and any return value Preconditions: Necessary state of the object before executing the operation. Any exceptions that are thrown when an error is detected. Postconditions: State of the data items in the object after executing the operation …. 62

The time 24 API Application n// the program uses time 24 objects to compute

The time 24 API Application n// the program uses time 24 objects to compute the cost of n// parking a car in a public garage at the rate is $6. 00 per hour. n// after the user inputs the times at which a customer enters and n// exits the garage, the program outputs a receipt that includes n// the enter and exit times, the length of time the car is parked n// and the total charges Example: prg 1_1. cpp 63

ADT §- An ADT provides simple and clear description of: 1) the input to

ADT §- An ADT provides simple and clear description of: 1) the input to an operation. 2) the action of the operation. 3) its return type. §- Preconditions: Part of the description of an Preconditions operation. A listing of the conditions that must apply in order for the operation to execute successfully. §- Postconditions: Indicate changes to the object's Postconditions data caused by the operation. Necessary because operations often alter the value of data. 64 64

ADT §- The private section of a class contains the data and operations that

ADT §- The private section of a class contains the data and operations that the public member functions use in their implementation. §- The splitting of a class into public and private parts is known as information hiding. §- A class encapsulates information by bundling the data items and operations within an object. 65 65

ADT §- The implementation of C++ class member functions is different from the implementation

ADT §- The implementation of C++ class member functions is different from the implementation of free functions. - Each function name must include the class scope operator : : that designates class membership. : : §- The constructor is a special function with no return type. - The constructor initializes the data members of the class by using its initialization list. 66 66