C++中accumulate的用法

std::accumulate

定义于头文件< numeric>

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

计算给定值 init 与给定范围 [first, last) 中元素的和。第一版本用 operator+ ,第二版本用二元函数 op 求和元素,均将 std::move 应用到其左侧运算数 (C++20 起)。

op 必须不非法化涉及范围的任何迭代器,含尾迭代器,且不修改其所涉及范围的任何元素及 *last 。(C++11 起)

参数

first, last - 要求和的元素范围
init - 和的初值
op - 被使用的二元函数对象。接收当前积累值 a (初始化为 init )和当前元素 b 的二元运算符。
该函数的签名应当等价于:

 Ret fun(const Type1 &a, const Type2 &b);
被使用的二元函数对象。接收当前积累值 a (初始化为 init )和当前元素 b 的二元运算符。

该函数的签名应当等价于:

Ret fun(const Type1 &a, const Type2 &b);

签名中并不需要有 const &。
类型 Type1 必须使得 T 类型的对象能隐式转换到 Type1 。类型 Type2 必须使得 InputIt 类型的对象能在解引用后隐式转换到 Type2 。 类型 Ret 必须使得 T 类型对象能被赋 Ret 类型值。 ​

类型要求
InputIt 必须满足遗留输入迭代器 (LegacyInputIterator) 的要求。
T 必须满足可复制赋值 (CopyAssignable) 和 可复制构造 (CopyConstructible) 的要求。

返回值
  1. 给定值与给定范围中的元素的和。
  2. 给定范围在 op 上左折叠的结果
注解

std::accumulate 进行左折叠。为进行右折叠,必须逆转二元运算符的参数顺序,并使用逆序迭代器。

可能的实现

版本一

template<class InputIt, class T>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init)
{
    for (; first != last; ++first) {
        init = std::move(init) + *first; // C++20 起有 std::move
    }
    return init;
}

版本二

template<class InputIt, class T, class BinaryOperation>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init, 
             BinaryOperation op)
{
    for (; first != last; ++first) {
        init = op(std::move(init), *first); // C++20 起有 std::move
    }
    return init;
}
示例
#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>());
 
    auto dash_fold = [](std::string a, int b) {
                         return std::move(a) + '-' + std::to_string(b);
                     };
 
    std::string s = std::accumulate(std::next(v.begin()), v.end(),
                                    std::to_string(v[0]), // 用首元素开始
                                    dash_fold);
 
    // 使用逆向迭代器右折叠
    std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(),
                                     std::to_string(v.back()), // 用首元素开始
                                     dash_fold);
 
    std::cout << "sum: " << sum << '\n'
              << "product: " << product << '\n'
              << "dash-separated string: " << s << '\n'
              << "dash-separated string (right-folded): " << rs << '\n';
}

输出

sum: 55
product: 3628800
dash-separated string: 1-2-3-4-5-6-7-8-9-10
dash-separated string (right-folded): 10-9-8-7-6-5-4-3-2-1
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++,我们可以使用accumulate函数来对容器的元素进行累加或者累乘操作。引用的代码演示了如何使用accumulate函数将字符串连接起来。而引用的代码演示了如何使用accumulate函数计算一个自定义结构体数组某个成员变量的总和。即使不指定第四个参数,accumulate函数也可以默认对范围内的元素进行累加操作。引用给出了accumulate函数的具体使用场景: 1. 计算数组所有元素的和:可以使用accumulate函数对整数数组的所有元素进行累加操作。例如,可以使用accumulate函数计算一个整数向量所有元素的和。引用的代码演示了如何使用accumulate函数计算一个整数向量所有元素的和。 2. 计算数组所有元素的乘积:通过定义一个自定义操作函数,可以使用accumulate函数对整数数组的所有元素进行累乘操作。这个自定义操作函数会将累加的结果与当前元素相乘。例如,可以使用accumulate函数计算一个整数向量所有元素的乘积。 总结起来,C++accumulate函数可以用来对容器的元素进行累加或累乘操作。您可以根据需要定义相应的操作函数,从而满足不同的计算需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C++ accumulate函数介绍、具体案例](https://blog.csdn.net/VariatioZbw/article/details/125257536)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [C++的STLaccumulate用法](https://blog.csdn.net/u011499425/article/details/52756242)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值