660 likes | 672 Views
COSC 220 Computer Science II: Data Structures and Algorithm Analysis. Instructor: Dr. Enyue (Annie) Lu Office room: HS114 Office hours: http://faculty.salisbury.edu/~ealu/schedule.htm Email: ealu@salisbury.edu Course information:
E N D
COSC 220 Computer Science II: Data Structures and Algorithm Analysis • Instructor: Dr. Enyue (Annie) Lu • Office room: HS114 • Office hours: http://faculty.salisbury.edu/~ealu/schedule.htm • Email: ealu@salisbury.edu • Course information: • Website:http://faculty.salisbury.edu/~ealu/COSC220/cosc220.html • Myclasses@SU
Prerequisite: • Computer Science I (COSC 120) with a grade of C or better; and • Discrete Mathematics (MATH 210) with a grade of C or better. MATH 210 may be taken concurrently. • If you have any question about prerequisite, talk to you instructor • DON’TTAKE THE COURSE IF YOU DON’T SATISFIED THE PREREQUISITE
Course overview • Chapters 14-20, handouts • ADT, C++ classes/objects, APIs, pointers and dynamic memory, object composition, operator overloading • Inheritance and abstract classes • Exceptions, STL containers, template classes, vectors • list container, iterators • Linked lists • Stacks, Queues and priority queues • Recursion • Binary trees • Introduction to Algorithms
Chapter 1 Introduction to Data Structure
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
Data Structure • A data structure is a systematic way of organizing and accessing data. • Programmer-defined data structures bundle data with operations that manipulate the data. • Data examples: • Primitive data type (part of a language definition) • Structure that groups together different but related data types (defined by a user/programmer) • The structures, called containers have operations to access, insert, and remove items from the collection. • When a user wants to define their own data structure, a model called ADT (abstract data type) is usually created first
Abstract Data Type (ADT) • A model used to understand the design of a data structure. • The type of data stored • The operations that support them • “Abstract” implies that ADT is implementation-independent. It describes “what” instead of “how” • 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 • For an ADT, we need to create a representation of the data and an implementation for the operations
Abstract Data Types ADT Operation Description • operationName: Action statement that specifies the input parameters, the type of operation on the elements of the data structure, and the output parameter • Preconditions: Necessary conditions that must apply to the input parameters and the current state of the object to allow successful execution of the operation. • Postconditions: Changes in the data of the structure caused by the operation.
C++ class • C++ class construct provides a physical realization of an ADT • C++ class construct syntax • Class declaration • A blueprint of user defined data type • “what” in terms of programming language • Class implementation • Build the class according to “blueprint” in programming language
Classes ( Private/Public Sections) • 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 • Everything defined in class can be accessed by all class members • Only things defined in “public” can be accessed by programs outside the class
Classes ( Private/Public Sections) • Public members of a class are the interface of the object to the program. • Any statement in a program block that declares an object can access a public member of the object
Classes ( Private/Public Sections) • The private section typically contains the data values of the object and utility functions that support class implementation. • Only member functions of the class may access elements in the private section.
Class implementation (member function) (className.cpp) returnType className::functionName(argument list) { <C++ statements> } • The symbol "::" signals the compiler that the function is a member of the class. • The statements in the function body may access all of the public and private members of the class. • The “::” operator allows you to code a member function like any other free function.
Constant member function • If an operation does not change any the data in the object, append the keyword “const” to the prototype • Compiler outputs an error message whenever a statement attempts to update a data member int getHour( )const;
Accessors and Mutators • Accessor: a member function that gets a value from a class’s member variable but does not change it • 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
Avoiding stale data • Stale data: An item whose value is dependent on other data and that item is not updated when the other data are changed • e.g. area of the rectangle
Value Argument: Passing Data by Value • A function call makes a copy of the contents of the actual argument and assigns it to the formal argument • Parameter cannot access the original argument • Changes to the parameter in the function do not affect the value of the argument back in the calling function
Reference Argument: Using Reference Variables as Parameters • Passing location of the actual argument • allow a function to access the parameter’s original argument. Changes to the parameter are also made to the argument. • Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument • Allows the function to modify values stored in the calling environment • Provides a way for the function to ‘return’ > 1 value
Passing by Reference • A reference variable is an alias for another variable • Defined with an ampersand (&) void getDimensions(int&, int&); • Changes to a reference variable are made to the variable it refers to • Use reference variables to implement passing parameters by reference
Reference Variable Notes • Each reference parameter must contain & • Space between type and & is unimportant • Must use & in both prototype and header • Argument passed to reference parameter must be a variable – cannot be an expression or constant • Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value • constant reference: the function has read-only access to the data. time24 duration(const time24& t);
Inline function • 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. • The compiler inserts the statements in the function body in place of the function, avoiding the function call and return mechanism. • The process provides efficiency at the expense of increased code size.
Constructor • A special member function that initialize the object • Has the same name as class name • Has no return type ( not even void ) • is called when an object is created, Called automatically • Programmers can create a constructor that takes arguments: • indicate parameters in prototype( if used ) definition • provide arguments when object is created:
Default constructor • a constructor that can be called with no arguments. class Fred { public: Fred(); // Default constructor: can be called with no args... }; • 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... };
Member Initialization List • Optional member initialization list of data-member (initial value): to assign initial values to the data members time24::time24(int h, int m): hour(h),minute(m) { …… }
Destructor • A special member function automatically called when 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 • Programmers can overwrite the default destructor
Anonymous object • Anonymous object: the object is not associated with an identifier in a declaration time24 time24::duration(const time24& t) { // convert current time and time t to minutes int currTime = hour * 60 + minute; int tTime = t.hour * 60 + t.minute; // if t is earlier than the current time, throw an exception if (tTime < currTime) throw rangeError( "time24 duration(): argument is an earlier time"); else // create an anonymous object as the return value return time24(0, tTime-currTime); }
Use of C++ classes in programs • Include the header file of class • Define an object of type “className” • Use dot operator to access the public member functions • Example: Class rectangle (d_rect.h)
The time24 ADT • Consider a data structure that uses integer values for hours and minutes to represent the time of data in a 24 hour clock • Hours are in the range 0 to 23 • Minutes are in the range 0 to 59 • Data members: • Hours (0-23) • Minutes (0-59) • Operations: accept data, carry out calculation, return a value.
Operation: 9 30 10 20 (a) addTime (50) Time (Before) Time (After) The time24 ADT • addTime(m): update the current time by adding m minutes and adjust the hours and minutes to fall in their specified range • Postcondition: the new time is m minutes later
The time24 ADT • 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 time24 value. • Precondition: Time t must not be earlier than the current time Operation: 45 14 1 30 16 15 (b) duration (t ) Current Time Return time Time t
The time24 ADT • readTime(): Input from the keyboard the hours and minutes for time24 object, using the format hh:mm • 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 • writeTime(): display on the screen the current time in the form hh:mm • getHour(): return the hour value for the current time • getMinute(): return the minute value for the current time
Class time24 (d_time24.h) • time24 API
Instance and Static Members • instance variable: a member variable in a class. Each object has its own copy. • static variable: one variable shared among all objects of a class • 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 IntVal { public: intVal(int val = 0) { value = val; valCount++; } int getVal(); void setVal(int); private: int value; static int valCount; }
static member variable 2) Define outside of class: int IntVal::valCount = 0; • Can be accessed or modified by any object of the class: IntVal val1, val2; valCount 2 val1 val2 value value
static member function • Declared with static before return type: static int getVal() { return valCount; } • Can only access static member data • Can be called independent of objects: cout << "There are " << IntVal::getVal() << " objects\n"; • Example 1: Tree.h, Prog14-1,
Separate Compilation • C++ allows you to divide a program into parts • Each part can be stored in a separate file • Each part can be compiled separately • A class definition can be stored separately from a program. • This allows you to use the class in multiple programs
ADT • An ADT is a class defined to separate theinterface and the implementation • All member variables are private • The class definition along with the function and operator declarations are grouped together as the interface of the ADT • Group the implementation of the operations together and make them unavailable to the programmer using the ADT
The ADT Interface • The interface of the ADT includes • The class definition • The declarations of the basic operations which can be one of the following • Public member functions • Friend functions • Ordinary functions • Overloaded operators • The function comments
The ADT Implementation • The implementation of the ADT includes • The function definitions • The public member functions • The private member functions • Non-member functions • Private helper functions • Overloaded operator definitions • Member variables • Other items required by the definitions
Separate Files • In C++ the ADT interface and implementation can be stored in separate files • The interface file stores the ADT interface • The implementation file stores the ADT implementation
A Minor Compromise • The public part of the class definition is part of the ADT interface • The private part of the class definition is part of the ADT implementation • This would hide it from those using the ADT • C++ does not allow splitting the public andprivate parts of the class definition across files • The entire class definition is usually in the interface file
Running The Program • Basic steps required to run a program:(Details vary from system to system!) • Compile the implementation file • Compile the application file • Link the files to create an executable program using a utility called a linker • Linking is often done automatically
Why Three Files? • Using separate files permits • The ADT to be used in other programs withoutrewriting the definition of the class for each • Implementation file to be compiled once even if multiple programs use the ADT • Changing the implementation file does not require changing the program using the ADT
Reusable Components • An ADT coded in separate files can be used over and over • The reusability of such an ADT class • Saves effort since it does not need to be • Redesigned • Recoded • Retested • Is likely to result in more reliable components
Multiple Classes • A program may use several classes • Each could be stored in its own interface and implementation files • Some files can "include" other files, that include still others • It is possible that the same interface file could be included in multiple files • C++ does not allow multiple declarations of a class • The #ifndef directive can be used to prevent multiple declarations of a class