-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.cpp
129 lines (108 loc) · 1.9 KB
/
Queue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#pragma once
#ifndef _QUEUE_
#define _QUEUE_
#include <iostream>
#include <exception>
using namespace std;
template <typename T>
class Queue
{
public:
Queue();
Queue(const size_t);
~Queue();
bool add(T);
T peek();
T poll();
bool isEmpty();
bool remove(size_t);
size_t getSize();
private:
T* queue;
size_t length;
size_t capacity;
void grow(size_t);
};
template <typename T>
Queue<T>::Queue()
{
queue = nullptr;
length = 0;
capacity = 0;
}
template <typename T>
Queue<T>::Queue(const size_t allocateCapacity)
{
queue = new T[allocateCapacity];
capacity = allocateCapacity;
length = 0;
}
template <typename T>
Queue<T>::~Queue()
{
if (queue != nullptr)
delete queue;
}
template <typename T>
bool Queue<T>::add(T object)
{
try
{
if (length >= capacity)
this->grow(capacity + 1);
queue[length] = object;
length++;
return true;
}
catch (exception& e)
{
cerr << e.what() << " in add method parametr: add = " << object << endl;
return false;
}
}
template <typename T>
void Queue<T>::grow(size_t minCapacity)
{
try
{
size_t newCapacity = minCapacity < 64 ? minCapacity + 2 : minCapacity * 2;
T* newQueue = new T[newCapacity];
for (size_t i = 0; i < minCapacity - 1; ++i)
{
newQueue[i] = queue[i];
}
delete queue;
capacity = newCapacity;
queue = newQueue;
}
catch (exception& e)
{
cerr << e.what() << " in grow method\n";
}
}
template <typename T>
size_t Queue<T>::getSize()
{
return length;
}
template <typename T>
bool Queue<T>::isEmpty()
{
return (length == 0) ? true : false;
}
template <typename T>
T Queue<T>::peek()
{
return queue[0];
}
template <typename T>
T Queue<T>::poll()
{
T dataToReturn = queue[0];
for (size_t i = 0; i < length - 1; ++i)
{
queue[i] = queue[i + 1];
}
return dataToReturn;
}
#endif _QUEUE_