I have a function that gets a sample (an std::vector<double>
) as input and computes the average of the sample: what is the best way to handle the empty input vector case?
My first idea is to throw an exception like in this snippet:
double average(const std::vector<double>& sample)
{
size_t sz = sample.size();
if (sz==0) throw std::exception("unexpected empty vector");
double acc = 0;
for (size_t i=0; i<sz; ++i) acc += sample[i];
return acc/sz;
}
But I think another solution could be to return NaN:
double average(const std::vector<double>& sample)
{
size_t sz = sample.size();
if (sz==0) return std::numeric_limits<double>::quiet_NaN();
double acc = 0;
for (size_t i=0; i<sz; ++i) acc += sample[i];
return acc/sz;
}
I like the exception because it shows where the problem happened while if I get a NaN in a final result of a long computation I will have more difficulties to understand where the NaN was born. Anyway with the NaN I like the possibility of returning a "special" double to signal something unexpected happened.
Is there any other way of cope with the empty vector? Thank you.