Download presentation

Presentation is loading. Please wait.

Published byAnjali Beson Modified about 1 year ago

1
Chapter 3 1

2
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated to any data type, irrespective of whether this data type is a fundamental C++ type or a user- defined type. 2

3
Selection sort using templates 3 template void SelectionSort ( T *a, const int n ) {// Sort a[0] to a[n-1] into nondecreasing order. for ( int i = 0 ; i < n ; i++ ) { int j = i; // find smallest integer in a[i] to a[n-1] for ( int k = i + 1 ; k < n ; k++ ) if ( a[k] < a[j] ) j = k; swap ( a[i], a[j] ); } }

4
Code fragment illustration template instantiation float farray [ 100 ]; int intarray [ 250 ];.. // assume that the arrays are initialized at this point SelectionSort ( farray, 100 ); SelectionSort ( intarray, 250 ); 4

5
Stack Last-In-First-Out (LIFO) list Push Add an element into a stack Pop Get and delete an element from a stack 5 pushpop

6
System stack after function call 6

7
Abstract data type Stack template class Stack { // A finite ordered list with zero or more elements public: Stack (int stackCapacity = 10); // Create an empty stack whose initial capacity is stackCapacity bool IsEmpty ( ) const; // if empty, return true; else, return false. T& Top ( ) const; // Return top element of stack. void Push (const T& item); // Insert item into the top of the stack. void Pop ( ); // Delete the top element of the stack. }; 7

8
Implementation private: int top; T *stack; int capacity; template Stack ::Stack(int stackCapacity): MaxSize(stackCapacity) { stack=new T[capacity]; top=-1; } 8

9
template inline Boolean Stack ::IsFull() { if (top==capacity-1) return TRUE; else return FALSE; } template inline Boolean Stack ::IsEmpty() { if (top==-1) return TRUE; else return FALSE; } 9

10
Adding to a stack template void Stack ::Push (const T& x) { // Add x to the stack. if (top = = capacity – 1) { ChangeSize1D (stack, capacity, 2 * capacity); capacity *= 2; } stack [ ++top ] = x; } 10

11
Deleting from a stack template void Stack ::Pop ( ) { // Delete top element from the stack. if (IsEmpty ( ) ) throw “Stack is empty. Cannot delete.”; stack [ top-- ].~T(); // destructor for T } 11

12
Queue First-In-First-Out (FIFO) list Add an element into a queue Get and delete an element from a queue Variation Priority queue 12 A AB ABC ABCD ABCDE BCDE ↑ ↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ f, r fr f r f r f r f r add delete f = queue front r = queue rear

13
Abstract data type Queue template class Queue { public: Queue (int queueCapacity = 10); // Create an empty queue whose initial capacity is stackCapacity bool IsEmpty ( ) const; // If empty, return true; else, return false. T& Front ( ) const; // Return the element at the front of the queue. T& Rear ( ) const; // Return the element at the rear of the queue. void Push (const T& item); // Insert item at the rear of the queue. void Pop ( ); // Delete the front element of the queue. } ; 13

14
Implementation private: int front,rear; T *queue; int capacity; template Queue ::Queue(int queueCapacity):capacity(queueCapacity) { queue=new T[capacity]; front=rear= 0; } 14

15
template inline Boolean Queue ::IsFull() { if (rear==capacity-1) return TRUE; else return FALSE; } template inline Boolean Stack ::IsEmpty() { if (front==rear) return TRUE; else return FALSE; } 15

16
Circular queue Two indices front: one position clockwise from the first element rear: current end 16

17
Adding to a queue template void Queue ::Push(const& x); { // Add x at rear of queue. if ((rear + 1) % capacity = = front) { // queue full, double capacity // omit } rear = (rear + 1) % capcity; queue [rear ] = x; } 17

18
Deleting from a queue template void Queue ::Pop( ); { // Delete front element from queue. if (IsEmpty( )) throw "Queue is empty. Cannot delete."; front = (front + 1) % capacity; queue [front ]. ̃T(); // destructor for T } 18

19
Problem: if front=rear? 19 Increase the capacity of a queue just before it become full

20
A mazing problem 20 0: path1: block

21
Allowable moves 21

22
Data type move struct offsets { int a,b; }; enum directions{ N, NE, E, SE, S, SW, W, NW}; offsets move[8]; 22

23
Table of moves qmove[q ].amove[q ].b N −1 0 NE −1 1 E 0 1 SE 1 1 S 1 0 SW 1−1 W 0 NW −1 23

24
Implementation with a stack A maze is represented by a two dimensional array maze[m][p] struct Items{ int x, y, dir; }; 24

25
Example in → 0000 0100 0111 0000 →out Stack (x,y,dir) PositionAction (1,1)Mark (1,1) (1,1,2)(1,2)Mark (1,2) (1,2,2) (1,1,2) (1,3)Mark (1,3) (1,3,2) (1,2,2) (1,1,2) (1,4)Mark (1,4) ……… 25 Stack (x,y,dir) PositionAction (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,4)Mark (2,4) ……… (2,4,6) (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,3)Mark (2,3) (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,4)pop

26
Example in → 0000 0100 0111 0000 →out Stack (x,y,dir) PositionAction (1,3,2) (1,2,2) (1,1,2) (1,4)pop (1,2,2) (1,1,2) (1,3)pop (1,1,2)(1,2)pop (1,2,5) (1,1,2) (2,1)Mark (2,1) ……… 26

27
First pass at finding a path through a maze Initialize list to the maze entrance coordinates and direction east; while (list is not empty) { (i, j, dir) = coordinates and direction from end of list; delete last element of list; while (there are more moves from (i, j) ) { (g, h) = next move; if ((g = = m) && (h = = p)) sucess; if ((!maze [g][h]) // legal move && (!mark [g][h])) // haven’t been here before { mark [g ][h] = 1; dir = next direction to try; add (i, j, dir) to end of list; (i, j, dir) = (g, h, N) ; } } } cout << "No path in maze." << endl; 27

28
Finding a path through a maze void Path(const int m, const int p) { // start at (1, 1) mark[1][1] = 1; Stack stack(m*p); Items temp(1, 1, E); // set temp.x, temp.y, and temp.dir Stack.Push(temp); while (!stack.IsEmpty( )) { 28

29
temp = stack.Top( ); stack.Pop( ); int i = temp.x; int j = temp.y; int d = temp.dir; while (d < 8) // move forward { int g = i + move[d].a; int h = j + move[d].b; if ((g = = m) && (h = = p)) { // reached exit // output path cout << stack; cout << i << " " << j << endl; cout << m << " " << p << endl; return; } if ((!maze [g ][h]) && (!mark [g ][h])) { // new position mark[g][h] = 1; temp.x = i; temp.y = j; temp.dir = d+1; stack.Push(temp); // stack it i = g; j = h; d = N; // move to (g, h) else d++; // try next direction } } cout << "No path in maze." << endl; } 29

30
Evaluation of expressions X = a / b - c + d * e - a * c Suppose that a = 4, b = 2, c = 2, d =3, e = 3 Interpretation 1: ((4/2)-2)+(3*3)-(4*2)=0 + 8+9=1 Interpretation 2: (4/(2-2+3))*(3-4)*2=(4/3)*(-1)*2= -2.66666… How to generate the machine instructions corresponding to a given expression? Precedence rule + associative rule 30

31
Priority of operators in C++ 31 PriorityOperator 1unary minus, ! 2*, /, % 3+, - 4 =, > 5= =, != 6&& 7||

32
Evaluation of expressions Infix Each operator comes in-between the operands Eg. 2+3 Postfix Each operator appears after its operands Eg. 23+ Prefix Each operator appears before its operands Eg. +23 32

33
Example InfixPostfix 2+3*4234*+ a*b+5ab*5+ (1+2)*712+7* a*b/cab*c/ (a/(b-c+d))*(e-a)*cabc-d+/ea-*c* a/b-c+d*e-a*cab/c-de*ac*-+ 33

34
Example: 6/2-3+4*2 62/3-42*+ 34 TokenStack [0] [1] [2] Top 62/3-42*+62/3-42*+ 6 6 2 6/2 6/2 3 6/2-3 6/2-3 4 6/2-3 4 2 6/2-3 4*2 6/2-3+4*2 010101210010101210

35
Evaluating postfix expressions void Eval(Expression e) {// Assume that the last token in e is ‘#’ // NextToken is used to get the next token from e Stack stack; // initialize stack for (Token x = NextToken(e); x!= ‘#’; x=NextToken(e)) if (x is an operand) stack.Push(x) // add to stack else {// operator remove the correct number of operands for operator x from stack; perform the operation x and store the result onto the stack; } 35

36
Infix to postfix (1) Fully parenthesize expression a / b - c + d * e - a * c ((((a / b) - c) + (d * e)) – (a * c)) (2) All operators replace their corresponding right parentheses. ((((a / b) - c) + (d * e)) - a * c)) (3) Delete all parentheses. ab/c-de*+ac*- 36

37
Example: a+b*c 37 TokenStack [0] [1] [2] TopOutput a + b * c eos + + * 0 1 a ab abc abc*+

38
Example: a*b+c 38 TokenStack [0] [1] [2] TopOutput a * b + c eos **++**++ 0 1 a ab ab* ab*c ab*c+

39
Example: a*(b+c)*d 39 TokenStack [0] [1] [2] TopOutput a * ( b + c ) * d eos * * ( * ( + * 0 1 2 0 a ab abc abc+ abc+* abc+*d abc+*d*

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google