-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRingBuffer.cpp
121 lines (97 loc) · 1.77 KB
/
RingBuffer.cpp
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
121
/*
* ring.h
*
* Created on: Jun 23, 2016
* Author: johnpurcell
*/
#ifndef RING_H_
#define RING_H_
#include <iostream>
using namespace std;
template <class T>
class ring
{
private:
int m_pos;
int m_size;
T *m_values;
public:
class iterator;
public:
ring(int size) : m_pos(0), m_size(size), m_values(nullptr)
{
m_values = new T[size];
}
~ring()
{
delete[] m_values;
}
int size()
{
return m_size;
}
iterator begin()
{
return iterator(0, *this);
}
iterator end()
{
return iterator(m_size, *this);
}
void add(T value)
{
m_values[m_pos++] = value;
if (m_pos == m_size)
{
m_pos = 0;
}
}
T &get(int pos)
{
return m_values[pos];
}
};
template <class T>
class ring<T>::iterator
{
private:
int m_pos;
ring &m_ring;
public:
iterator(int pos, ring &ring_ref) : m_pos(pos), m_ring(ring_ref)
{
}
// Post fix
/*
* This differs from what's in at least the original
* version of the tutorial video. Really we should
* return a version of the iterator as it was
* before it was modified, for consistency with
* the usual behaviour of the postfix operator.
*/
iterator operator++(int)
{
iterator old = *this;
++(*this);
return old;
}
// prefix
iterator &operator++()
{
++m_pos;
return *this;
}
T &operator*()
{
return m_ring.get(m_pos);
}
bool operator==(const iterator &other) const
{
return m_pos == other.m_pos;
}
bool operator!=(const iterator &other) const
{
return !(*this == other);
}
};
#endif /* RING_H_ */