Backto C/C++ Index
顾名思义, numeric
是一个用于数值计算的小库.
Generalized numeric operations
This header describes a set of algorithms to perform certain operations on sequences of numeric values. Due to their flexibility, they can also be adapted for other kinds of sequences.
比较常用的就一个累加函数 accumulate
, 定义和实现如下
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}
场景, 计算平均值
#include <numeric>
...
std::vector<float> scores(3);
scores.push_back(1.2);
scores.push_back(2.8);
scores.push_back(3.5);
float mean = std::accumulate(scores.begin(), scores.end(), 0.0) / scores.size