Data Structures in C++
StaticQueue.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 Queue implementation using a native C++ array as data storage.
5  */
6 
7 #ifndef AULA1_STATICQUEUE_HPP
8 #define AULA1_STATICQUEUE_HPP
9 
10 #include <stdexcept>
11 #include <string>
12 #include "Queue.hpp"
13 
14 //! Queue 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 StaticQueue : public Queue<T> {
18  private:
19  int size, head, tail, count;
20  T *data;
21 
22  public:
23  std::string getName() { return "Static Queue"; }
24 
25  //! Create a fixed-size queue
26  //! \param size the size of the queue
27  explicit StaticQueue(int size) {
28  head = tail = count = 0;
29  this->size = size;
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 StaticQueue(T data[]) {
36  this->data = data;
37 
38  size = count = (sizeof(data) / sizeof(data[0])) + 1;
39  head = 0;
40  tail = (sizeof(data) / sizeof(data[0]));
41  }
42 
43  ~StaticQueue() { delete[] data; }
44 
45  void enqueue(T val) {
46  if (isFull()) {
47  throw std::out_of_range("The queue is full.");
48  }
49 
50  data[tail] = val;
51  count ++;
52  tail = (tail + 1) % size;
53  }
54 
55  T dequeue() {
56  if (isEmpty())
57  throw std::out_of_range("The queue is empty.");
58 
59  T tmp = data[head];
60  count --;
61  head = (head + 1) % size;
62 
63  return tmp;
64  }
65 
66  T peek() {
67  if (isEmpty())
68  throw std::out_of_range("The queue is empty.");
69  return data[head];
70  }
71 
72  int getSize() { return count; }
73 
74  bool isEmpty() { return count == 0; }
75 
76  bool isFull() { return count == size; }
77 };
78 
79 #endif
T peek()
See the first value from the queue, without removing it.
Definition: StaticQueue.hpp:66
StaticQueue(int size)
Create a fixed-size queue.
Definition: StaticQueue.hpp:27
void enqueue(T val)
Add an element to the end of the queue.
Definition: StaticQueue.hpp:45
int getSize()
Outputs the number of elements stored in the structure.
Definition: StaticQueue.hpp:72
bool isEmpty()
Check whether the structure is empty.
Definition: StaticQueue.hpp:74
Abstract queue interface.
Definition: Queue.hpp:16
T dequeue()
Remove an element from the queue.
Definition: StaticQueue.hpp:55
Queue implementation using a native C++ array as data storage.
Definition: StaticQueue.hpp:17
std::string getName()
Provides the name of the data structure as a string representation.
Definition: StaticQueue.hpp:23
bool isFull()
Check whether the structure is full.
Definition: StaticQueue.hpp:76
StaticQueue(T data[])
create the structure and populate it with the data from the array
Definition: StaticQueue.hpp:35