C++11标准模板(STL)- 算法 - 数值运算 (std::accumulate)

定义于头文件 <algorithm>

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

对一个范围内的元素求和

std::accumulate

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 求和元素,均将 std::move 应用到其左侧运算数 (C++20 起)。

op 必须无副效应。

(C++11 前)

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

(C++11 起)

参数

first, last-要求和的元素范围
init-和的初值
op-被使用的二元函数对象。接收当前积累值 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>
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>
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 <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <iterator>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }

    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

int main()
{
    std::mt19937 g{std::random_device{}()};

    srand((unsigned)time(NULL));;

    std::cout << std::boolalpha;

    std::function<Cell()> generate = []()
    {
        int n = std::rand() % 10 + 100;
        Cell cell{n, n};
        return cell;
    };

    // 初始化lCells1
    std::list<vector<Cell>> lCells1(6, vector<Cell>(5));
    //用从起始值开始连续递增的值填充一个范围
    for (vector<Cell> &vCells : lCells1)
    {
        std::generate(vCells.begin(), vCells.end(), generate);
    }

    size_t index = 0;
    for (vector<Cell> &vCells : lCells1)
    {
        std::cout << "lCells " << index << " ";
        std::copy(vCells.begin(), vCells.end(), std::ostream_iterator<Cell>(std::cout, " "));

        //计算给定值 init 与给定范围 [first, last) 中元素的和。第一版本用 operator+
        Cell accumulate = std::accumulate(vCells.begin(), vCells.end(), Cell{0, 0});
        std::cout << "  accumulate: " << accumulate << std::endl;
        index++;
    }

    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << std::endl;


    auto BinaryOperation = [](const Cell & a, const Cell & b)
    {
        Cell cell{a.x + b.x, a.y + b.y};
        return cell;
    };

    // 初始化lCells2
    std::list<vector<Cell>> lCells2(6, vector<Cell>(5));
    //用从起始值开始连续递增的值填充一个范围
    for (vector<Cell> &vCells : lCells2)
    {
        std::generate(vCells.begin(), vCells.end(), generate);
    }

    index = 0;
    for (vector<Cell> &vCells : lCells2)
    {
        std::cout << "lCells " << index << " ";
        std::copy(vCells.begin(), vCells.end(), std::ostream_iterator<Cell>(std::cout, " "));
        Cell cell = generate();
        std::cout << " Tp value: " << cell;

        //计算给定值 init 与给定范围 [first, last) 中元素的和。第二版本用二元函数 op 求和元素
        Cell accumulate = std::accumulate(vCells.begin(), vCells.end(), cell, BinaryOperation);
        std::cout << "  accumulate: " << accumulate << std::endl;
        index++;
    }

    return 0;
}

输出

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值