Need to implement stack using array only, methods: push, pop, print. The task itself: Implement stack using only array. The only time compiler should allocate memory is through set_size function. The current code version works good enough, but I'm looking for ways to improve it's exec-time / complexity / readability etc. Any ideas? Thank you in advance.
#include <vector>
#include <string>
template <class T>
class Stack
{
int size = 0;
T* Array;
int top = 0;
public:
Stack(size_t Size);
~Stack()
{
delete[] Array;
}
void push(T element);
void pop();
void print();
};
template <class T>
Stack<T>::Stack(size_t Size)
{
size = Size;
top = -1;
Array = new T[size];
}
template <class T>
void Stack<T>::push(T element)
{
if (top >= (size - 1))
{
std::cout << "overflow" << std::endl;
}
else
{
Array[++top] = element;
}
}
template <class T>
void Stack<T>::pop()
{
if (top < 0)
{
std::cout << "underflow" << std::endl;
}
else
{
std::cout << Array[top--] << std::endl;
}
}
template <class T>
void Stack<T>::print()
{
if (top == -1)
{
std::cout << "empty" << std::endl;
}
int i = top;
while (i > -1)
{
std::cout << Array[i--] << " ";
}
std::cout << std::endl;
}
template <class T>
Stack<T> set_size(int Size)
{
return Stack<T>(Size);
}
int main()
{
auto stack = set_size<std::string>(5);
stack.push("hello");
stack.push("hi");
stack.push("hey");
stack.push("greetings");
stack.push("welcome");
stack.print();
stack.pop();
stack.pop();
stack.print();
return 0;
}```