August
1999 QUESTION 2 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
(a) | Explain, using an appropriate example, the term coercion. | [3] |
Coercion is:
|
||
(b) | Consider the
following declaration of a Stack in C++: template
<class T> public: } (i) The polymorphic function reverse takes a reference to a stack s,
and changes it so that its items are in reverse order. template <class T> (ii) The polymorphic function Split takes a reference to a stack s and splits s up into two stacks. The function returns a stack which consists of the first n items of s, and also removes the first n items from s. It there are less than n items in s, then the function returns a copy of s, and s has all its items removed. For example, if the integer stack s = (8,7,6,5,4,3,2,1)
were passed to (iii) The polymorphic function Slice takes a reference to a stack s, and two integer parameters x and y. The function removes the xth to the yth items from s, inclusive. If there are less than x items, then s remains unchanged; if there are less than y items, then all items from x to the bottom of the stack are removed. Copy and complete, the following definition of Slice : template <class T>
|
[5]
[6] |
(i) A sample definition of reverse follows: temple <class T> void reverse(Stack<T>& s) { Stack<T> t; while(!s.empty ( ) ) t.push(s.pop ( ) ); s= t; }
|
||
(ii) A sample definitioin of Split follows: template <class T> Stack<T> Split(Stack<T>& s, int n) } Stack<T> t;
for (i= 0; i< n; i++) reverse(t);
|
||
(iii) A sample definition of Slice follows: template <class T> void Slice(Stack<T>& s, int x, int y) { Stack<T> t; for (i= 1; i<= s,size ( ); i++) reverse(t);
|