900 likes | 1.07k Views
CSc212 AB Data Structures Lecture 10. M. P. Johnson mpjohnson@gmail.com http://www-cs.ccny.cuny.edu/~mjohnson/212/ City College of New York, Spring, 2005. Outline: review session. Review some material Interspersed with sample problems Discuss homework Discuss exam topics
E N D
CSc212AB Data StructuresLecture 10 M. P. Johnson mpjohnson@gmail.com http://www-cs.ccny.cuny.edu/~mjohnson/212/ City College of New York, Spring, 2005 M.P. Johnson, DS, CCNY, Spring 2005
Outline: review session • Review some material • Interspersed with sample problems • Discuss homework • Discuss exam topics • More sample problems • Take questions M.P. Johnson, DS, CCNY, Spring 2005
Chapter 1 • The Phases of Software Development • Basic design strategy • Pre-conditions and post-conditions • Run time analysis M.P. Johnson, DS, CCNY, Spring 2005
Basic Design Strategy • Basic Design Strategy – four steps (Reading: Ch.1 ) • Specify Input/Output (I/O) • Design data structures and algorithms • Implement in a language such as C++ • Test and debug the program (Reading Ch 1.3) • Design Technique • Decomposing the problem M.P. Johnson, DS, CCNY, Spring 2005
Specifications: pre and post-condition • Frequently a programmer must communicate precisely what a function accomplishes, without any indication of how the function does its work • One way to specify such requirements is with a pair of statements about the function. • The precondition statement indicates what must be true before the function is called. • The postcondition statement indicates what will be true when the function finishes its work. M.P. Johnson, DS, CCNY, Spring 2005
Run time analysis • Counts the number of basic operations of the program • Big-O Notation – the order of the algorithm • Use the largest term in a formula • Ignore the multiplicative constant • Worse case analysis M.P. Johnson, DS, CCNY, Spring 2005
Example Q: • Write the simplest big-O expression to describe the number of operations required for the following algorithm: for (i = 1; i < N; ++i) { ...statements that require exactly 7 operations... } M.P. Johnson, DS, CCNY, Spring 2005
Q • Write the simplest big-O expression to describe the number of operations required for the following algorithm: for (i = 1; i < N; ++i) { ...statements that require exactly N operations... } M.P. Johnson, DS, CCNY, Spring 2005
Q • Write the simplest big-O expression to describe the number of operations required for the following algorithm: for (i = 1; i < N; ++i) { ...statements that require exactly i operations... } M.P. Johnson, DS, CCNY, Spring 2005
Q • Which of these is used to stop the program execution when a precondition is not met. • A. assert(); • B. exit(); • C. return(); • D. void(); M.P. Johnson, DS, CCNY, Spring 2005
Q • Which of the following formulas in big-O notation best represent the expression n²+35n+6? • A. O(n³) • B. O(n²) • C. O(n) • D. O(42) M.P. Johnson, DS, CCNY, Spring 2005
Q • Answer true or false for this statement: True or false: An algorithm with complexity O(3n) takes at least 30 operations for every input of size n=10. • TRUE. • FALSE. M.P. Johnson, DS, CCNY, Spring 2005
Chapter 2 outline A Review of C++ Classes (Lecture 2) • OOP, ADTs and Classes • Class Definition, Implementation and Use • Constructors and Value Semantics More on Classes (Lecture 3) • Namespace and Documentation • Classes and Parameters (value, reference, const reference) • Operator Overloading M.P. Johnson, DS, CCNY, Spring 2005
Summary of classes • Classes have member variables and member functions. An object is a variable whose data type is a class. • You should know how to declare a new class type, how to implement its member functions, how to use the class type. • Frequently, the member functions of an class type place information in the member variables, or use information that's already in the member variables. M.P. Johnson, DS, CCNY, Spring 2005
Constructors • Constructor is a member function which • automatically called whenever a variable of the class is declared • the name must be the same as the class name • arguments must be given after the variable name (when declared) • A way to improve the initialize function • by providing an initialization function that is guaranteed to be called • You may declare as many constructors as you like – one for each different way of initializing an object • Each constructor must have a distinct parameter list so that the compiler can tell them part M.P. Johnson, DS, CCNY, Spring 2005
(Automatic) Default constructor • What happens if you write a class without any constructors? • The compiler automatically creates a simple default constructor • which only calls the default constructors for the member variables that are objects of some other classes • Programming Tip: Always provide your own constructors, and better with a default constructor M.P. Johnson, DS, CCNY, Spring 2005
Value semantic of a class • Value semantics determines how values are copied from one object to another • Consists of two operations in C++ • The assignment operator • The copy constructor • Document the value semantics • When you implement an ADT, the document should include a comment indicating that the value semantics is safe to use. M.P. Johnson, DS, CCNY, Spring 2005
Q: Constructors & assignment op • point p1; • // Default constructor • point p2(p1); • //Copy constructor • point p3 = p2; • //Copy constructor • p3 = p1; • //Assignment operator M.P. Johnson, DS, CCNY, Spring 2005
Classes and parameters • Default parameters • when no or only part of the parameters are provided in calling function • Types of parameters • value parameters • reference parameters • constant reference parameters • Return value is a class M.P. Johnson, DS, CCNY, Spring 2005
Default arguments • A default argument is a value that will be used for an argument when a programmer does not provide an actual argument when calling a function • Default arguments may be listed in the prototype of a function • Syntax: Type_name var_name = default_value M.P. Johnson, DS, CCNY, Spring 2005
Value parameters • A value parameter is declared by writing • type-nameparameter-name • Any change made to the formal parameter within the body of the function does not change the actual argument from the calling program • The formal parameter is implemented as a local variable of the function, and the class’s copy constructoris used to initialize the formal parameter as a copy of the actual argument M.P. Johnson, DS, CCNY, Spring 2005
Reference parameters • A reference parameter is declared by writing • type-name ¶meter-name • Any use of the formal parameter within the body of the function will access the actual argument from the calling program; change made to the parameter in the body of the function will alter the argument • The formal parameter is merely another name of the argument used in the body of the function! M.P. Johnson, DS, CCNY, Spring 2005
const reference parameters • A const reference parameter is declared by writing • const type-name ¶meter-name • A solution that provides the efficiency of a reference parameter along with the security of a value parameter. • Example ( newpoint.cxx) • double distance (const point& p1, const point& p2) • point p1 and p2 cannot be changed (TEST!) M.P. Johnson, DS, CCNY, Spring 2005
Class as return value • The type of a function’s return value may be a class • Often the return value will be stored in a local variable of the function (such as midpoint), but not always (could be in a formal parameter) • C++ return statement uses the copy constructor to copy the function’s return value to a temporary location before returning the value to the calling program • Example ( Ch 2.4, Look into newpoint.cxx) • point middle(const point& p1, const point& p2) M.P. Johnson, DS, CCNY, Spring 2005
Operator Overloading • Binary functions and binary operators • Overloading arithmetic operations • Overloading binary comparison operations • Overloading input/output functions • Friend functions – when to use M.P. Johnson, DS, CCNY, Spring 2005
Chapter 2 sample questions • Write one clear sentence telling me when it would be appropriate to use a const reference parameter. • Suppose that you define a new class called foo. For two foo objects x and y, you would like the expression x+y to be a new foo object. What is the prototype of the function that you must write to enable expressions such as x+y? . M.P. Johnson, DS, CCNY, Spring 2005
Q • Which kind of functions can access private member variables of a class? • A. Friend functions of the class • B. Private member functions of the class • C. Public member functions of the class • D. All of the above • E. None of the above M.P. Johnson, DS, CCNY, Spring 2005
Q • Here is the start of a class declaration: class foo { public: void x(foo f); void y(const foo f); void z(foo f) const; ... Which of the three member functions can alter the PRIVATE member variables of the foo object that activates the function? M.P. Johnson, DS, CCNY, Spring 2005
Chapter 3 – container classes • A container classis a data type that is capable of holding a collection of items. • In C++, container classes can be implemented as a class, along with member functions to add, remove, and examine items. • Bag and sequence class using partially filled static array. M.P. Johnson, DS, CCNY, Spring 2005
The invariant of a class • Two rules for our bag implementation • The number of items in the bag is stored in the member variable used; • For an empty bag, we don’t care what is stored in any of data; for a non-empty bag, the items are stored in data[0] through data[used-1], and we don’t care what are stored in the rest of data. • The rules that dictate how the member variables of a (bag) class are used to represent a value (such as a bag of items) are called the invariant of the class M.P. Johnson, DS, CCNY, Spring 2005
run time analysis of the bag class • count – the number of occurrence • erase_one – remove one from the bag • erase – remove all • += - append • b1+b2 - union • insert – add one item • size – number of items in the bag M.P. Johnson, DS, CCNY, Spring 2005
Containers - summary • A container class is a class that can hold a collection of items. • Container classes can be implemented with a C++ class. • The class is implemented with • a header file (containing documentation and the class definition) bag1.h and • an implementation file (containing the implementations of the member functions) bag1.cxx. • Other details are given in Section 3.1, which you should read, especially the real bag code M.P. Johnson, DS, CCNY, Spring 2005
Chapter 3 – sample questions • Suppose that I have the following declarations: int data[100]; size_t i; Write a small segment of C++ code that will shift data[51]...data[99] down one spot to the locations data[50]...data[98]. The value of data[99] remains at its original value. M.P. Johnson, DS, CCNY, Spring 2005
Q • Suppose that the bag class is efficiently implemented with a fixed array with a capacity of 4000, as in Chapter 3 of the class text. We execute these statements: • bag b; • b.insert(5); • b.insert(4); • b.insert(6); • b.erase_one(5); • What are the values of used and data afterward? M.P. Johnson, DS, CCNY, Spring 2005
Chapter 4: pointers and dynamic arrays • Pointers • *(asterisk) and &(ampersand) operators • Dynamic Variables and new Operator • Dynamic Arrays and Dynamic Objects • Stack (local) vs. heap (dynamic) memory • Garbage Collection and delete Operator • Parameters revisited • Pointers and Arrays as Parameters M.P. Johnson, DS, CCNY, Spring 2005
Operator * Pointer declaration int *i_ptr; dereferencing operator cout << *i_ptr; Two different meanings! Operator & Reference parameter void funct(int& i); “address of ” operator i_ptr = &i; Just coincidence? Will see in parameter passing Operators * and & M.P. Johnson, DS, CCNY, Spring 2005
Assignment Operators with Pointers • p1 = p2 • *p1 = *p2 M.P. Johnson, DS, CCNY, Spring 2005
Use array notation the 1st entry p1[0] = 18; the 3rd entry p1[2] = 20; the ith entry p1[i-1] = 19; Use pointer notation the 1st entry *p1 = 18; the 3rd entry *(p1+2) = 20; the ith entry *(p1+i-1) = 19; Accessing Dynamic Array M.P. Johnson, DS, CCNY, Spring 2005
Failure of the new Operator • Dynamic memory via new operator comes from heap of a program • Heap size from several K to 1GB, however fixed • Could run out of room therefore cause a bad_alloc exception • error message and program halts • Good practice 1: document which functions uses new • Good practice 2: garbage collection by delete operator M.P. Johnson, DS, CCNY, Spring 2005
new & delete • Release any dynamic memory (heap memory) that is no longer needed int *i_ptr; double *d_ptr; point *p_ptr; i_ptr = new int; d_ptr = new double[20]; p_ptr = new point(1, 2); //… … delete i_ptr; //empty brackets delete [] d_ptr; delete p_ptr; • Questions( true or false): • delete resets these pointers • delete removes dynamic objects pointed by the pointers • nothing happens to the pointers themselves X V V M.P. Johnson, DS, CCNY, Spring 2005
Pointers and Arrays as Parameters • Value parameters that are pointers • Array parameters • Pointers and arrays as const parameters • Reference parameters that are pointers M.P. Johnson, DS, CCNY, Spring 2005
Array Parameters • Compare ordinary and Dynamic arrays void make_all_20(int data[], size_t size) { for (int i = 0 ; i< size; i++) data[i] = 20; } Calling programs: int *ages; ages = new int[30] make_all_20(ages, 30); int ages[30]; make_all_20(ages, 30); • An array parameter automatically treated as pointer to the first entry (– value or reference?) • In the function prototype and implementation, size of the array is not specified inside bracket but by another parameter M.P. Johnson, DS, CCNY, Spring 2005
Dynamic Classes New Features (Ch 4.3–4) • Pointers Member Variables • Dynamic Memory Allocation (where and how) • Value Semantics (what’s new?) • assignment operator overloading • your own copy constructor • Introducing Destructor • Conclusion: the Law of the Big Three M.P. Johnson, DS, CCNY, Spring 2005
The Static bag The Dynamic bag Pointer Member Variable // From bag1.h in Sect. 3.1 class bag { public: static const size_t CAPACITY = 20; //... private: value_type data[CAPACITY]; size_type used; }; // From bag2.h class bag { public: //... private: value_type *data; size_type capacity; size_type used; }; M.P. Johnson, DS, CCNY, Spring 2005
Invariant of the Dynamic bag • the number of items is in the member variable used • The actual items are stored in a partially filled array. The array is a dynamic array, pointed to by the pointer variable data • The total size of the dynamic array is the member variable capacity • Invariant is about rules of implementation... M.P. Johnson, DS, CCNY, Spring 2005
Allocate Dynamic Memory: Where? • In Old Member Functions • constructor – how big is the initial capacity? • insert – if bag is full, how many more? • +/+= operators – how to combine two bags? • New Member Functions • resize – explicitly adjust the capacity • Example • constructor with default size M.P. Johnson, DS, CCNY, Spring 2005
Allocate Dynamic Memory: How? // From bag2.h class bag { public: static const size_t DEFAULT_CAPACITY = 20; bag(size_type init_cap = DEFAULT_CAPACITY); //... private: value_type *data; size_type capacity; size_type used; }; • Constructor: • why initialize? • Default • specific size // From implementation file bag2.cxx bag::bag(size_type init_cap) { data = new value_type[init_cap]; capacity = init_cap; used = 0; } M.P. Johnson, DS, CCNY, Spring 2005
Value Semantics • Copy constructor • bag y = x; // or: • bag y(x); • Assignment operator • y = x; • Automatic assignment operator and copy constructor • copy all the member variables (data, used, capacity) from object x to object y • but our days of easy contentment are done! M.P. Johnson, DS, CCNY, Spring 2005
Failure in auto assignment operator capacity used data bag x(4), y(5); x.insert(18); x.insert(19); y=x; x.insert(20); x [0] [1] [2] [3] y [0] [1] [2] [3] [4] Question: What will happen after executing code on left? M.P. Johnson, DS, CCNY, Spring 2005
Failure in auto assignment operator capacity used data bag x(4), y(5); x.insert(18); x.insert(19); y=x; x.insert(20); x [0] [1] [2] [3] y [0] [1] [2] [3] [4] Question: What will happen after executing code on left? M.P. Johnson, DS, CCNY, Spring 2005