include cstdlib include iostream include stdexcept include cmath inclu

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