1、C++ STL中std::accumulate()、std::begin()和std::end()
accumulate定义在#include<numeric>中,实现的功能为:(1)用来计算指定范围内的元素之和。(2)指定的二进制操作计算特定范围内的元素结果。分别由两个函数模板实现:
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
各个参数说明:
first 指定范围内第一个迭代的值或者结合操作选项使用。
last 指定范围内最后一个迭代值或者结合操作项使用。
init 要计算的初始值,也就是在累加之前给定的基础值。
binary_op 运用于指定范围内所有元素和前面计算得到结果的参数。
#include <numeric>
#include <iostream>
#include <vector> using namespace std;
int main()
{
vector<int> vec(10,1);
int total = accumulate(vec.begin(),vec.end(),1000);
cout<<"total:"<<total<<endl;
}
total:1010
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;
}
init既是初始值。
模版函数std::begin、std::end,这两个模版函数可以作用于容器和数组,结合for_each()范围循环可以对容器逐个访问。
//容器时使用
template <class Container>
auto begin (Container& cont) -> decltype (cont.begin());
template <class Container>
auto begin (const Container& cont) -> decltype (cont.begin());
//数组时使用
template <class T, size_t N> T* begin (T(&arr)[N]);
例如:
int array[] = {1,2,3,4,5,6};
std::for_each(std::begin<int>(array), std::end<int>(array), [&](int n) {cout << n;}); //1,2,3,4,5,6。
accumulate()结合std::begin()和std::end()使用
以下是摘自网络的一段代码,求vector的均值和方差。
double sum = std::accumulate(std::begin(resultSet), std::end(resultSet), 0.0);
double mean = sum / resultSet.size(); //均值
double accum = 0.0;
std::for_each (std::begin(resultSet), std::end(resultSet), [&](const double d)
{
accum += (d-mean)*(d-mean);
});
double stdev = sqrt(accum/(resultSet.size()-1)); //方差