Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSI 1340 Introduction to Computer Science II

Similar presentations


Presentation on theme: "CSI 1340 Introduction to Computer Science II"— Presentation transcript:

1 CSI 1340 Introduction to Computer Science II
Chapter 4 ADTs Stack and Queue What did we have before? A list. With an unsorted list, you accessed items by key. They were stored in no specific order so if you traversed the list you got a nonsensical ordering of items. With a sorted list, you could access items by key or traverse in order. Are there other ways to access? What about accessing in an order related to the order in which the items were added to the list?

2 Stacks of Plates in Cafeteria
New plates are “pushed” on top The next plate is “popped” from the top

3 What is a Stack? A stack is an ordered group of homogeneous items (elements), in which the removal and addition of stack items can take place only at the top of the stack. A stack is a LIFO “last in, first out” structure. Entries are taken out of the stack in the reverse order of their insertion.

4 Are Stacks Useful? Web Surfing Lost in hyperlink space
CNN article on wild goats Yahoo search for wild goat cheese recipe Ebay bid on goat hair purse How did I get here?

5 Stack ADT Operations MakeEmpty -- Sets stack to an empty state.
IsEmpty -- Determines whether the stack is currently empty. IsFull -- Determines whether the stack is currently full. Push (ItemType newItem) -- Adds newItem to the top of the stack. Pop (ItemType& item) -- Removes the item at the top of the stack and returns it in item.

6 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] [ 1 ] items [ 0 ]

7 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] [ 1 ] items [ 0 ]

8 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] [ 1 ] items [ 0 ] ‘V’

9 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] [ 1 ] ‘C’ items [ 0 ] ‘V’

10 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

11 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

12 Tracing Client Code ‘S’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

13 Tracing Client Code ‘S’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

14 Tracing Client Code ‘S’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

15 Tracing Client Code ‘K’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

16 Tracing Client Code ‘K’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

17 Tracing Client Code ‘C’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

18 Tracing Client Code ‘C’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

19 Tracing Client Code ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

20 End of Trace ‘V’ letter char letter = ‘V’; StackType charStack;
charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) Private data: top [MAX_ITEMS-1] . [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’ Show my example Derive specification, then main, then implementation

21 Just How Generic Are We? typedef string GenType; class StackType {
public: StackType(); bool push(const GenType& url); bool pop(GenType& url); private: enum {MAXSTACK = 100}; int top; GenType item[MAXSTACK]; }; typedef int GenType; class StackType { public: StackType(); bool push(const GenType& url); bool pop(GenType& url); private: enum {MAXSTACK = 100}; int top; GenType item[MAXSTACK]; }; Using my approach, I could generalize to use GenType Problem: Using multiple stack types in the same program (e.g., string and integer stack) In this case, I have to start playing name games. I have to have a StackType class for every type (e.g., StringStackType, IntStackType). Also, I cannot multiply define GenType. Same with separate ItemType class as in text.

22 What is a Class Template?
A class template allows the compiler to generate multiple versions of a class type by using type parameters. The formal parameter appears in the class template definition, and the actual parameter appears in the client code. Both are enclosed in pointed brackets, < >.

23 StackType<int> numStack;
ACTUAL PARAMETER StackType<int> numStack; top [MAX_ITEMS-1] . [ 3 ] [ 2 ] [ 1 ] items [ 0 ]

24 StackType<float> myStack;
ACTUAL PARAMETER StackType<float> myStack; top [MAX_ITEMS-1] . [ 3 ] [ 2 ] [ 1 ] items [ 0 ] See my code Can do this with functions as well

25 Using class templates The actual parameter to the template is a data type. Any type can be used, either built-in or user-defined. When using class templates, both the specification and implementation should be located in the same file (the header file), instead of in separate .h and .cpp files. Can you guess why it has to be in the header file?

26 Recall that… Memory is like a shelf of slots
2 slot # 522 523 524 525 content Each slot has a number and some content value

27 Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the address of the variable. int x; // 2 bytes float number; // 4 bytes char ch; // 1 byte x number ch

28 Obtaining Memory Addresses
We can get the value of a slot. How about the slot # itself? The address of a non-array variable can be obtained by using the address-of operator &. int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl; & makes sense since it is the sign we use for pass by reference in function parameters (e.g., int sum(int &total);)

29 Results Address of x is 0012FF7C Address of number is 0012FF78
int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl; Output: Address of x is 0012FF7C Address of number is 0012FF78 Address of ch is 0012FF74

30 What is a pointer variable?
A pointer variable is a variable whose value is the address of a location in memory. To declare a pointer variable, you must specify the type of value that the pointer will point to. For example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char

31 Using a pointer variable
2000 12 x 3000 ptr int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x A pointer variable is just like any other variable. It has a memory location (AKA shelf slot). It’s value “points” to another memory location.

32 * - dereference operator
2000 12 x 3000 ptr int x = 12; int* ptr = &x; cout<<“Addr of x: “<< ptr << endl; cout<<“Value of x:“<< *ptr << endl; NOTE: The value pointed to by ptr is denoted by *ptr

33 Results int x = 12; int* ptr = &x;
cout<<“Addr of x: “<< ptr << endl; cout<<“Value of x:“<< *ptr << endl; Output: Addr of x: 0012FF7C Value of x: 12

34 Using the dereference operator
int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at address ptr to 5 2000 x 3000 ptr

35 Another Example char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’;
char* p; p = q; // the right side has value 4000 // now p and q both point to ch 4000 A Z ch q p

36 The NULL Pointer There is a special pointer value called the “null pointer” denoted by NULL to represent a pointer variable that is not pointing to anything NULL is not a valid memory address It is an error to dereference (e.g., *x) a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) { // ok to use *ptr here }

37 Allocation of memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

38 Using operator new If memory is available, new allocates the requested object or array and returns a pointer to (address of ) the memory allocated. Otherwise, the null pointer is returned. The dynamically allocated object exists until the delete operator destroys it.

39 New Operator Creates a new dynamic variable of the specified type and returns a pointer to this new dynamic variable. Example double *dptr; dptr = new double; *dptr = ; dptr dptr dptr

40 Dynamically Allocated Data
char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; 2000 ptr

41 Dynamically Allocated Data
char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr

42 Dynamically Allocated Data
char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr ‘B’

43 Dynamically Allocated Data
char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 2000 ptr NOTE: Delete deallocates the memory pointed to by ptr. ?

44 Using operator delete The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. The memory is returned to the free store.

45 Dynamic Array Allocation
char *ptr; // ptr is a pointer variable that // can hold the address of a char ptr = new char[ 5 ]; // dynamically, during run time, allocates // memory for 5 characters and places into // the contents of ptr their beginning address 6000 6000 ptr

46 Dynamic Array Allocation
char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; // a pointer can be subscripted cout << ptr[ 2 ] ; 6000 ‘u’ 6000 ‘B’ ‘y’ ‘e’ ‘\0’ ptr

47 Declaring a Dynamic Array
Example int *arrayptr; // (1) Declare a pointer arrayptr = new int[10]; // (2) Create an array pointed // to by the pointer arrayptr[0] = 65; // (3) Assign a value to the first // memory location in the array NOTE: With dynamic arrays, omit the * when assigning values or otherwise accessing the array elements. After allocation, access is identical to statically allocated arrays.

48 Dynamic Array Deallocation
char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete [ ] ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated, but // the value of ptr is considered unassigned ? ptr

49 Declaring a Dynamic Record
Example struct RecType { int iNum; float fNum; }; RecType *rptr;

50 What is a Queue? A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the rear), and elements are removed from the other end (the front). A queue is a FIFO “first in, first out” structure. Like a line at the grocery store.

