经典造轮子之accumulate

本文介绍了如何在 C++ 中手动实现类似于标准库中的 accumulate 函数。通过自定义模板函数 my_accumulate,可以对容器中元素进行累加操作。文中提供了完整的代码实现,并通过一个示例展示了其使用方法。

轮子的代码是学习了官网之后写的,只为熟悉。链接如下[accumulate-c++]

实现代码

  • my_accumulate.h
/*************************************************************************
 > File Name: my_accumulate.h
 > Author: kang
 > Mail:likang@tju.edu.cn 
 > Created Time: 2017年01月06日 星期五 10时13分45秒
 ************************************************************************/
#ifndef MY_ACCUMULATE_H
#define MY_ACCUMULATE_H

template<class InputIterator, class T>
T my_accumulate( InputIterator first, InputIterator last, T init )
{
    while( first != last )
    {
        init += *first;
        ++first;
    }
    return init;
}
template<class InputIterator, class T>
T my_accumulate( InputIterator first, InputIterator last, T init, BinaryOperation binary_op )
{
    while( first != last )
    {
        init = binary_op( init, *first );
        ++first;
    }
    return init;
}

#endif
  • 测试代码
/*************************************************************************
 > File Name: main.cpp
 > Author: kang
 > Mail:likang@tju.edu.cn 
 > Created Time: 2017年01月06日 星期五 10时17分05秒
 ************************************************************************/
#include "my_accumulate.h"
#include <vector>
#include <iostream>

int main( void )
{
    const int arr[] = {1,2,3,4,5,6,7,8};
    std::vector<int> v( arr, arr + 8 );

    int res = 0;
    res = my_accumulate( v.begin(), v.end(), res );
    std::cout << "res = " << res << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值