Csc212 ab data structures lecture 10
This presentation is the property of its rightful owner.
Sponsored Links
1 / 89

CSc212 AB Data Structures Lecture 10 PowerPoint PPT Presentation


  • 53 Views
  • Uploaded on
  • Presentation posted in: General

CSc212 AB Data Structures Lecture 10. M. P. Johnson [email protected] 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

Download Presentation

CSc212 AB Data Structures Lecture 10

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Csc212 ab data structures lecture 10

CSc212AB Data StructuresLecture 10

M. P. Johnson

[email protected]

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

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

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

  • 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

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

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

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


Csc212 ab data structures lecture 10

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


Csc212 ab data structures lecture 10

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


Csc212 ab data structures lecture 10

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


Csc212 ab data structures lecture 10

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


Csc212 ab data structures lecture 10

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

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

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

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

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

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

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

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

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

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!

M.P. Johnson, DS, CCNY, Spring 2005


Const reference parameters

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!)

M.P. Johnson, DS, CCNY, Spring 2005


Class as return value

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

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

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


Csc212 ab data structures lecture 10

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


Csc212 ab data structures lecture 10

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

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

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

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

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

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


Csc212 ab data structures lecture 10

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

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


Operators and

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

Assignment Operators with Pointers

  • p1 = p2

  • *p1 = *p2

M.P. Johnson, DS, CCNY, Spring 2005


Accessing dynamic array

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

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

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

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

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

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


Pointer member variable

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

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

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

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

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

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 operator1

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 operator2

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]

lost memory

Question: What will happen after executing code on left?

M.P. Johnson, DS, CCNY, Spring 2005


Failure in auto assignment operator3

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]

lost memory

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

M.P. Johnson, DS, CCNY, Spring 2005


If we want y to have its own dynamic array

If we want y to have its own dynamic array

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]

M.P. Johnson, DS, CCNY, Spring 2005


Dynamic memory allocation is needed

Dynamic memory allocation is needed

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]

memory de-allocated

Answer: overloading the assignment operator =

M.P. Johnson, DS, CCNY, Spring 2005


Dynamic memory allocation is needed1

Dynamic memory allocation is needed

capacity used data

x

bag x(4), y(5);

x.insert(18);

x.insert(19);

y=x;

x.insert(20);

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

y

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

memory de-allocated

Answer: overloading the assignment operator =

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

// 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;

};

// From impl. file bag2.cxx

bag::bag(size_type init_cap) {

data = new

value_type[init_cap];

capacity = init_cap;

used = 0;

}

void bag::operator=(const bag& source)

/* Postcondition: The bag that activated this function has the same items and capacity as source */

M.P. Johnson, DS, CCNY, Spring 2005


Implementation of operator

Implementation of operator=

  • y = x;

  • y *this

  • x  source

void bag::operator =(const bag& source) {

// Library facilities used: algorithm

value_type *new_data;

// Check for possible self-assignment:

if (this == &source)

return;

// If needed, allocate an array a diff. size:

if (capacity != source.capacity) {

new_data = new value_type[source.capacity];

delete [] data; // free old memory6

data = new_data;

capacity = source.capacity;

}

// Copy the data from the source array:

used = source.used;

copy(source.data, source.data + used, data);

}

M.P. Johnson, DS, CCNY, Spring 2005


What s missing

What’s missing?

allocate dynamic memory via new,

take care of the value semantics,

....?

M.P. Johnson, DS, CCNY, Spring 2005


De allocation of dynamic memory

De-allocation of dynamic memory

  • Return an 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

M.P. Johnson, DS, CCNY, Spring 2005


Destructor

bag::~bag() {

delete [] data;

}

Destructor

  • 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?

M.P. Johnson, DS, CCNY, Spring 2005


Destructor1

bag::~bag() {

delete [] data;

}

Destructor

  • 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?

M.P. Johnson, DS, CCNY, Spring 2005


The law of the big three

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)

    • an overloaded assignment operator

  • Generally speaking: you write your own versions of all three or none at all

M.P. Johnson, DS, CCNY, Spring 2005


What will happen if not

What will happen if not?

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

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 3

Importance of the Law of Big 3

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

// constructor

bag::bag(size_type init_cap) {

data = new value_type[init_cap];

capacity = init_cap;

used = 0;

}

// destructor

bag::~bag() {

delete [] data;

}

Question: What will happen after executing code on left?

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 31

Importance of the Law of Big 3

capacity used data

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

*x

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

*y

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

// From implementation file bag2.cxx

bag::bag(size_type init_cap) {

data = new value_type[init_cap];

capacity = init_cap;

used = 0;

}

allocate memory for objects (*x, *y) and their dynamic arrays

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 32

Importance of the Law of Big 3

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

capacity used data

*x

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

*y

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

Insert two items in the dynamic array of object *x

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 33

Importance of the Law of Big 3

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

capacity used data

*x

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

*y

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

lost memory

automatic assignment only copies three variables (capacity, used and data) from *x to *y

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 34

Importance of the Law of Big 3

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

dangling pointer

*y

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

lost memory

// destructor

bag::~bag() {

delete [] data;

}

Deleting x will also delete the dynamic array of *x by calling the destructor

M.P. Johnson, DS, CCNY, Spring 2005


Importance of the law of big 35

Importance of the Law of Big 3

bag *x, *y;

x = new bag(4);

y = new bag(5);

x->insert(18);

x->insert(19);

*y = *x;

delete x;

y->insert(20);

dangling pointer

*y

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

lost memory

Your program crashes: *y needs its own copy of data!

