Consider the stack classes created in Lecture 3 and included in file Lecture3Code- CandOOPStacks. Rewrite this class using a valarray for storing the data. Add methods void clear ( ), bool isEmpty ( ) and int getSize ( ). The first erases the stack content and makes size = 0. The second returns true if the stack is empty. The third returns the number of the items currently in the stack. Write an application to test the functions of the stack. Use separate compilation and separate interface from implementation from application.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
void error (string message);
const int SIZE = 20;
class Stack {
private:
char data[SIZE];
int size;
public:
Stack () { size = 0; }
char pop() {
if (size == 0) error("Underflow");
return data[--size];
}
void push(char v) {
if (size == SIZE) error("Overflow");
data[size++] = v;
}
};
void error (string message) {
cout << "\n" << message << "\n";
exit (1);
}
int main () {
Stack stack;
stack.push ('a');
stack.push ('b');
stack.push ('c');
cout << stack.pop() << " ";
cout << stack.pop() << " ";
cout << stack.pop() << " ";
cout << stack.pop() << " ";
}
Aucun commentaire:
Enregistrer un commentaire