Answer to Question #196019 in C++ for IRUM

Question #196019

Implement stacks using dynamic array


1
Expert's answer
2021-05-21T06:49:08-0400
#include <iostream>

class Stack
{
    int*   data_;
    size_t maxSize_;
    size_t currentSize_;

  public:

    Stack(size_t maxSize)
         :data_(new int[maxSize]), maxSize_(maxSize), currentSize_(0)
    {
    }

    ~Stack()
    {
        delete[] data_;
    }

    void Push(int v)
    {
        if(currentSize_ == maxSize_)
        {
            throw std::range_error("Stack is full");
        }

        data_[currentSize_++] = v;
    }

    int Pop()
    {
        if(currentSize_ == 0)
        {
            throw std::range_error("Stack is empty");
        }
        
        return data_[--currentSize_];
    }
};

int main()
{
    try
    {
        Stack s(3);

        std::cout << 0 << " " << 1 << " " << 2 << "\n";
        s.Push(0);
        s.Push(1);
        s.Push(2);
        
        int i0 = s.Pop();
        int i1 = s.Pop();
        int i2 = s.Pop();
        std::cout << i0 << " " << i1 << " " << i2 << "\n";

        //Expected error
        s.Pop();

        return 0;
    }

    catch(std::exception& err)
    {
        std::cout << "Error: " << err.what() << "\n";
        return 1;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog