forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular_buffer.cpp
65 lines (57 loc) · 1.18 KB
/
circular_buffer.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
//
// Queue: the entities in the collection are kept in
// order and the principal (or only) operations on the
// collection are the addition of entities to the rear
// terminal position
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/data-scructures/
// https://github.com/allalgorithms/cpp
//
// Contributed by: Carlos Abraham
// Github: @abranhe
//
#include <iostream>
#include <vector>
template <typename T, long SZ>
class circular_buffer
{
private:
T* m_buffer;
long m_index;
public:
circular_buffer()
: m_buffer {new T[SZ]()}
, m_index {0}
{
}
~circular_buffer()
{
delete m_buffer;
}
std::vector<T> get_ordered() noexcept
{
std::vector<T> vec;
for (long i = 0; i < SZ; ++i)
vec.push_back(m_buffer[(i + m_index) % SZ]);
return vec;
}
void push(T x) noexcept
{
m_buffer[m_index] = x;
m_index = (m_index + 1) % SZ;
}
};
int main()
{
circular_buffer<int, 4> buf;
buf.push(1);
buf.push(2);
buf.push(3);
buf.push(4);
buf.push(5);
buf.push(6);
for (auto x : buf.get_ordered())
std::cout << x << std::endl;
}