-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleApplication1.cpp
121 lines (100 loc) · 2.33 KB
/
ConsoleApplication1.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 buffer class
// Once buffer is full, elements shift and the new element comes in
// Own iterator nested class
// auto inference example
#include<iostream>
#include<typeinfo>
#include<vector>
using namespace std;
template<class T>
class ring {
int length; // number of elements
int currentElement; // current element position
T* buffer; // ptr to heap memory, to the start of array of T-type elements
bool gotFull; // buffer is full flag
public:
ring(int l = 0) :
length(l){
currentElement = 0; // initialize position to 0
buffer = new T[length]; // allocate needed memory on heap
gotFull = false;
}
void add(T e) {
// if full, do rotation, add @ beginning of buffer
if (currentElement == length || gotFull == true)
{
gotFull = true;
this->shiftElements();
//printBuffer();
currentElement = 0;
}
// add element
buffer[currentElement++] = e;
//printBuffer();
}
void printBuffer() {
for (int i = 0; i < length; i++)
cout << buffer[i] << endl;
}
// shift elements to right
void shiftElements() {
for (int i = length - 2; i >= 0; i--)
{
buffer[i + 1] = buffer[i];
}
}
int size() {
return length;
}
T& get(int i) {
return buffer[i];
}
~ring() {
delete[] buffer;
}
class iterator;
iterator begin() {
return iterator(0, *this);
}
iterator end() {
return iterator(length, *this);
}
};
template<class T>
class ring<T>::iterator {
int pos;
ring& it_r;
public:
iterator(int p, ring& r) :
pos(p), it_r(r){
}
T& operator*() {
return it_r.get(pos);
}
iterator& operator++(int){ // dummy int for postfix operator overloading
pos++;
return *this;
}
iterator& operator++() {
pos++;
return *this;
}
bool operator!=(iterator otherIt) const {
return (pos != otherIt.pos);
}
};
int main() {
ring<string> textring(3);
textring.add(string("one"));
textring.add(string("two"));
textring.add(string("three"));
textring.add(string("four"));
textring.add(string("five"));
for (int i = 0; i < textring.size(); i++)
cout << textring.get(i) << endl;
for (ring<string>::iterator it = textring.begin(); it !=textring.end(); it++)
cout << *it << endl;
for (auto v : textring)
cout << v << endl;
return 0;
}