ok... you can do that by either:
* counting those not _missed (and thus iterating twice over your vector)
* or, by using a function object that counts both values and missed
(* or you could use globals, which is very bad imho)
try to replace your function by
class MeanAccumulator
{
int counted_;
double sum_;
public:
MeanAccumulator() : counted_(0), sum_(0) {}
void operator() (const Value &right)
{
if ( right.getMissed() ) return;
++counted_;
sum_ += right._value;
}
double mean() const {return counted_ ? sum_/counted_ : 0; }
};
void computeMean() {
MeanAccumulator res = std::for_each( _values.begin(), _values.end(),
MeanAccumulator());
std::cerr << "sum="<<res.mean()<<std::endl;
}
class MeanAccumulator
{
int counted_;
double sum_;
public:
MeanAccumulator() : counted_(0), sum_(0) {}
void operator() (const Value &right)
{
if ( right.getMissed() ) return;
++counted_;
sum_ += right._value;
}
double mean() const {return counted_ ? sum_/counted_ : 0; }
};
void computeMean() {
MeanAccumulator res = std::for_each( _values.begin(), _values.end(),
MeanAccumulator());
std::cerr << "sum="<<res.mean()<<std::endl;
}
To copy to clipboard, switch view to plain text mode
Note that the function object passed into for_each does NOT get modified.
The resulting function object (with the updated state) is returned by for_each.
(I assumed you do not insist on using accumulate.)
HTH
Bookmarks