/* This function calculates the average of values in cBuf */ void updateAverage( INTYPE data) { double tempVal = 0; float mulFactor = 0; INTYPE oldElement = 0; if( !stableStream ) { /* Add data to Buffer */ cBuf.push_back(data); mulFactor = 1/(double)(cBuf.size()); /* If number of elements in the buffer < total buffer capacity * Calculate the average using loops */ for(int i = 0; i < (int)cBuf.size(); i++) { tempVal += cBuf[i]; } tempVal = tempVal * mulFactor; currentAverage = tempVal; stableStream = (cBuf.size() == cBuf.capacity()); } else { /* Efficient way of calculating average in case the buffer is full * Every calculation will update the current average value. * To get new average: * new_average = * current_average + * ( new_element - oldest_element ) * mulFactor * * The CircularBuffer at this point is Full * */ oldElement = cBuf.peek_front(); /* Adding new data Element */ cBuf.push_back(data, OVERWRITE_OLD_DATA); /* We now have a pointer to the old element in the buffer */ tempVal = currentAverage; tempVal = tempVal + ( ( data - oldElement ) / ( cBuf.capacity() ) ); currentAverage = tempVal; } }
int main (int argc, const char * argv[]) { //Create a new circular buffer for unsigned integers CircularBuffer< UINT > buffer; //Resize the buffer buffer.resize( 10 ); //Add some values to the buffer so we fill it for(UINT i=0; i<buffer.getSize(); i++){ cout << "Adding " << i << " to buffer\n"; buffer.push_back( i ); //Print the values in the buffer cout << "Values: \t\t"; for(UINT j=0; j<buffer.getSize(); j++){ cout << buffer[j] << "\t"; }cout << endl; //Print the raw values in the buffer cout << "RawValues: \t\t"; for(UINT j=0; j<buffer.getSize(); j++){ cout << buffer(j) << "\t"; }cout << endl; } //Get all the data in the buffer as a vector vector<UINT> data = buffer.getDataAsVector(); cout << "Data: \t\t\t"; for(UINT j=0; j<data.size(); j++){ cout << data[j] << "\t"; } cout << endl; return EXIT_SUCCESS; }