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
|
namespace CLRS
{
template <typename T, std::size_t n>
class Queue;
template <typename T, std::size_t n>
void enqueue(Queue<T, n> &, T);
template <typename T, std::size_t n>
T dequeue(Queue<T, n> &);
template <typename T, std::size_t n>
class Queue
{
friend void enqueue<T, n> (Queue<T, n> &, T);
friend T dequeue<T, n> (Queue<T, n> &);
T queue_array[n];
std::size_t head = 0;
std::size_t tail = 0;
public:
T &operator[](std::size_t i) {return queue_array[i];}
};
template <typename T, std::size_t n>
void enqueue(Queue<T, n> &q, T x)
{
if((q.tail + 1 == q.head) || (q.tail + 1 - n == q.head))
throw std::overflow_error("Queue is overflow");
q[q.tail] = x;
if(q.tail == n - 1)
q.tail = 0;
else
++q.tail;
}
template <typename T, std::size_t n>
T dequeue(Queue<T, n> &q)
{
if(q.tail == q.head)
throw std::underflow_error("Queue is underflow");
T x = q[q.head];
if(q.head == n - 1)
q.head = 0;
else
++q.head;
return x;
}
}
|