include cstdlib include iostream include stdexcept include cmath templ

 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
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <cmath>
template<typename T, unsigned int MAX_SIZE>
class Queue {
protected:
T array[MAX_SIZE];
unsigned int size;
unsigned int start;
unsigned int end;
public:
Queue() {
size = 0;
start = 0;
end = 0;
}
void enqueue(T val) {
if (size < MAX_SIZE) {
size++;
end = end < MAX_SIZE ? end + 1 : 0;
array[end] = val;
} else throw std::overflow_error("Queue is full");
}
T dequeue() {
if (size > 0) {
T result = array[start];
size--;
start++;
start = start < MAX_SIZE ? start + 1 : 0;
return result;
} else throw std::underflow_error("Queue is empty");
}
};
int main() {
Queue<int, 1000> q;
try {
for(int i = 0; i < 990; i++) q.enqueue(rand() % 1000);
for(int i = 0; i < 900; i++) q.dequeue();
for(int i = 0; i < 500; i++) q.enqueue(rand() % 1000);
} catch (std::exception &e) {
printf("Exception thrown: %s\n", e.what());
}
return 0;
}