M.P. Johnson, DS, CCNY, Spring 2005


Linked lists motivation

Linked Lists Motivation

  • How can we insert a new item without moving others?

and then put the new item into the chain

M.P. Johnson, DS, CCNY, Spring 2005


Declarations for linked lists

Declarations for Linked Lists

  • The data portion of each node is a type called value_type, defined by a typedef

class node {

public:

typedef int

value_type;

...

private:

value_type data;

node *link;

};

15

data

link

10

data

7

data

link

null

link

M.P. Johnson, DS, CCNY, Spring 2005


Declarations for linked lists1

A program can keep track of the first node by using a pointer variable such as head_ptr in this example.

NB: head_ptr itself is not a node

it is a pointer to a node

15

data

link

10

data

7

data

link

link

Declarations for Linked Lists

null

head_ptr

node * head_ptr;

M.P. Johnson, DS, CCNY, Spring 2005


Code of list length list traverse

Initialize the count to zero.

Each time cursor points to a new node, add 1 to count.

return count.

code of list_length: List Traverse

size_t list_length(const node* head_ptr) {

const node *cursor;

size_t count = 0; // step 1

for (cursor = head_ptr; cursor != NULL;

cursor = cursor->link())

count++; // step 2

return count; // step 3

}

15

10

cursor

7

null

0

head_ptr

M.P. Johnson, DS, CCNY, Spring 2005

count


Homework 2

Homework 2

  • Issues with old exam program

  • Download current vector exam and retry

  • Can turn in Tuesday night with no late penalty

  • But finish before the exam!

    • The homework is preparatory to th exam

M.P. Johnson, DS, CCNY, Spring 2005


Exam 1

Exam 1

  • O(10) pages

    • Short answer

    • Some multiple choice

    • Programming

      • Implement a function

      • Define a class

      • Fill in missing parts

      • Find errors in code

M.P. Johnson, DS, CCNY, Spring 2005


General skills to have

General skills to have

  • recognizing bugs in short programs

  • predicting the output of short programs

  • predicting the final var values in short programs

  • Determining the complexity of algorithms / short programs

  • Most important: writing short, conceptually and syntactically correct programs to solve problems

M.P. Johnson, DS, CCNY, Spring 2005


Individual topics c

Individual topics C++:

  • references v. pointers

  • static class vars v. member vars

  • copy constructor/assignment op: what for, when called, what are their defaults?

  • arith. operators: +-*/% ++ -- (pre and post), +=, -=, etc.

  • == v. =

  • bool. operators: && || ! xor (concept)

  • bits and bytes

  • operator overloading

M.P. Johnson, DS, CCNY, Spring 2005


Individual topics c1

Individual topics C++:

  • how to write header files, including the necessary preprocessor code

  • static arrays v. dynamic arrays v. vectors

  • the NULL pointer

  • the this pointer

  • classes, the . operator for accessing fieldsclass pointers, the -> for access fieldstypedef

  • assert

M.P. Johnson, DS, CCNY, Spring 2005


Sample questions

sample questions

Draw a picture of memory after these statements:

int i = 42;

int k = 80;

int* p1;

int* p2;

p1 = &i;

p2 = &k;

*p1 = *p2;

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • What is the usual worst-case complexity for vector.add(x)?

  • A. Constant time

  • B. Logarithmic time

  • C. Linear time

  • D. Quadratic time

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • What is the worst-case complexity for vector.add(x), in the case when resizing is required?

  • A. Constant time

  • B. Logarithmic time

  • C. Linear time

  • D. Quadratic time

M.P. Johnson, DS, CCNY, Spring 2005


How do we prevent duplicate headers

How do we prevent duplicate headers?

  • #ifndef MYHEADER_H

  • #define MYHEADER_H

  • #endif

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

Convert each time formula to the best possible big-O notation. Do not include any spurious constants in your big-O answer.

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • Draw a picture of memory after these statements:

  • int i = 42; int k = 80; int* p1; int* p2; p1 = &i; p2 = &k;

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • Which of these is the correct big-O expression for 1+2+3+...+n?

    • A. O(log n)

    • B. O(n)

    • C. O(n log n)

    • D. O(n²)

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • Suppose that the foo class does not have an overloaded assignment operator. What happens when an assignment a=b; is given for two foo objects?

    • The automatic assignment operator is used

    • The copy constructor is used

    • Compiler error

    • Run-time error

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • Here is a function prototype and some possible function calls:

  • int day_of_week(int year, int month = 1, int day = 1);

    //Possible function calls: cout << day_of_week();

    cout << day_of_week(1995); cout << day_of_week(1995, 10); cout << day_of_week(1995, 10, 4);

  • How many of the function calls are legal?

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

  • Consider the following statements:

  • int *p; int i; int k; i = 42; k = i; p = &i;

  • After these statements, which of the following statements will change the value of i to 75?

    • A. k = 75;

    • B. *k = 75;

    • C. p = 75;

    • D. *p = 75;

    • E. Two or more of the answers will change i to 75.

M.P. Johnson, DS, CCNY, Spring 2005


Csc212 ab data structures lecture 10

Q

  • Consider the following statements:

  • int i = 42; int j = 80;

    int *p1; int *p2;

    p1 = &i; p2 = &j; *p1 = *p2;

    cout << i << j << endl;

    What numbers are printed by the output statement?

    • A. 42 and then another 42

    • B. 42 and then 80

    • C. 80 and then 42

    • D. 80 and then another 80

M.P. Johnson, DS, CCNY, Spring 2005


  • Login