-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueueNaive.h
120 lines (105 loc) · 2.7 KB
/
QueueNaive.h
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//
// QueueNaive.h
//
// Queue implementation with naive memory management schema
//
// Authors : Gokcehan Kara <[email protected]>
// License : This file is placed in the public domain.
//
#ifndef QUEUE_NAIVE_H
#define QUEUE_NAIVE_H
#include <algorithm>
#include <iostream>
template <typename T>
class QueueNaive {
public:
QueueNaive()
: capacity(1)
, size(0)
, offset(0)
{
data = new T[capacity];
}
~QueueNaive() { delete[] data; }
T& operator[](size_t ind) { return data[ind + offset]; }
float load_factor() { return static_cast<float>(size) / capacity; }
void reserve_back(size_t n)
{
if (n + offset > capacity) {
capacity = n + offset;
T* new_data = new T[capacity];
std::copy(data + offset, data + offset + size, new_data + offset);
delete[] data;
data = new_data;
}
}
void reserve_front(size_t n)
{
if (n > size + offset) {
capacity += n - (size + offset);
offset = n - size;
T* new_data = new T[capacity];
std::copy(data + offset, data + offset + size, new_data + offset);
delete[] data;
data = new_data;
}
}
void push_back(const T& val)
{
if (size + offset >= capacity) {
capacity *= 2;
T* new_data = new T[capacity];
std::copy(data + offset, data + offset + size, new_data + offset);
delete[] data;
data = new_data;
}
data[size + offset] = val;
size++;
}
void pop_back() { size--; }
void push_front(const T& val)
{
if (offset > 0) {
size++;
offset--;
data[offset] = val;
} else {
if (size >= capacity) {
capacity *= 2;
T* new_data = new T[capacity];
std::copy(data, data + size, new_data + 1);
delete[] data;
data = new_data;
} else {
std::move_backward(data, data + size, data + size + 1);
}
data[0] = val;
size++;
}
}
void pop_front()
{
size--;
offset++;
}
void draw()
{
std::cout << "|";
for (size_t i = 0; i < capacity; ++i) {
if (i < offset) {
std::cout << " |";
} else if (i < size + offset) {
std::cout << "x|";
} else {
std::cout << " |";
}
}
std::cout << std::endl;
}
private:
T* data;
size_t capacity;
size_t size;
size_t offset;
};
#endif // QUEUE_NAIVE_H