blob: e47460abf6297c78ac68e1ac0d9024e7f46717f0 (
plain) (
blame)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
#pragma once
#include <iostream>
template <typename T>
class Queue
{
T* data;
size_t capacity;
size_t count;
size_t head; //where to get
size_t tail; //last added element;
void resize(size_t newCapacity);
void copyFrom(const Queue<T>& other);
void free();
public:
Queue();
Queue(const Queue<T>& other);
Queue<T>& operator=(const Queue<T>& other);
void enqueue(const T& obj);
T dequeue();
size_t getCount();
size_t isEmpty();
~Queue();
};
template <typename T>
Queue<T>::Queue()
{
capacity = 4;
data = new T[capacity];
count = 0;
head = tail = 0;
}
template <typename T>
void Queue<T>::enqueue(const T& obj)
{
if (count == capacity)
resize(capacity * 2);
if (count != 0)
tail++;
tail %= capacity; //so we don't get an out of range exception
data[tail] = obj;
count++;
}
template <typename T>
T Queue<T>::dequeue()
{
if (count == 0)
throw std::exception("The collection is empty!");
T toReturn = data[head];
(++head) %= capacity;
count--;
return toReturn;
}
template <typename T>
size_t Queue<T>::getCount()
{
return count;
}
template <typename T>
size_t Queue<T>::isEmpty()
{
return getCount() == 0;
}
template <typename T>
void Queue<T>::resize(size_t newCapacity)
{
T* newData = new T[newCapacity];
for (int i = 0, ind = head; i < count; i++, (++ind) %= capacity)
newData[i] = data[ind];
delete[] data;
capacity = newCapacity;
data = newData;
head = 0;
tail = count - 1;
}
template <typename T>
void Queue<T>::copyFrom(const Queue<T>& other)
{
data = new T[other.capacity];
for (int i = 0; i < other.capacity; i++)
data[i] = other.data[i];
head = other.head;
tail = other.tail;
count = other.count;
capacity = other.capacity;
}
template <typename T>
void Queue<T>::free()
{
delete[] data;
}
template <typename T>
Queue<T>::Queue(const Queue<T>& other)
{
copyFrom(other);
}
template <typename T>
Queue<T>& Queue<T>::operator=(const Queue<T>& other)
{
if (this != &other)
{
free();
copyFrom(other);
}
return *this;
}
template <typename T>
Queue<T>::~Queue()
{
free();
}
|