Это не совсем вопрос, который вы задали, но в вашем примере кода есть простая ошибка. Начальное значение в accumulate
является шаблонным, а в вашем коде - целыми. Если вы передадите ему двойное число, оно будет приведено к целым числам, и вы получите неправильные ответы. Сделав эту ошибку раньше, я быстро гарантировал себе следующее:
/** Check that not inputting integer type into accumulate
* This is considered an error in this program (where a double was expected
* @tparam InputIterator The iterator to accumulate
* @tparam T The type to accumulate - will fail if integer.
* @param first The first iterator to accumulate from.
* @param last the iterator to acculate to,
* @param init The initial value
* @return The accumulated value as evaluated by std::accumulate.
*/
template<class InputIterator, class T>
inline
T
accumulate_checked(InputIterator first, InputIterator last, T init )
{
return std::accumulate(first,last, init);
}
//Not implemented for integers (will not compile if called).
template<class InputIterator>
inline
int
accumulate_checked(InputIterator first, InputIterator last, int init );
Думаю, я поделюсь этим, если это будет интересно.
Просто для полноты ваша функция может выглядеть следующим образом:
double mean_array( double *array, size_t count )
{
double sum = std::accumulate(array,array+count,0.0)
return sum / count;
}
или быть очень осторожным
double mean_array( double *array, size_t count )
{
double sum = accumulate_checked(array,array+count,0.0)
return sum / count;
}
или, что еще лучше, шаблонная версия от Didier Trosset