1 / 66

COSC 220 Computer Science II: Data Structures and Algorithm Analysis

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:

abulkley
Download Presentation

COSC 220 Computer Science II: Data Structures and Algorithm Analysis

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. Chapter 1 Introduction to Data Structure

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

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

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

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

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

  10. Classes Declaration ( classNme.h)

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

  12. Classes ( Private/Public Sections)

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

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

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

  16. 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;

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

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

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

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

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

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

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

  24. 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:

  25. 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... };

  26. 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) { …… }

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

  28. 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); }

  29. 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)

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

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

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

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

  34. Runtime execution of the time24 function addTime()

  35. Class time24 (d_time24.h) • time24 API

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

  37. 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; }

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

  39. 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,

  40. Separate Compilationand Namespaces

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

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

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

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

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

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

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

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

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

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

More Related