如何用标准库的方法对一个数组中的元素求和
怎么用标准库的方法对一个数组中的元素求和?
没想到什么好的办法?有人能给个嘛?
使用plus,还是for_each,或者是其它的方法?
------解决方案--------------------
stl的accumulate算法
------解决方案--------------------
std::accumulate
------解决方案--------------------
同上:
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int A[] = {1, 2, 3, 4, 5};
const int N = sizeof(A) / sizeof(int);
cout < < "The sum of all elements in A is "
< < accumulate(A, A + N, 0)
< < endl;
cout < < "The product of all elements in A is "
< < accumulate(A, A + N, 1, multiplies <int> ())
< < endl;
}
/home/pinghc/test> ./a.out
The sum of all elements in A is 15
The product of all elements in A is 120
/home/pinghc/test>
------解决方案--------------------
template <class InputIterator, class _TYPE> inline
_TYPE accumulate(InputIterator first, InputIterator last, _TYPE init)
template <class InputIterator, class _TYPE, class BinaryOperator> inline
_TYPE accumulate(InputIterator first, InputIterator last, _TYPE init,
BinaryOperator binary_op)
注意 : 原型中的类 / 参数名称不匹配头文件中版本。 一些已被修改以提高可读性。
------解决方案--------------------
accumulate( .., .., minus <T> () ); /// -
............ plus <T> () ); /// +
没想到什么好的办法?有人能给个嘛?
使用plus,还是for_each,或者是其它的方法?
------解决方案--------------------
stl的accumulate算法
------解决方案--------------------
std::accumulate
------解决方案--------------------
同上:
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int A[] = {1, 2, 3, 4, 5};
const int N = sizeof(A) / sizeof(int);
cout < < "The sum of all elements in A is "
< < accumulate(A, A + N, 0)
< < endl;
cout < < "The product of all elements in A is "
< < accumulate(A, A + N, 1, multiplies <int> ())
< < endl;
}
/home/pinghc/test> ./a.out
The sum of all elements in A is 15
The product of all elements in A is 120
/home/pinghc/test>
------解决方案--------------------
template <class InputIterator, class _TYPE> inline
_TYPE accumulate(InputIterator first, InputIterator last, _TYPE init)
template <class InputIterator, class _TYPE, class BinaryOperator> inline
_TYPE accumulate(InputIterator first, InputIterator last, _TYPE init,
BinaryOperator binary_op)
注意 : 原型中的类 / 参数名称不匹配头文件中版本。 一些已被修改以提高可读性。
------解决方案--------------------
accumulate( .., .., minus <T> () ); /// -
............ plus <T> () ); /// +