Beware of <numeric> templates!

C++'s <numeric> header provides many templates to process numeric operations. For example, you can use the templates to easily accumulating items in a vector without using good old for loop. However, if you don't craft your code careful enough, you may end with very hard to debug issues.

Consider the following code:

double AddAll(const std::vector<double>& data)
{
  return std::accumulate(data.begin(), data.end(), 0);    
}

It's very clear that the method returns data[0] + data[1] + ... + data[n]. OR, IS IT?

No. This method produces a wrong result, you'll always end with an integer, there won't be any decimal part. The reason of this tricky problem is, the compiler believes we want an integer instead of double! The std::accumulate template uses last argument's type as return type, and here we provided an integer!

So, resolving this issue is simple, simply put 0.0 instead of 0 for the 3rd argument.

Be careful, people!

 

posted @ 2013-11-15 23:26  wane  阅读(132)  评论(0)    收藏  举报