R
Raider
I'm trying to get average value. My first attempt is:
#include <...>
template <typename T>
struct avg : public unary_function<T, void>
{
T sum, count;
avg() : sum(0), count(0) {}
void operator()(T value) { sum+=value; ++count; }
T result() { return sum / count; }
};
int main()
{
const int N = 4;
double arr[N] = { 1, 2, 3, 4 };
avg<double> res = std::for_each(arr, arr+N, avg<double>());
std::cout << "avg=" << res.result() << std::endl;
}
Questions are:
1. Is for_each a right way? May be I should use accumulate or
something?
2. ": public unary_function<T, void>" is not nessesary. Should I use it
anyway?
Raider
#include <...>
template <typename T>
struct avg : public unary_function<T, void>
{
T sum, count;
avg() : sum(0), count(0) {}
void operator()(T value) { sum+=value; ++count; }
T result() { return sum / count; }
};
int main()
{
const int N = 4;
double arr[N] = { 1, 2, 3, 4 };
avg<double> res = std::for_each(arr, arr+N, avg<double>());
std::cout << "avg=" << res.result() << std::endl;
}
Questions are:
1. Is for_each a right way? May be I should use accumulate or
something?
2. ": public unary_function<T, void>" is not nessesary. Should I use it
anyway?
Raider