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.
I DO think that mathematically the NaN
would be more correct. In the end it's 0.0/0
. Had it been a direct division, what would have happened?
Be aware that about C++ and exceptions there are holy wars. For example read this: To throw or not to throw exceptions?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With