Implement stacks using dynamic array
#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;
}
}
Comments
Leave a comment