Skip to content

Circular Buffer

Hawkmask edited this page Sep 11, 2023 · 1 revision

CircularBuffer Class

The CircularBuffer class is a C++ implementation of a circular buffer that can be used to store and compute statistics on a fixed-size collection of double values.

Constructor

CircularBuffer(int size)

  • Initializes a CircularBuffer with the specified size.
  • Initializes all elements to 0.

Parameters:

  • size (int): The size of the circular buffer.

Public Methods

void add(double value)

  • Adds a new value to the circular buffer.
  • If the buffer is full, it overwrites the oldest value.

Parameters:

  • value (double): The value to add to the buffer.

double getAverage()

  • Calculates and returns the average of the values currently in the buffer.

Returns:

  • The average value as a double.

double getStandardDeviation()

  • Calculates and returns the standard deviation of the values currently in the buffer.

Returns:

  • The standard deviation value as a double.

int getSize()

  • Returns the size of the circular buffer.

Returns:

  • The size of the buffer as an integer.

int getNumElements()

  • Returns the number of elements currently in the buffer.

Returns:

  • The number of elements as an integer.

void reset()

  • Resets the circular buffer by clearing all values and setting the number of elements to 0.

Private Members

  • int size: The size of the circular buffer.
  • int numElements: The current number of elements in the buffer.
  • int index: The index for the next insertion.
  • double sum: The sum of all values in the buffer.
  • double sumOfSquares: The sum of squares of all values in the buffer.
  • double *buffer: A dynamically allocated array to store the buffer elements.

Note:

  • The circular buffer overwrites the oldest value when it reaches its maximum size.

Example Usage

// Create a CircularBuffer with a size of 5
CircularBuffer buffer(5);

// Add values to the buffer
buffer.add(10.0);
buffer.add(20.0);
buffer.add(30.0);

// Get statistics
double average = buffer.getAverage();
double stdDeviation = buffer.getStandardDeviation();
int bufferSize = buffer.getSize();
int numElements = buffer.getNumElements();

// Reset the buffer
buffer.reset();