I've got a quick and I am assuming question but I have not been able to find anything online.
How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
I've got a quick and I am assuming question but I have not been able to find anything online.
How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
C++03 and C++0x:
#include <numeric>
int count = sizeof(arr)/sizeof(arr[0]);
int sum = std::accumulate<unsigned char*, int>(arr,arr + count,0);
double average = (double)sum/count;
Online Demo : http://www.ideone.com/2YXaT
C++0x Only (using lambda)
#include <algorithm>
int sum = 0;
std::for_each(arr,arr+count,[&](int n){ sum += n; });
double average = (double)sum/count;
Online Demo : http://www.ideone.com/IGfht
Arithmetic operations work just fine on
unsigned char
, although you may occasionally be surprised by the fact that arithmetic in C always promotes toint
.In C++'s Standard Template Library,
To calculate the sum of
unsigned char arr[]
, you may useaccumulate(arr, arr + sizeof(arr) / sizeof(arr[0]), 0)
. (0 is anint
here. You may find it more appropriate to use a different type.)Without STL, this is trivially computed with a loop.
The average is the sum divided by the length (
sizeof(arr) / sizeof(arr[0])
).