首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::accumulate

在标题<numeric>中定义

?

?

template <class InputIt,class T> T accumulate(InputIt first,InputIt last,T init);

(1)

?

template <class InputIt,class T,class BinaryOperation> T accumulate(InputIt first,InputIt last,T init,BinaryOperation op);

(2)

?

计算给定值init和范围中元素的总和[first, last)。第一个版本用于operator+总结元素,第二个版本使用给定的二元函数op

op必须没有副作用。

(直到C ++ 11)

op不得使任何迭代器无效,包括结束迭代器,或修改所涉及范围的任何元素。

(自C ++ 11以来)

参数

第一,最后

-

要求的元素范围

在里面

-

总和的初始值

-

将应用的二进制运算函数对象。二元运算符获取当前累加值a(初始化为init)和当前元素b的值。函数的签名应该等同于以下内容:Ret fun(const Type1&a,const Type2&b); 签名不需要const&。类型Type1必须是类型为T的对象可以隐式转换为Type1。类型Type2必须是可以取消引用InputIt类型的对象,然后隐式转换为Type2。Ret类型必须能够为类型为T的对象分配Ret类型的值。

类型要求

-输入必须符合输入器的要求。

| -T必须满足CopyAssignable和CopyConstructible的要求。|

返回值

1)给定值和给定范围内的元素之和。

2)左侧折叠的结果(http://en.wikipedia.com/wiki/Fold_(gigh-order_function%29)超出给定范围op

注记

虽然std::accumulate默认情况下执行左侧折叠,但可以通过使用反向迭代器来实现右侧折叠,例如std::accumulate(v.rbegin(), v.rend(), init, binop)

可能的实施

第一版

|:----|

| template <class InputIt,class T> T accumulate(InputIt first,InputIt last,T init){for(; first!= last; ++ first){init = init + * first; } return init; } |

第二版

| template <class InputIt,class T,class BinaryOperation> T accumulate(InputIt first,InputIt last,T init,BinaryOperation op){for(; first!= last; ++ first){init = op(init,* first); } return init; } |

二次

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
 
int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    int sum = std::accumulate(v.begin(), v.end(), 0);
 
    int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
 
    std::string s = std::accumulate(std::next(v.begin()), v.end(),
                                    std::to_string(v[0]), // start with first element
                                    [](std::string a, int b) {
                                        return a + '-' + std::to_string(b);
                                    });
 
    std::cout << "sum: " << sum << '\n'
              << "product: " << product << '\n'
              << "dash-separated string: " << s << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
sum: 55
product: 3628800
dash-separated string: 1-2-3-4-5-6-7-8-9-10

二次

另见

adjacent_difference

计算范围内相邻元素之间的差异(函数模板)

inner_product

计算两个元素范围的内积(函数模板)

partial_sum

计算一系列元素的部分和(函数模板)

减少(C ++ 17)

类似于std :: accumulate,除了乱序(函数模板)

代码语言:txt
复制
 ? cppreference.com

根据知识共享署名 - ShareAlike Unported License v3.0获得许可。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com