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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#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:
inline unsigned int iterate(unsigned int index) {
return index < (MAX_SIZE - 1) ? ++index : 0;
}
void enqueue(T val) {
if (size < MAX_SIZE) {
if (size > 0) end = iterate(end);
size++;
array[end] = val;
} else throw std::overflow_error("Queue is full");
}
T dequeue() {
if (size > 0) {
T result = array[start];
size--;
start = iterate(start);
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;
}
void sort(bool (*comp_func)(T, T)) {
for(int i = 0; i < size; i++) {
for(int j = start; j <= (end - 1); j = iterate(j) ) {
unsigned int k = iterate(j);
if(comp_func(array[j], array[k])) {
T temp = array[j];
array[j] = array[k];
array[k] = temp;
}
}
}
}
Queue() {
clear();
}
};
bool compare_ints(int a, int b) {
return a < b;
}
int main() {
Queue<int, 1000> q;
int i;
try {
q.enqueue(123);
q.enqueue(456);
q.enqueue(789);
q.sort(&compare_ints);
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;
}