1. Engineering
  2. Computer Science
  3. main should remain as is stack class implement template stack...

Question: main should remain as is stack class implement template stack...

Question details

main should remain as is

stack class

Implement template stack class that is capable of storing integer and string values. Write both header and implementation in one file (stack.h).

Private data fields:

  • data: An array with maximum size of 20. (Declare a constant in stack.h called MAX_SIZE and set it to 20.)
  • size: stores the current number of elements in the stack.

Public interface:

  • stack(): constructs an empty stack.
  • push(T val): inserts a new element (val) of type T (T could be integer or string) into the data. If the data array is full, this function should throw an overflow_error exception with error message "Called push on full stack.".
  • pop(): removes the last element from data. If the data array is empty, this function should throw an outofrange exception with error message "Called pop on empty stack.".
  • top(): returns the top element of stack (last inserted element). If stack is empty, this function should throw an underflow_error exception with error message "Called top on empty stack.".
  • empty(): returns true if the stack is empty otherwise it returns false.

main.cpp test harness

Use this main.cpp file for testing your stack.

#include 
#include 
#include "stack.h"
#include 

using namespace std;

int main()
{
   cout << "Enter a test number(1-5): ";
    int test;
    cin >> test;
    cout << endl;
   //tests constructor, push, pop, top and empty
   if (test == 1) {
       try{
          cout << "\nstack1 constructor called";
          stack stack1;
          if(stack1.empty()){
              cout<<"\nstack1 is empty.";
          }
          else{
              cout<<"\nstack1 is not empty";
          }
          cout << "\npush 10";
          stack1.push( 10 );
          cout << "\npush 20";
          stack1.push( 20 );
          cout << "\npush 30";
          stack1.push( 30 );
          cout << "\nstack1 top: ";
          cout< stack2;
          cout << "\nstack2 top: ";
          cout< stack3;
          cout<<"\npop from empty stack\n";
          stack3.pop();
          cout << endl;
       }
       catch(underflow_error & e){
           cout< stack4;
          cout << "\npush 20 elements";
          for(int i = 1; i <=20; ++i){
              stack4.push(i);
          }
          cout<<"\nstack4 top: ";
          cout< stack5;
          cout << "\npush A";
          stack5.push("A");
          cout << "\npush B";
          stack5.push("B");
          cout << "\npush C";
          stack5.push("C");
          cout << "\nstack5 top: ";
          cout<
Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution