Data Structures Class Templates
Various data structures implemented using c++ class templates.
stack_impl.h
Go to the documentation of this file.
1 #pragma once
2 #include <iostream>
3 #include "stackerror.h"
4 
5 using namespace std;
6 
12 template <typename T>
13 Stack<T>::Stack (size_t s): s_size(s) {
14  arr = new T[s_size+1];
15  top = 0;
16 }
17 
18 template <typename T>
20  s_size = 0;
21  top = 0;
22  delete[] arr;
23  arr = nullptr;
24 }
25 
26 template <typename T>
27 void Stack<T>::push (T value) {
28  if (top == s_size)
29  throw StackOverflowError("Trying to push into a full stack!");
30  arr[++top] = value;
31 }
32 
33 template <typename T>
35  if (top == 0)
36  throw StackUnderflowError("Trying to pop off an empty stack!");
37  return arr[top--];
38 }
39 
40 template <typename T>
42  if (top == 0)
43  throw StackUnderflowError("The stack is empty!");
44  return arr[top];
45 }
46 
47 template <typename T>
49  size_t i;
50 
51  if (top == 0) {
52  cout << "Stack is empty.\n";
53  return;
54  }
55  for (i=top; i>0; i--)
56  cout << arr[i] << "\n";
57 }
Stack::~Stack
~Stack()
Destructor.
Definition: stack_impl.h:19
StackOverflowError
Exception class for Stack overflow runtime error.
Definition: stackoverflowerror.h:12
StackUnderflowError
Exception class for Stack underflow runtime error.
Definition: stackunderflowerror.h:12
stackerror.h
Contains implementation of StackError base exception class.
Stack::push
void push(T value)
Member function to push data into the stack.
Definition: stack_impl.h:27
Stack::display
void display()
Member function for displaying the stack.
Definition: stack_impl.h:48
Stack::Stack
Stack(size_t s=10)
Constructor.
Definition: stack_impl.h:13
Stack::stacktop
T stacktop()
Member function which returns element at top of the stack.
Definition: stack_impl.h:41
Stack::pop
T pop()
Member function which removes and returns element at the top of the stack.
Definition: stack_impl.h:34