forked from funkey/util
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathring.hpp
95 lines (67 loc) · 1.61 KB
/
ring.hpp
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
#ifndef RING_H_
#define RING_H_
#include <vector>
#include "circular_iterator.hpp"
namespace util {
/**
* Class ring.
*
* This class realizes a ring buffer of a fixed size. As soon as more elements
* are added to the buffer, the least recent elements are removed.
*/
template<typename T>
class ring {
public:
typedef std::vector<T> container_type;
typedef typename container_type::iterator container_iterator;
typedef circular_iterator<container_type> iterator;
typedef const_circular_iterator<container_type> const_iterator;
ring(int capacity) :
_buffer(capacity+1),
_head(_buffer.begin(),_buffer.end()),
_tail(_buffer.begin(),_buffer.end())
{};
const const_circular_iterator<container_type> begin() const {
return _head;
}
const const_circular_iterator<container_type> end() const {
return _tail;
}
circular_iterator<container_type> begin() {
return _head;
}
circular_iterator<container_type> end() {
return _tail;
}
void push_front(const T& t) {
_head--;
(*_head) = t;
if (_head == _tail)
_tail--;
}
void push_back(const T& t) {
(*_tail) = t;
_tail++;
if (_tail == _head)
_head++;
}
void pop_front() {
if (_head != _tail)
_head++;
}
void pop_back() {
if (_tail != _head)
_tail--;
}
void clear() {
_tail = _head;
}
private:
// the fixed size buffer to store the elements of the ring
container_type _buffer;
// head and tail mark the current beginning and end of the ring
circular_iterator<container_type> _head;
circular_iterator<container_type> _tail;
};
}; // namespace util
#endif // RING_H_