-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueOnArray.h
More file actions
60 lines (50 loc) · 1.1 KB
/
QueueOnArray.h
File metadata and controls
60 lines (50 loc) · 1.1 KB
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
#pragma once
#include <stdexcept>
#include <algorithm>
constexpr int MinusOne = -1;
template <class T, size_t capacity>
class QueueOnArray {
private:
int first = MinusOne;
int last = MinusOne;
size_t size = 0;
T* data = new T[capacity];
public:
~QueueOnArray() {
delete[] data;
}
void push(const T& value) { // Pushes the given element value to the end of the queue
if (full()) throw std::overflow_error("queue is full");
if (empty() && first == last) {
last = 0; first = 0;
data[0] = value;
}
else {
int index = ++last % int(capacity);
data[index] = value;
}
++size;
}
T pop() { // Removes an element from the front of the queue.
if (empty()) throw std::underflow_error("queue is empty");
T poped = data[first % int(capacity)];
--size;
if (!empty()) ++first;
return poped;
}
bool empty() const {
return size == 0;
}
bool full() const {
return size == capacity;
}
T front() const {
return data[first];
}
size_t get_size() const {
return size;
}
size_t get_capacity() const {
return capacity;
}
};