Is there a defined design pattern where if I have a buffer with a maximum count of 5, and all 5 slots are full, and I insert to the buffer, it overwrites the current start position's value with the new value? Then increments the start position.
As an example:
class RollingBuffer {
private:
static const int max = 5;
int count = 0,
start = 0;
float data[max];
public:
void insert(float f) {
data[(start + count) % max] = f;
if (++count > max) {
count = max;
++start %= max;
}
}
float get(int index) {
return data[(start + index) % max];
}
};
Then usage of the buffer would look like this:
int main(int argc, const char* argv[]) {
RollingBuffer& buffer = *new RollingBuffer;
buffer.insert(1.0); // index 0, buffer index 0
cout << buffer.get(0); // prints 1.0 at buffer index 0
buffer.insert(2.0); // index 1, buffer index 1
buffer.insert(3.0); // index 2, buffer index 2
buffer.insert(5.0); // index 3, buffer index 3
buffer.insert(7.0); // index 4, buffer index 4
buffer.insert(11.0); // index 5, buffer index 0
cout << buffer.get(0); // prints 2.0 at buffer index 1 (start = 1)
cout << buffer.get(4); // prints 11.0 at buffer index 0 ((start + index) % max = (1 + 4) % 5 = 0)
}
Aucun commentaire:
Enregistrer un commentaire