-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathring_buffer.cpp
More file actions
76 lines (56 loc) · 1.14 KB
/
ring_buffer.cpp
File metadata and controls
76 lines (56 loc) · 1.14 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
using namespace std;
template<class T, size_t SIZE>
class ring_buffer_t
{
T buff[SIZE];
int front;
int back;
int current;
public:
ring_buffer_t()
: front(0), back(0), current(0)
{
memset(buff, 0, SIZE * sizeof(T));
}
void push_back(T value)
{
buff[back] = value;
back = (back + 1) % SIZE;
if (current < SIZE)
{
current++;
}
else
{
/* Overwriting the oldest. Move front to next-oldest */
front = (front + 1) % SIZE;
}
}
T pop_front()
{
if (!current)
throw runtime_error("ERROR: buffer empty!");
T value = buff[front];
front = (front + 1) % SIZE;
current--;
return value;
}
};
//ring buffer of size 3 (will hold 3 latest items)
ring_buffer_t<int, 3> buff;
int main(int argc, char* argv[])
{
buff.push_back(1);
buff.push_back(2);
buff.push_back(3);
buff.push_back(4);
buff.push_back(5);
//Will output 3 latest items (i.e. 3, 4 & 5)
cout << buff.pop_front() << endl;
cout << buff.pop_front() << endl;
cout << buff.pop_front() << endl;
cout << "All done!\n";
cin.get();
return EXIT_SUCCESS;
}