Data Structures and Other Objects by ewghwehws

VIEWS: 3 PAGES: 70

• pg 1
```									  CSC212
Data Structure
- Section RS
Review (Chapters1-4)

Instructor: Esther Levin
Department of Computer Science
City College of New York

@ Esther Levin, 2004                                    1
Outline

     Homework Project #2
 sequence      class
 Exam           Review:
       Chapter 1-4;

@ Esther Levin, 2004                   2
Exam 1

 40          questions
 Multiple choice

@ Esther Levin, 2004               3
Chapter 1

 The          Phases of Software Development
       Basic design strategy
       Pre-conditions and post-conditions
       Run time analysis

@ Esther Levin, 2004                                        4
Basic Design Strategy

 Basic   Design Strategy – four steps
 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

@ Esther Levin, 2004                                           5
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.

@ Esther Levin, 2004                                          6
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

@ Esther Levin, 2004                                          7
Example questions:

1.  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...
}
@ Esther Levin, 2004                                  8
1.      Which of these is used to stop the program
execution when a precondition is not met.
       A. assert();
       B. exit();
       C. return();
       D. void();

@ Esther Levin, 2004                                          9
1.      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)

@ Esther Levin, 2004                                        10
1.      Answer true or false for this statement:
True or false: An algorithm with worst
case time behavior of 3n takes at least 30
operations for every input of size n=10.
       TRUE.
       FALSE.

@ Esther Levin, 2004                                          11
Chapter 2 outline

A Review of C++ Classes (Lecture 2)
 Class Definition, Implementation and Use
 Constructors and Value Semantics
More on Classes (Lecture 3)
 Namespace and Documentation
 Classes and Parameters (value, reference, const
reference)

@ Esther Levin, 2004                                         12
Summary of classes

 Classes have member variables and member
functions. An object is a variable where the 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.

@ Esther Levin, 2004                                             13
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
@ Esther Levin, 2004                                                          14
(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

@ Esther Levin, 2004                                                         15
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.

@ Esther Levin, 2004                                                       16
 point p1;        •Default constructor
 point p2(p1);    •Copy constructor
 point p3 = p2;   •Copy constructor
 p3 = p1;         •Assignment operator

@ Esther Levin, 2004                               17
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

@ Esther Levin, 2004                                            18
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

@ Esther Levin, 2004                                                19
Value parameters

    A value parameter is declared by writing
       type-name parameter-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
constructor is used to initialize the formal
parameter as a copy of the actual argument
@ Esther Levin, 2004                                         20
Reference parameters

    A reference parameter is declared by writing
       type-name& parameter-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!
@ Esther Levin, 2004                                              21
const reference parameters

    A const reference parameter is declared by
writing
       const type-name& parameter-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!)

@ Esther Levin, 2004                                                        22
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)
@ Esther Levin, 2004                                                23

 Binary    functions and binary operators
     Friend functions – when to use

@ Esther Levin, 2004                                      24
Chapter 2 sample questions

1.      Write one clear sentence telling me when it
would be appropriate to use a const reference
parameter.
2.      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?
.

@ Esther Levin, 2004                                                 25
1.      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 can access private
member variables
       E. None of the above
@ Esther Levin, 2004                                        26
1.      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?
       A. Only x can alter the private member variables of the object
that activates the function.
       B. Only y can alter the private member variables of the object
that activates the function.
       C. Only z can alter the private member variables of the object
that activates the function.
       D. Two of the functions can alter the private member variables
of the object that activates the function.
       E. All of the functions can alter the private member variables
@ Estherof the object that activates the function.
Levin, 2004                                                      27
Chapter 3 – container classes

A   container class is 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.

@ Esther Levin, 2004                                   28
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
@ Esther Levin, 2004                                                       29
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

@ Esther Levin, 2004                             30
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
@ Esther Levin, 2004                                                      31
Chapter 3 – sample questions

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

@ Esther Levin, 2004                                           32
1.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);
•A. b.used is 2, b.data[0] is 4, b.data[1] is 6
•B. b.used is 2, b.data[0] is 6, b.data[1] is 4
•C. b.used is 3, b.data[0] is 4, b.data[1] is 6
•D. b.used is 3, b.data[0] is 6, b.data[1] is 4
@ Esther Levin, 2004                                                     33
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

@ Esther Levin, 2004                                             34
Operators * and &

    Operator *                     Operator &
 Pointer declaration           Reference parameter
int *i_ptr;                    void funct(int& i);
 dereferencing operator        “address of ” operator
cout << *i_ptr;                i_ptr = &i;
    Two different                  Just coincidence?
meanings!                          Will see in parameter
passing

@ Esther Levin, 2004                                                      35
Assignment Operators with Pointers

 p1= p2
 *p1 = *p2

@ Esther Levin, 2004                     36
Accessing Dynamic Array

    Use array notation      Use pointer notation
 the 1st entry          the 1st entry
p1[0] = 18;             *p1 = 18;
 the 3rd entry          the 3rd entry
p1[2] = 20;             *(p1+2) = 20;
 the ith entry          the ith entry
p1[i-1] = 19;           *(p1+i-1) = 19;

@ Esther Levin, 2004                                          37
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
       error message and program halts
 Good practice 1: document which functions uses
new
 Good practice 2: garbage collection by delete
operator
@ Esther Levin, 2004                                        38
The delete Operator

 Release  any dynamic memory (heap
memory) that is no longer needed
…
int *i_ptr;
delete i_ptr;
double *d_ptr;
delete [ ] d_ptr; // empty brackets
point *p_ptr;
delete p_ptr;
Questions( true or false):
i_ptr = new int;
d_ptr = new double[20];                                     X
1. delete resets these pointers
2. delete removes dynamic
p_ptr = new point(1.0, 2.0);
objects pointed by the pointers
V
……
3. nothing happens to the
@ Esther Levin, 2004                      pointers themselves          V     39
Pointers and Arrays as Parameters

     Value parameters that are pointers
     Array parameters
     Pointers and arrays as const parameters
     Reference parameters that are pointers

@ Esther Levin, 2004                                     40
Array Parameters

 Compare          ordinary and Dynamic arrays
void make_all_20(int data[ ], size_t size)
Calling program:
Calling program:                   {
for (int i = 0 ; i< size; i++)
int ages[30];
int *ages;                           {
ages = new int[30]                           data[i] = 20;
make_all_20(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
@ Esther Levin, 2004                                                                  41
Dynamic Classes New Features (Ch 4.3–4)

     Pointers Member Variables
     Dynamic Memory Allocation (where and how)
     Value Semantics (what’s new?)
     Introducing Destructor
     Conclusion: the Law of the Big Three

@ Esther Levin, 2004                                     42
Pointer Member Variable

    The Static bag                     The Dynamic bag
// From bag1.h in Section 3.1                 // From bag2.h in Section 4.3
class bag                                     class bag
{                                             {
public:                                       public:
static const size_t CAPACITY = 20;            ...
...                                       private:
private:                                          value_type *data;
value_type data[CAPACITY];                    size_type used;
size_type used;                               size_type capacity;
};                                            };

@ Esther Levin, 2004                                                               43
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...
@ Esther Levin, 2004                                         44
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
 reserve       – explicitly adjust the capacity
     Example
       constructor with default size

@ Esther Levin, 2004                                                45
Allocate Dynamic Memory: How?
// From bag2.h in Section 4.3
class bag
   In constructor:
{                                                        why initialize?
public:
static const size_t DEFAULT_CAPACITY = 20;          how?
bag(size_type init_cap = DEFAULT_CAPACITY);
   default
...                                                          specific size
private:
value_type *data;
size_type used;          // From implementation file bag2.cxx
size_type capacity;      bag::bag(size_type init_cap)
};                          {
data = new value_type[init_cap];
capacity = init_cap;
used = 0;
}

@ Esther Levin, 2004                                                               46
Value Semantics

    Assignment operator
       y = x;
    Copy constructor
       bag y(x); // bag 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!

@ Esther Levin, 2004                                                     47
Failure in auto assignment operator

capacity used data
bag x(4), y(5);
x.insert(18);            x   4 0   984         ?         ?         ?         ?
x.insert(19);                                  [0]       [1]       [2]       [3]
y=x;
x.insert(20);        y       5 0   964          ?         ?            ?         ?     ?

[0]       [1]       [2]       [3]   [4]

Question: What will happen after executing lines 2 – 5?

@ Esther Levin, 2004                                                                           48
Failure in auto assignment operator

capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984         18     19     ?         ?
x.insert(19);                                  [0]    [1]    [2]       [3]
y=x;
x.insert(20);        y       5 0   964          ?      ?         ?         ?     ?

[0]    [1]       [2]       [3]   [4]

Question: What will happen after executing lines 2 – 5?

@ Esther Levin, 2004                                                                     49
Failure in auto assignment operator

capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984         18     19     ?         ?
x.insert(19);                                  [0]    [1]    [2]       [3]
y=x;
x.insert(20);        y       4 2   984          ?      ?         ?         ?     ?

[0]    [1]       [2]       [3]   [4]

lost memory

Question: What will happen after executing lines 2 – 5?

@ Esther Levin, 2004                                                                     50
Failure in auto assignment operator

capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984         18     19     20     ?
x.insert(19);                                 [0]     [1]    [2]    [3]
y=x;
x.insert(20);        y       4 2   984         ?       ?      ?         ?     ?

[0]    [1]    [2]       [3]   [4]

lost memory

Consequence: Change to x’ array will also change y’s array

@ Esther Levin, 2004                                                                  51
If we want y to have its own
dynamic array
capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984    18     19     ?         ?
x.insert(19);                             [0]    [1]    [2]       [3]
y=x;
x.insert(20);        y       5 0   964    ?       ?         ?         ?     ?

[0]    [1]       [2]       [3]   [4]

@ Esther Levin, 2004                                                                52
Dynamic memory allocation is
needed
capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984       18        19        ?         ?
x.insert(19);                                [0]       [1]       [2]       [3]
y=x;
x.insert(20);        y       4 2   984        18       19        ?         ?

?         ?         ?         ?     ?

[0]       [1]       [2]       [3]   [4]

memory de-allocated
@ Esther Levin, 2004                                                                           53
Dynamic memory allocation is
needed
capacity used data
bag x(4), y(5);
x.insert(18);            x   4 2   984       18        19        20        ?
x.insert(19);                                [0]       [1]       [2]       [3]
y=x;
x.insert(20);        y       4 2   922        18       19        ?         ?

?         ?         ?         ?     ?

[0]       [1]       [2]       [3]   [4]

memory de-allocated
@ Esther Levin, 2004                                                                           54
// From bag2.h in Section 4.3
class bag
{
public:
static const size_t DEFAULT_CAPACITY = 20;
bag(size_type init_cap = DEFAULT_CAPACITY);

...                            // From implementation file bag2.cxx
private:                          bag::bag(size_type init_cap)
value_type *data;              {
size_type used;                   data = new value_type[init_cap];

};
      C++ Requires the overloaded assignment
size_type capacity;               capacity = init_cap;
used = 0;
operator to be a member function
}

bag x, y; // OR bag x(4), y(5); // OR....
y=x; // y.operator=(x);
void bag::operator=(const bag& source)
// Postcondition: The bag that activated this function
has the same items and capacity as source

(A 5-minute Quiz: write your own implementation )
@ Esther Levin, 2004                                                     55
Implementation of operator=
void bag::operator =(const bag& source)
// Library facilities used: algorithm
{
value_type *new_data;
     y = x;
// Check for possible self-assignment:
     y  *this             if (this == &source)
return;

     x  source            // If needed, allocate an array with a different size:
if (capacity != source.capacity)
{
new_data = new value_type[source.capacity];
delete [ ] data; // make sure all valid before new!!!
data = new_data;
capacity = source.capacity;
}

// Copy the data from the source array:
used = source.used;
copy(source.data, source.data + used, data);
}
@ Esther Levin, 2004                                                                    56
What’s missing?

allocate dynamic memory via new,
take care of the value semantics,
....?

@ Esther Levin, 2004                                        57
De-allocation of dynamic memory

 Returnan object’s dynamic memory to the
heap when the object is no longer in use
 Where and How? – Two ways
       Take care of it yourself
   delete dynamic data of an object after you’re done
with it
       let the program do it automatically
   destructor

@ Esther Levin, 2004                                                            58
bag::~bag()
{
Destructor                                          delete [ ] data;
}

  The primary purpose is to return an object’s
dynamic memory to the heap, and to do other
“cleanup”
 Three unique features of the destructor
  The name of the destructor is always ~ followed by the
class name;
 No parameters, no return values;
 Activated automatically whenever an object becomes
inaccessible
Question: when this happens?

@ Esther Levin, 2004                                                       59
bag::~bag()
{
Destructor                                         delete [ ] data;
}

    Some common situations causing automatic
destructor activation
 Upon function return, objects as local variables
destroyed;
 Upon function return, objects as value parameters
destroyed;
 when an object is explicitly deleted

Question: shall we put destructor in how-to-use-a-
bag documentation?

@ Esther Levin, 2004                                                      60
The Law of the Big Three

    Using dynamic memory requires the following
three things all together
       a destructor
       a copy constructor (and of course an ordinary one)
     In other words, the three functions come in a set –
either you need to write all three yourself, or you
can rely on the compiler-supplied automatic
versions of all the three.

@ Esther Levin, 2004                                                        61
What will happen if not?

If we only have a constructor and a
destructor, but do not provide a copy
assignment operator

@ Esther Levin, 2004                                           62
Importance of the Law of Big-3
// constructor
bag::bag(size_type init_cap)
bag *x, *y;                   {
data = new value_type[init_cap];
x = new bag(4);                  capacity = init_cap;
y = new bag(5);                  used = 0;
}
x->insert(18);
x->insert(19);                                 // destructor
*y = *x;                                       bag::~bag()
{
delete x;                                          delete [ ] data;
y->insert(20);                                 }
Question: What will happen after executing lines 1 – 8?

@ Esther Levin, 2004                                                    63
Importance of the Law of Big-3

capacity used data
bag *x, *y;
x = new bag(4);      *x     4 0   984            ?         ?         ?         ?
y = new bag(5);                                 [0]        [1]       [2]       [3]
x->insert(18);
x->insert(19);       *y     5 0    964           ?          ?            ?         ?     ?

*y = *x;                                             [0]       [1]       [2]       [3]   [4]
delete x;                                 // From implementation file bag2.cxx
bag::bag(size_type init_cap)
y->insert(20);                            {
allocate memory for objects (*x, *y)      data = new value_type[init_cap];
capacity = init_cap;
and their dynamic arrays                  used = 0;
@ Esther Levin, 2004
}                                                    64
Importance of the Law of Big-3

capacity used data
bag *x, *y;
x = new bag(4);      *x     4 2    984           18     19     ?         ?
y = new bag(5);                                  [0]    [1]    [2]       [3]
x->insert(18);
x->insert(19);       *y     5 0    964           ?       ?         ?         ?     ?

*y = *x;                                          [0]    [1]       [2]       [3]   [4]
delete x;
y->insert(20);
Insert two items in the dynamic array of object *x

@ Esther Levin, 2004                                                                       65
Importance of the Law of Big-3

capacity used data
bag *x, *y;
x = new bag(4);      *x    4 2   984          18      19     ?         ?
y = new bag(5);                               [0]    [1]     [2]       [3]
x->insert(18);
x->insert(19);       *y    4 2   984           ?      ?          ?         ?     ?

*y = *x;                                       [0]     [1]       [2]       [3]   [4]
delete x;                                     lost memory
y->insert(20);
automatic assignment only copies three variables
(capacity, used and data) from *x to *y
@ Esther Levin, 2004                                                                     66
Importance of the Law of Big-3

bag *x, *y;
x = new bag(4);                              dangling pointer
y = new bag(5);
x->insert(18);
x->insert(19);       *y     4 2    984       ?      ?     ?     ?     ?

*y = *x;                                      [0]   [1]   [2]   [3]   [4]
delete x;                                    lost memory
y->insert(20);
bag::~bag()
Deleting x will also delete the dynamic                {
array of *x by calling the destructor                    delete [ ] data;
@ Esther Levin, 2004                                        }                  67
Importance of the Law of Big-3

bag *x, *y;
x = new bag(4);                               dangling pointer
y = new bag(5);
x->insert(18);
x->insert(19);       *y    4 2   984           ?     ?     ?     ?     ?

*y = *x;                                       [0]   [1]   [2]   [3]   [4]
delete x;                                     lost memory
y->insert(20);
Your program crashes: *y needs its own copy of data !!!

@ Esther Levin, 2004                                                           68
Chapter 4-sample questions

1.    Draw a picture of memory after these
statements:
int i = 42;
int k = 80;
int* p1;
int* p2;
p1 = &i;
p2 = &k;
*p1 = *p2;
@ Esther Levin, 2004                                  69
1.      What is the usual worst-case performance
for resizing a container class that stores its
data in a dynamic array?
       A. Constant time
       B. Logarithmic time
       C. Linear time