本文主要是介绍vector所有元素相加求和_利用accumulate函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自己使用时的两行代码
#include<numeric> //使用accumulate函数要包含这个头文件vector<float> result = {1.2, 2.3, 3.4};
float scoreSum = accumulate(result.begin(), result.end(), 0.0);
然后看一下http://www.cplusplus.com/reference/上面关于accumulate的介绍
函数原型:
sum (1)
template <class InputIterator, class T>T accumulate (InputIterator first, InputIterator last, T init);
custom (2)
template <class InputIterator, class T, class BinaryOperation>T accumulate (InputIterator first, InputIterator last, T init,BinaryOperation binary_op);
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;
}
示例:
// accumulate example
#include <iostream> // std::cout
#include <functional> // std::minus
#include <numeric> // std::accumulateint myfunction (int x, int y) {return x+2*y;}
struct myclass {int operator()(int x, int y) {return x+3*y;}
} myobject;int main () {int init = 100;int numbers[] = {10,20,30};std::cout << "using default accumulate: ";std::cout << std::accumulate(numbers,numbers+3,init);std::cout << '\n';std::cout << "using functional's minus: ";std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());std::cout << '\n';std::cout << "using custom function: ";std::cout << std::accumulate (numbers, numbers+3, init, myfunction);std::cout << '\n';std::cout << "using custom object: ";std::cout << std::accumulate (numbers, numbers+3, init, myobject);std::cout << '\n';return 0;
}
输出结果:
using default accumulate: 160
using functional's minus: 40
using custom function: 220
using custom object: 280
这篇关于vector所有元素相加求和_利用accumulate函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!