51 Queue ADT Operations MakeEmpty -- Sets queue to an empty state.
IsEmpty -- Determines whether the queue is currently empty. IsFull -- Determines whether the queue is currently full. Enqueue (ItemType newItem) -- Adds newItem to the rear of the queue. Dequeue (ItemType& item) -- Removes the item at the front of the queue and returns it in item.

52 Accessing a Dynamic Record
Example rptr = new RecType; // Creates a record pointed to by // the pointer (*rptr). iNum = 65; // Assigns a value to the first // field in the record rptr -> iNum = 65; // Alternative syntax

53 Dereferencing Operator w/ Records
Asterisk and the pointer name are enclosed in parentheses. Example cout << (*rptr).iNum;

54 Arrow Operator w/Records
-> (a hyphen followed by a greater-than symbol) For records and classes, it is equivalent to the use of the dereferencing operator and parentheses. Example cout << rptr -> iNum;

55 Pointers as Value Parameters
Example void myFunc (int* intptr); // Prototype for myFunc A quick summary This presentation has only introduced classes. You should read all of Chapter 2 to get a better understanding of classes. Pay particular attention to the notion of a constructor, which is a special member function that can automatically initialize the member variables of an object. Also pay attention to the more advanced features such as operator overloading with the Point class given in Chapter 2.

56 What happens here? int* ptr = new int; *ptr = 3;
ptr = new int; // changes value of ptr *ptr = 4; 3 ptr 3 ptr 4

57 Memory Leak A memory leak occurs when dynamic memory (that was created using operator new) is left without a pointer to it by the program int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; 8 ptr -5 ptr2

58 Causing a Memory Leak int* ptr = new int; *ptr = 8;
-5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2

59 A Dangling Pointer Occurs when two pointers point to the same object and delete is applied to one of them. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; 8 ptr -5 ptr2 FOR EXAMPLE,

60 Leaving a Dangling Pointer
8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; 8 ptr NULL ptr2

61 Classes and Dynamic MemoryAllocation

62 class Counter { public: Counter( ); Counter(int initCount); void incrementCounter( ); void decrementCounter( ); void setCounter(int initCount); int getCounter( ); private: int *countptr; }; countptr

63 #include "counter.h” Counter::Counter( ) // default constructor { countptr = new int; *countptr = 0; } countptr *countptr

64 Counter::Counter(int initCount) // parameterized constructor
{ countptr = new int; *countptr = initCount; } countptr initCount *countptr

65 void Counter::setCounter(int initCount)
{ *countptr = initCount; } countptr initCount *countptr

66 void Counter::incrementCounter( )
{ *countptr = *countptr + 1; } countptr 1 *countptr

67 void Counter::decrementCounter( )
{ *countptr = *countptr - 1; } countptr 1 *countptr

68 int Counter::getCounter( ) const
{ return *countptr; } countptr *countptr

69 Destructor Syntax Example
Counter::~Counter( ) // Implementation for destructor { delete countptr; // memory location pointed to by } // countptr is returned to heap NOTE: the pointer is NOT returned to the heap


Download ppt "CSI 1340 Introduction to Computer Science II"

Similar presentations


Ads by Google