Upload
vanthuan
View
215
Download
0
Embed Size (px)
Citation preview
# 1
1 2
Objectives1. Dynamic Memory
2. Shallow Copy
3. Deep Copy
4. LIFO & FIFO
5. Array Implementation Of A Stack
6 Dynamic Stack
3
6. Dynamic Stack
7. Templates
8. Template Stack
9. Primitive Operations
• Push, Pop, Empty
• Full, Resize, Overload =
34
4
55
class Name{public:
Name(void);~Name(void);void Set (char NewFirst[] = "", char NewLast[] = "");
private:int
NoCharsInFirstName,NoCharsInLastName;
char*First,*Last;
}; Name::Name(void){}
Not A Good Constructor!Nothing Initialized!
}
6
Construct A Memory Map [Sketch Of Memory] For Name N1;
Initial N1 Map
Address Symbolic Name Contents --------------------------------------| &1000 | *FirstName | ? |--------------------------------------| &1004 | *LastName | ? | --------------------------------------| &1008 | NoCharsInFirst | ? | --------------------------------------| &1012 | NoCharsInLast | ? |--------------------------------------
Dangling PointersFirstName & LastName - Pointers
Reference Memory Incorrect Memory!
6
# 2
77
class Person{public:
Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");
private:int
NoCharsInFirstName,NoCharsInLastName;
char*First,*Last;
};
Create A Good Constructor For Person P1;
In order to avoid dangling pointers, the constructor should either allocate the needed dynamic memory or set the pointer to NULL.
8
Create A Good Constructor For Person P1;
Person::Person (char NewFirst[] = "", char NewLast[] = ""){
};
You Do!
NoCharsInFirstName = strlen(NewFirst)+1;First = new char[NoCharsInFirstName];strcpy(First, NewFirst);NoCharsInLastName = strlen(NewLast)+1;Last = new char[NoCharsInLastName];strcpy(First, NewFirst);
8
class Person{public:
Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");
private:int
NoCharsInFirstName,NoCharsInLastName;
char*First,*Last;
};
Create A Good Destructor For Person P1;
9
Person::~Person (void){
};
You Do!
delete [] First;delete [] Last;
9
class Person{public:
Person (char NewFirst[] = "", char NewLast[] = ""); ~Person (void);void Set (char NewFirst[] = "", char NewLast[] = "");
private:int
NoCharsInFirstName,NoCharsInLastName;
char*First,*Last;
};
Create A Good Memory Map For Person P1 (“Mickey”, “Mouse”);
10
Create A Good Memory Map For Person P1 ( Mickey , Mouse );
You Do!
Initial P1 MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------
1111
Initial Donald Mapdd b li
Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);
Initial Mickey MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------
Address Symbolic Name Contents -------------------------------------- -------------------------------| &1016 | *FirstName | &2400 | | &2400-&2406 | Donald | -------------------------------------- -------------------------------| &1020 | *LastName | &2822 | --------------------------------------| &1024 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1028 | NoCharsInLast | 5 | | &2822-&2826 | Duck | -------------------------------------- -------------------------------
12
Donald = Mickey;
Shallow Copy!No Operator Overload For =
What Happens?Alter The Memory Maps Accordingly!12
# 3
Initial Donald MapAddress Symbolic Name Contents
Initial Mickey MapAddress Symbolic Name Contents -------------------------------------- -------------------------------| &1000 | *FirstName | &2000 | | &2000-&2006 | Mickey | -------------------------------------- -------------------------------| &1004 | *LastName | &3174 | --------------------------------------| &1008 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1012 | NoCharsInLast | 6 | | &3174-&3180 | Mouse | -------------------------------------- -------------------------------
Donald = Mickey; Shallow Copy!
Address Symbolic Name Contents -------------------------------------- -------------------------------| &1016 | *FirstName | &2400 | | &2400-&2406 | Donald | -------------------------------------- -------------------------------| &1020 | *LastName | &2822 | --------------------------------------| &1024 | NoCharsInFirst | 7 | -------------------------------------- -------------------------------| &1028 | NoCharsInLast | 5 | | &2822-&2826 | Duck | -------------------------------------- -------------------------------
13
Memory Leak
Shallow copy of Dynamic Variables Creates Memory Leak – When Either Mickey Or Donald Go Out Of Scope, The Destructor Would Cause Other
To Have Dangling Pointers. 13
Problems With A Shallow Copy
1. Shallow Copy only applies to objects which contain pointers2. Shallow copy transfers pointer addresses, but fails
to properly manage dynamic memory
3. Immediately creates a Memory Leak
If processing occurs in actual memory [like in Windows, MacOS, etc.] re-booting the computer is generally the easiest
t t th l t t th O ti S t
14
way to return the lost memory to the Operating System If processing occurs in a shell [like in UNIX, Linux] logging out and then re-logging in is generally the easiest way to return the lost memory to the Environment.
4.When one of the assignment variables goes out of scope, the destructor for that variable will cause the other assigned variable to have one or more Dangling Pointers.
I Hope You Are Asking Yourself?I Hope You Are Asking Yourself?
How Do I Avoid The Problems Generated
By Shallow
15
aCopies?
Potential Problem In Many LanguagesNot Unique To C & C++
Must Be Some Solution?16
16
class Person{public:
Name (char NewFirst[] = "", char NewLast[] = ""); ~Name(void);void Set (char NewFirst[] = "", char NewLast[] = ""); void operator = (Person P);
private:int
NoCharsInFirstName,NoCharsInLastName;
char*First,*Last;
};
17
Create A Good Operator Overload For
Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);
Mickey = Donald;
void Person::operator = (Person P)
{// Fill the Indigenous data
NoCharsInFirstName = P.NoCharsInFirstName;NoCharsInLastName = P.NoCharsInLastName;
Person Mickey (“Mickey”, “Mouse”),Donald (“Donald”, “Duck”);Mickey = Donald;
Part 1/2
// Free the memory associated with First and Last
if (First != NULL)
delete [] First;
if (Last != NULL)
delete [] Last;
18
# 4
// Allocate memory for First and fill it with P.First if appropriate
if (N.First == NULL)
First = NULL;
else
{
First = new char [NoCharsInFirstName];
strcpy (First, P.First);
}
// Allocate memory for Last and fill it with P.Last if appropriate
Part 2/2
if (N.Last == NULL)
Last = NULL;
else
{
Last = new char [NoCharsInLastName];
strcpy (Last, P.Last);
}
}Deep Copy - makes an actual copy of the data to which the pointers are pointing.
19
There Are Other Solutions!
Deep Copy Solves Problems With A Shallow Copy
1. Object has one or more pointers
2. Shallow copy transfers pointer addresses and properly manage dynamic memory
3. Creates no Memory Leak
4.Creates No Dangling Pointers.
20
So Why Do We Really Care About This Shallow Copy & Deep Copy Stuff?
Are We Ever Going To Use It?To Use It?
21 2222
2323
How many of you have ever written a program that had a stack?
What do we ever use a stack for?
LIFO is an acronym for __________________Last In First Out
FIFO is an acronym for __________________First In First Out
A Stack Is A {LIFO/FIFO} Structure ?__________________LIFO
Stack Applet
24
# 5
Stack Applethttp://www.sci.brooklyn.cuny.edu/~cis22/animations/tsang/html/STACK/stack800.html
3 Required Primitive Operations For StackPush – Add To Stack
Pop Remove From StackPop – Remove From StackEmpty – Is Stack Empty
Optional Primitive Operations For StackStackTop – Peek To See What’s On Top [Peek]
Resize – Resize A Dynamic Memory StackFull – Is Stack Full
25
Stack.hpp
# ifndef STACK_CLASS //============================================
// ----------------------------- Includes -------------------------# include "Utilities.hpp"
// ----------------------------- Defines ---------------------------# define STACK_DIAGNOSTIC_LEVEL 1# define STACK_CLASS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Class Stack //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////class Stack{//You Do};
# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void TestStack (void);
# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------
# endif //STACK_CLASS ==============================================
Time To Think About Some Code There Are Poor Solutions, Good Solutions, Better Solutions!
26
2727
class Stack1{public:
Class Design Should Often Start With The Data!What Type Of Info Goes Into The Container?
Data Structures Are Often Data Driven
long int
What Is The Capacity Of The Container? 3
4
5# define MAX 6
// Constructor// Destructor// Push// Pop// Empty
private:
};
6
Need The Info Container?
long intInfo[5],
Info
0
1
2
Need Some Reference To Top?
MAXTop;
Top 28
# define MAX 5 class Stack1{public:// Constructor// Destructor// Push// Pop// Empty
private:long int
Info[MAX + 1],Top;
Design Really Poor Thus Far?
1
2
3
4
5
1
2
3
4
5All Stacks HaveTo Be The
Same Exact Size!
};
Stack1S1,S2;
Info
0
MAX
Top
Info
0
MAX
Top
S1S2
We Really Don’t Want To Have To Create One Class
For 6 integers, another for 10
integers, another for 100 integers,
etc.29 30
30
# 6
class StackInt{public:
StackInt (long int NewMax = 10);// Destructor// Push// Pop// Empty
i t
What If We Used DynamicMemory & Passed The Size?
StackInt Design is Betterprivate:
long int*Info,Max,Top;
};
StackIntS1,S2(5),S3(100);
Info
Max
TopS1
Than Stack1 Design?
31
StackInt::StackInt(long int NewMax){
Max = NewMax;Info = new long int [Max + 1];if (Info == NULL){
puts (“Out Of Memory In StackInt()”);Max = -1;
}Top = -1; // Empty
The StackInt Constructor
0
1
2
3
4
5
?
?
?
?
?
?
p ; p y};
StackIntS1(5);
Info
Max
TopS1
Not the best constructor, but it works!
-1
5
&1000
0 ?
Since we really don’t care, or know what memory block is going to be assigned by
the compiler, we shall abbreviate the memory map as follows: 32
StackInt::~StackInt (void){
if (Info != NULL)delete [] Info;
}
The StackInt Destructor
1
2
3
4
5
?
?
?
?
?
Max
TopS1
-1
5
Info
0 ?
33
bool StackInt::Empty (void){
if (Top ==-1)return (true);
elsereturn (false);
}
The StackInt Empty
1
2
3
4
5
?
?
?
?
?
0
1
2
3
4
5
A
B
C
?
?
?
Max
TopS2
-1
5
Info
0 ?
Max
TopS1
2
5
Info
0 A
S2 is Empty
S1 is not Empty
if (S1.Empty() )
34
bool StackInt::Full (void){
if (Top == Max)return (true);
elsereturn (false);
}
The StackInt Full
1
2
3
4
5
?
?
?
?
?
0
1
2
3
4
5
A
B
C
D
E
F
Max
TopS2
0
5
Info
0 A
Max
TopS1
5
5
Info
0 A
S2 is Empty
S1 is not Empty
if (S1.Full() )
Better Than if (Top == Max - 1) 35
bool StackInt::Push (long int NewInfo){
if (Full())return (UNSUCCESSFUL);
else{
Top = Top + 1;Info[Top] = NewInfo;return (SUCCESSFUL);
}
The StackInt Push
0
1
2
3
4
5
A
?
?
?
?
?
0
1
2
3
4
5
A
B
C
D
E
F
}
Max
TopS2
0
5
Info
Max
TopS1
5
5
Info
S2 is EmptyS1 is Full
In Utilities.hpp
# define SUCCESSFUL 1# define UNSUCCESSFUL 0or# define SUCCESSFUL true# define UNSUCCESSFUL false
if (S1.Push(B) )
Readability is the Goal!
36
# 7
bool StackInt::Pop (long int &OldInfo){
if (Empty())return (UNSUCCESSFUL);
else{
OldInfo = Info[Top];Top = Top -1;return (SUCCESSFUL);
}}
The StackInt Pop
0
1
2
3
4
5
A
?
?
?
?
?
0
1
2
3
4
5
A
B
C
D
E
F
Max
TopS2
0
5
Info
Max
TopS1
5
5
Info
S2 is EmptyS1 is Full
•We will eventually place many things on the stack. •Not all data types can be explicitly returned. •Items are placed on a stack to be used.
if (S1.Pop(B) )
Readability is the Goal!
37
bool StackInt::StackTop (long int &OldInfo)
{if (Empty())
return (UNSUCCESSFUL);else
{OldInfo = Info[Top];return (SUCCESSFUL);
}}
The StackInt StackTop
0
1
2
3
4
5
A
?
?
?
?
?
0
1
2
3
4
5
A
B
C
D
E
F
Max
TopS2
0
5
Info
Max
TopS1
5
5
Info
S2 is EmptyS1 is Full
if (S1.StackTop(C))if (C == ?)
Readability is the Goal!
38
void Stack :: Display(char Message[], long int NoToDisplay) {long int
Postition,DisplayMax;
if (NoToDisplay == -1)
DisplayMax = Max;
else
DisplayMax = Top;
if(strlen(Message) > 0)puts(Message);
for (Postition = DisplayMax; Postition >= 0; Postition--) {
puts(" ------------------------------------------------------");
fflush(stdout);
Some type of Displayis essential to proper
diagnostic testing!
cout << setw(5) << Postition << "| ";
cout << setw(50) << Info[Postition];
cout << " |\n";
cout.flush();
}
if ((NoToDisplay == -1) || (Top >=0)){
puts(" ------------------------------------------------------");printf(" Top = %3ld Max Stack = %3ld", Top, Max);printf(" Info = & %X\n\n\n", Info);
}
if(Top = -1)
puts("\nStack Is Empty\n");
}
39 4040
class StackInt{public:
StackInt (long int NewMax = 10);~StackInt (void);bool Empty (void);bool Full (void);bool Pop (long int & OldInfo);bool Push (long int NewInfo);bool StackTop (long int & OldInfo);
# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="", long int NoToDisplay = 0);
# dif //
Putting It All Together!
Good But Not Great!
# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------
private:long int
*Info;long int
Max,Top;
}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------
void TestStackInt (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------
# endif //STACK_CLASS ==============================================
Why Not Great?
What If We NeededA Stack For float, char,int, short int, double,
Athlete, Part, Employee, etc.?
41 4242
# 8
class StackFloat{public:
StackFloat (long int NewMax = 10);~StackFloat (void);bool Empty (void);bool Full (void);bool Pop ( float & OldInfo);
bool Push ( float NewInfo);
bool StackTop ( float & OldInfo);
# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="" long int NoToDisplay = 0);
Change long int to float
Rename Class, Constructor, Destructor
void Display(char Message[]= , long int NoToDisplay = 0);# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------
private:float
*Info;long int
Max,Top;
}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------
void TestStackFloat (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------
# endif //STACK_CLASS ==============================================
43 4444
class StackChar{public:
StackChar (long int NewMax = 10);~StackChar (void);bool Empty (void);bool Full (void);bool Pop ( char & OldInfo);
bool Push ( char NewInfo);
bool StackTop ( char & OldInfo);
# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="" long int NoToDisplay = 0);
Change long int to char
Rename Class, Constructor, Destructor
void Display(char Message[]= , long int NoToDisplay = 0);# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------
private:char
*Info;long int
Max,Top;
}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------
void TestStackFloat (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------
# endif //STACK_CLASS ==============================================
Could Do Likewise for Employee, short int, double, Athlete, etc.
45 4646
4747
typedef long int InfoType; class Stack{public:
StackInt (long int NewMax = 10);~StackInt (void);bool Empty (void);bool Full (void);bool Pop (InfoType & OldInfo);bool Push (InfoType NewInfo);bool StackTop (InfoType & OldInfo);
# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------void Display(char Message[]="" long int NoToDisplay = 0);
This is even better; only one change is required
to transfer the stack from onedatatype to another.
void Display(char Message[]= , long int NoToDisplay = 0);# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------
private:InfoType
*Info;long int
Max,Top;
}; # ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------
void TestStackInt (void);# endif // STACK_DIAGNOSTIC_LEVEL ----------------------------------
# endif //STACK_CLASS ==============================================
Many Languages havesome type of TypeDef
Including C & C++
Problem?What if a single
program has two stacks of different
datatypes?
48
# 9
4949
5050
typedef int T;void Swap (T & Value1, T & Value2){T
Temp;
Temp = Value1;Value1 = Value2;Value2 = Temp;
}
TypeDef Swap Function – Restricted to one Datatype Per Program!
template <class T>void Swap (T & Value1, T & Value2){T
Temp;
Temp = Value1;Value1 = Value2;Value2 = Temp;
}
Template Swap Function – Not Restricted to one Datatype Per Program!
51
Templates are used to achieve type-independent logic and abstraction
void TestSwap(void){int
A = 5, B = 10;cout << "A = " << A << " B = " << B << endl;Swap (A, B);cout << "A = " << A << " B = " << B << endl;
double AA = 5.5, BB = 5.6;cout << "AA = " << AA << " BB = " << BB << endl;Swap (AA, BB);
If you have never done a template function, create your own Swap and test it!
52
p ,cout << "AA = " << AA << " BB = " << BB << endl;
char AAA = 'X', BBB = 'O';cout << "AAA = " << AAA << " BBB = " << BBB << endl;Swap (AAA, BBB);cout << "AAA = " << AAA << " BBB = " << BBB << endl;
EmployeeE1(“Road”, “Runner”, 111),E2 (“Roger”, “Rabbit”, 222); E1.Display(“Road Runner”);E2.Display(“Roger Rabbit”);
Swap(E1, E1); E1.Display(“Roger Rabbit”);E2.Display(“Road Runner”);
}
Function Templatetemplate <class T>void Swap (T & Value1, T & Value2){T
Temp;
Temp = Value1;Value1 = Value2;Value2 = Temp;
}
template <class InfoType>class Stack{
...public:
InfoType* Info;
};
53
Templates are not really functions. They are more of a design or pattern for what shall become a function
if evoked.
The compiler shall generate the necessary variations of this function during run time.
Must be placed in .hpp files!
Template - Multiple Parameterstemplate <class InfoType, class HeaderNodeType>class Binary Tree{
...};
These did not work properly in GNU C++ twoyears ago.
An important goal of both software
54
p gengineering and object-oriented
programming is reuse!
Function Templates facilitate code reuse!
# 10
5555 56
5757
template <class InfoType> class Stack{public:
Stack (long int NewMax = 10);~Stack (void);bool Empty (void);bool Full (void);bool Pop (InfoType & OldInfo);bool Push (InfoType NewInfo);bool StackTop (InfoType & OldInfo);bool Resize(long int SizeChange = 10);bool operator = (const Stack & S);
Datatype Independent!
If stack is full, attempt to Resize it on the fly!
Deep Copy!# ifdef STACK_DIAGNOSTIC_LEVEL //-----------------------------------
void Display(char Message[]="", long int NoToDisplay = 0);# endif // STACK_DIAGNOSTIC_LEVEL ---------------------------
private:InfoType
*Info;long int
Max,Top;
};
Deep Copy!
Not Many Changes RequiredTo Get This Generic Solution!
58
template <class InfoType>Stack <InfoType> ::Stack (long int NewMax){# ifdef STACK_DIAGNOSTIC_LEVEL //----------------
if (STACK_DIAGNOSTIC_LEVEL <= 1)puts (“Evoking Constructor Stack(NewMax)”);
# endif // STACK_DIAGNOSTIC_LEVEL ---------------
if (NewMax <= 0)Max = 10;
else
Really Good Stack Constructor
0
1
2
3
4
5
?
?
?
?
?
?
Critical Error IfProgrammer Accidently
Creates An Array OfelseMax = NewMax;
Info = new InfoType [Max+1];if (Info == NULL){
puts (“Out Of Memory In StackInt()”);Max = -1;
}Top = -1; // Empty
}
Stack <char>S1(5);
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
Creates An Array Of Negative Size!
59
Stack <int>IntStack1;
IntStack1.Display(“Contents Of IntStack1”, -1);
IntStack1 shall contain 11 Part elements – the default. Since the built in int class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.
60
# 11
Stack <float>FloatStack4(4);
FloatStack5.Display(“Contents Of FloatStack4”, -1);
FloatStack4 shall contain 5 float elements – the default. Since the built in Float class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.
61
Stack <char>CharStack5(5);
CharStack5.Display(“Contents Of CharStack5”, -1);
CharStack5 shall contain 6 char elements. Since the built in char class has no initialization in the constructor, the contents of this container is initialized to garbage in memory.
62
Stack <Student>ClassStack8(8);
ClassStack8.Display(“Contents Of ClassStack8”, -1);
ClassStack8 shall contain 9 Student elements. Since the Student class has a constructor to initialize the data, the contents of this container is initialized accordingly!
63
Stack <Auto>GarageStack9(9);
GarageStack9.Display(“Contents Of GarageStack9”, -1);
GarageStack9 shall contain 10 Auto elements. Since the Auto class has a constructor to initialize the data, the contents of this container is initialized accordingly!
64
template <class InfoType>Stack <InfoType> ::~Stack (void){# ifdef STACK_DIAGNOSTIC_LEVEL //----------------
if (STACK_DIAGNOSTIC_LEVEL <= 1)puts (“Evoking Destructor ~Stack()”);
# endif // STACK_DIAGNOSTIC_LEVEL ---------------
if (Info != NULL)delete [] Info;
}
Really Good Stack Destructor
0
1
2
3
4
5
?
?
?
?
?
?
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!65
template <class InfoType>bool Stack <InfoType> ::Empty (void){
if (Top ==-1)return (true);
elsereturn (false);
}
Really Good Stack Empty
0
1
2
3
4
5
?
?
?
?
?
?
if (S1.Empty() )
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
66
# 12
template <class InfoType>bool Stack <InfoType> ::Full (void){
if (Top >= Max)return (true);
elsereturn (false);
}
Really Good Stack Full
0
1
2
3
4
5
?
?
?
?
?
?
if (S1.Full() )
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
67
template <class InfoType>bool Stack <InfoType> ::Push (long int NewInfo){
if (Full())if (!Resize() )
return (UNSUCCESSFUL);
Top = Top + 1;Info[Top] = NewInfo;return (SUCCESSFUL);
}
Really Good Stack Push
0
1
2
3
4
5
?
?
?
?
?
?
}
if (S1.Push(‘B’) )
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
“Overflow” – An attempt to exceed theCapacity of the container.
68
template <class InfoType>bool Stack <InfoType> ::Pop (long int &OldInfo){
if (Empty())return (UNSUCCESSFUL);
else{
OldInfo = Info[Top];Top = Top -1;return (SUCCESSFUL);
}
Really Good Stack Pop
0
1
2
3
4
5
?
?
?
?
?
?
}}
if (S1.Pop(TopInfo) ) S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
“Underflow” – An attempt to take more From the container than it contains
69
template <class InfoType>bool Stack <InfoType> :: StackTop (long int &OldInfo){
if (Empty)return (UNSUCCESSFUL);
else{
OldInfo = Info[Top];return (SUCCESSFUL);
}}
Really Good Stack StackTop
0
1
2
3
4
5
?
?
?
?
?
?
}
if (S1.StackTop(C))if (C == ?)
S1
Info
Max
Top-1
5
Not Many Changes RequiredTo Get This Generic Solution!
70
Really Good Stack Display
Not Many Changes RequiredTo Get This Generic Solution!
# ifdef STACK_DIAGNOSTIC_LEVEL //---------------------------------------------------
template <class InfoType>
void Stack <InfoType> :: Display(char Message[], long int NoToDisplay) {long int
Postition,DisplayMax;
if (NoToDisplay == -1)
DisplayMax = Max;else
DisplayMax = Top;
if(strlen(Message) > 0)puts(Message);
for (Postition = DisplayMax; Postition >= 0; Postition--) {
puts(" ------------------------------------------------------");
Our Display Is Only Used During Testing!//# define STACK_DIAGNOSTIC_LEVEL 1
It Can Only Be Used To Display Those Classes That Overload <<
puts( ------------------------------------------------------ );fflush(stdout);cout << setw(5) << Postition << "| ";cout << setw(50) << Info[Postition]; cout << " |\n";cout.flush();
} if ((NoToDisplay == -1) || (Top >=0)){
puts(" ------------------------------------------------------");printf(" Top = %3ld Max Stack = %3ld", Top, Max);printf(" Info = & %X\n\n\n", Info);
}
if(Top = -1)
puts("\nStack Is Empty\n");
}
# endif // STACK_DIAGNOSTIC_LEVEL --------------------------------------------------
71
template <class InfoType>bool Stack <InfoType> :: Resize (long int SizeChange){long int
Pos,NewMax = Max + SizeChange;
InfoType* NewInfo;
// Create New Block Of MemoryNewInfo = new InfoType [NewMax + 1];
Marginally OK Stack Resize
0
1
2
3
4
5
?
?
?
?
?
?
ew o ew o ype [ ew a ];if (NewInfo == NULL)
return (UNSUCCESSFUL);
// Copy Data To New Block Of Memoryfor (Pos = 0; Pos <= Max; Pos ++)
NewInfo[Pos] = Info[Pos];
// Update Other Stuffdelete [] Info;Info = NewInfo;Max = NewMax;return (SUCCESSFUL);
}
S1
Info
Max
Top-1
5
Assumes SizeChange is Positive!What if pass Negative SizeChange?
// Can't make array smallerif (SizeChange < 1)
return (UNSUCCESSFUL);
72
# 13
If we do not overload the = operator, then we would have the following Shallow Copy
73
Shallow Copy pygenerates
Memory Leak
74
overload = operator,
Deep Copy
75
Deep Copy p pyReturned Memory
& 7F0894
No Memory Leak
76
template <class InfoType> void Stack <InfoType> :: operator = (const Stack & S){long int
Pos;InfoType
* NewInfo;
// Create Properly Sized Info ContainerNewInfo = new InfoType [S.Max + 1];if (NewInfo == NULL)
Good Stack operator = Overload
0
1
2
3
4
5
?
?
?
?
?
?
return;
// Free the memory associated with Info if (Info != NULL)
delete [] Info;
Max = S.Max;Top = S.Top;Info = NewInfo;
// Copy Infofor (Pos = 0; Pos <= Max; Pos ++)
Info[Pos] = S.Info[Pos]; }
S1
Info
Max
Top-1
5
77
Athlete Trinity[50];
long intPos;
Stack <Athlete>CSCI2320 (3), CSCI3343(3);
Trinity[1].Set ("Sarah", 1001, 1, 11.11), Trinity[2].Set ("Michael", 1002, 11, 22.22), Trinity[3].Set ("Rebecca", 1002, 2, 33.33), Trinity[4].Set ("Thomas", 1004, 12, 44.44);
for (Pos = 1; Pos <= 4; Pos++)CSCI2320.Push(Trinity[Pos]);
CSCI2320.Display("CSCI2320 is full with 4", -1);
Copy Constructor
CSCI3343.Display("CSCI3343 is Empty With 10", -1);
CSCI3343 = CSCI2320;
The Deep Copy Assignment is necessary and essential, but if the only objective is only to create one Stack that is a duplicate of the other, why take the time to initialize a stack – only to destroy it and copy it.
Most ADT’s use a Copy Constructor to save that wasted effort.
Stack <Athlete>CSCI2320 (CSCI2320);
Stack (const Stack & S);
Class Prototype Left As An Exercise For You!78
# 14
Stack <int>Quatity (4);
Stack <char>Prefix (10);
Stack <float>Cost (3);
Stack <Book>TU_Library (6000),
Testing – All in the same program
0
1
2
3
4
5
?
?
?
?
?
?
BookStop;
Stack <Client>SmithBarney (5),DataAbstractions;
Stack <Part>Inventory (-5),SearsWarehouse;
Stack <Athlete>Football(40),Softball(33);
S1
Info
Max
Top-1
5
Not Possible With one Block Of Class Code In Most Languages!
79
Remember The Microsoft Office ExampleStructured Language
Developed Windows Version FirstMac Version Cost 88% of Windows Version
C++Developed Windows Version FirstWrote Parallel Versions Of A Few Short Utilities To Open/Close File, Move Cursor To Row/Col, Minimize Window, etc. using the basic operating system calls.Mac Version Ran In One Day – had to tweek screen because of different pixel
80
resolution – alter images on user manual.
Function Overloads Operator Overloads .hpp & .cpp Separation Stream overloads
Templates
80
8181
82
82
83
83
8484
# 15
Dynamic Memory Allocation 1short int
E, // Variable E contains garbage*F; // Pointer F contains garbage
E = 5;// To display the contents of container E
printf (" E = %d\n", E);
// To display the where container E is stored in memory (i.e. the address of E)printf (" &E = %ld = %x \n", &E, &E);
// To display the sizeof container E (i.e. 2)printf (" sizeof(E) = %ld bytes \n", sizeof(E));
// To display where pointer F is stored in memory (i.e. the address of F)printf (" &F = %ld = %x\n" &F &F);
E = 5&E = 1245052 = 12ff7c sizeof(E) = 2 bytes &F = 1245048 = 12ff78sizeof(F) = 4 bytes *F = 5E = 32766*F = 32766
printf (" &F = %ld = %x\n", &F, &F);
// To display the sizeof container F (i.e. 4)printf (" sizeof(F) = %ld bytes \n", sizeof(F));
// To make pointer F point to variable E memory containerF = & E;
// To display the memory pointed to by pointer F (i.e. variable E = 5)printf (" *F = %d\n", *F);
// To change the value of the memory pointed to by F to 32766 (i.e. E to 32766)(*F) = 32766;printf (" E = %d\n", E);printf (" *F = %d\n", *F);
// To increase the value of E(*F)++;E++;
85
Dynamic Memory Allocation 2
char *F; // Pointer F contains garbage
// To display the garbage memory associated with Fprintf ("1 F = %ld = %x\n", F, F); // Garbage in memory
// To allocate 1 character of memory for FF = new char;printf ("2 F = %ld = %x\n", F, F); // NULL if no memory
1 F = -858993460 = cccccccc2 F = 4457376 = 4403a03 sizeof(F) = 4 bytes 4 *F = A5 *F = 656 *F = 667 F = 4457376 = 4403a08 F = 0 = 0
// To display the sizeof container F (i.e. 4)printf ("3 sizeof(F) = %ld bytes \n", sizeof(F));
// To change the value of the memory pointed to by F to 'A')(*F) = 'A';printf ("4 *F = %c\n", *F);printf ("5 *F = %d\n", *F); // ASCII Value of A
// To increment the value of the memory pointed to by F(*F)++;printf ("6 *F = %c\n", *F);
// To return the memory associated with pointer Fdelete F;printf ("7 F = %ld = %x\n", F, F); // Dangling/Stale PointerF = NULL;printf ("8 F = %ld = %x\n", F, F); // Good computer scientist assigns ptrs NULL
86
short int E = 1,*F;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nMake F Point To Container E\n");F = & E;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nUse Pointer F to Change Memory Associated With It\n");(*F) = 32766;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nTwo Ways To Change Memory associated with variable E\n");E++;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");puts ("\nMax Value For 2 Byte [2's Complement] = 32767 - Overflow E\n");E++;SketchShortInt(E, &E, "E");SketchShortIntPtr(F, &F, "F");
Dynamic Memory Allocation Memory Map Code
void SketchShortInt(short int ContainerContents, short int * ContainerAddress, char ContainerName[])
{printf (" %-3s - %ld Bytes - short int\n", ContainerName, sizeof(short int));printf (" |--------------------------------|\n");// Print Contents in Decimal and then Hexadecimalprintf (" | %14d | %13x |\n", ContainerContents, ContainerContents);printf (" |--------------------------------|\n");// Print Address in Decimal and then Hexadecimalprintf (" &%ld - &%x\n\n", ContainerAddress, ContainerAddress);
}
void SketchShortIntPtr(short int * ContainerContents, short int ** ContainerAddress, char ContainerName[])
{printf (" %-3s - %ld Bytes - short int*\n", ContainerName, sizeof(short int*));printf (" |----------------------------------------------------|\n");printf (" | %50d |\n", ContainerContents);printf (" |----------------------------------------------------|\n");printf (" &%ld - &%x\n\n", ContainerAddress, ContainerAddress); //Address Decimal - Hex
}
87