#include #include using namespace std; /** * interface of a stack */ class IntegerStackInterface { public: // add value on top virtual void push(int value) = 0; // remove value on top virtual void pop() = 0; // return value on top virtual int top() = 0; // tells whether stack is empty virtual bool is_empty() = 0; }; /** * Implementation as a C array */ class IntegerStackAsArray : public IntegerStackInterface { protected: int max_elements; int index; int *elements; public: IntegerStackAsArray(int sz=10) { index = -1; elements = new int [max_elements = sz]; } ~IntegerStackAsArray() { delete [] elements; } void push(int value) { elements[++index] = value; } void pop() { --index; } int top() { return elements[index]; } bool is_empty() { return (index == -1) ? true : false; } }; /** * Implementation as a STL vector */ class IntegerStackAsVector : public IntegerStackInterface { protected: int max_elements; vector v; public: IntegerStackAsVector(int sz=10) { max_elements = sz; } ~IntegerStackAsVector() { } void push(int value) { v.push_back(value); } void pop() { v.pop_back(); } int top() { return v[v.size()-1]; } bool is_empty() { return (v.size() == 0) ? true : false; } }; /** * treatment using pointer access * add values 1, 2, ..., 10 * then compute sum by poping them */ void process_ptr(IntegerStackInterface *s) { for (int i=1; i<=10; ++i) { s->push(i); } int sum = 0; while (!s->is_empty()) { sum += s->top(); s->pop(); } cout << "sum = " << sum << endl; } /** * treatment using reference access * add values 1, 2, ..., 10 * then compute sum by poping them */ void process_ref(IntegerStackInterface& s) { for (int i=1; i<=10; ++i) { s.push(i); } int sum = 0; while (!s.is_empty()) { sum += s.top(); s.pop(); } cout << "sum = " << sum << endl; } int main() { IntegerStackAsArray s1; IntegerStackAsVector s2; process_ptr(&s1); process_ptr(&s2); process_ref(s1); process_ref(s2); }