Data Structures in C++
StaticStack.hpp
Go to the documentation of this file.
1 /**
2  * @author Douglas De Rizzo Meneghetti (douglasrizzom@gmail.com)
3  * @date 2017-6-14
4  * @brief Stack implementation using a native C++ array as data storage.
5  */
6 
7 #ifndef AULA1_STATICSTACK_HPP
8 #define AULA1_STATICSTACK_HPP
9 
10 #include <stdexcept>
11 #include <string>
12 #include "Stack.hpp"
13 
14 //! Stack implementation using a native C++ array as data storage.
15 //! \tparam T The type of object the data structure will contain
16 template<class T>
17 class StaticStack : public Stack<T> {
18  private:
19  int top, size;
20  T *data;
21 
22  public:
23  std::string getName() { return "Static Stack"; }
24 
25  //! Create a fixed-size stack
26  //! \param size the size of the stack
27  explicit StaticStack(int size) {
28  this->size = size;
29  top = - 1;
30  data = new T[size];
31  }
32 
33  //! create the structure and populate it with the data from the array
34  //! \param data an array with data with which the structure will be initialized
35  explicit StaticStack(T data[]) : this->data(data) {
36  top = sizeof(data) / sizeof(data[0]);
37  }
38 
39  ~StaticStack() { delete[]data; }
40 
41  void push(T val) {
42  if (isFull())
43  throw std::out_of_range("The stack is full.");
44  data[++ top] = val;
45  }
46 
47  T pop() {
48  if (isEmpty())
49  throw std::out_of_range("The stack is empty.");
50  return data[top --];
51  }
52 
53  T peek() {
54  if (isEmpty())
55  throw std::out_of_range("The stack is empty.");
56  return data[top];
57  }
58 
59  int getSize() {
60  return top + 1;
61  }
62 
63  bool isEmpty() {
64  return top == - 1;
65  }
66 
67  bool isFull() {
68  return top == size - 1;
69  }
70 };
71 
72 #endif
int getSize()
Outputs the number of elements stored in the structure.
Definition: StaticStack.hpp:59
StaticStack(T data[])
create the structure and populate it with the data from the array
Definition: StaticStack.hpp:35
Abstract stack interface.
Definition: Stack.hpp:16
bool isFull()
Check whether the structure is full.
Definition: StaticStack.hpp:67
std::string getName()
Provides the name of the data structure as a string representation.
Definition: StaticStack.hpp:23
T pop()
Remove an element from the top of the stack.
Definition: StaticStack.hpp:47
StaticStack(int size)
Create a fixed-size stack.
Definition: StaticStack.hpp:27
void push(T val)
Add an element to the top of the stack.
Definition: StaticStack.hpp:41
Stack implementation using a native C++ array as data storage.
Definition: StaticStack.hpp:17
T peek()
See the value from the top of the stack, without removing it.
Definition: StaticStack.hpp:53
bool isEmpty()
Check whether the structure is empty.
Definition: StaticStack.hpp:63