C++--accumulate介绍

在C++中,accumulate是一个用于对容器中的元素进行累加操作的函数模板,位于 头文件中。它允许你对容器(如vector或array)中的元素进行累加运算,并返回累加的结果。

源代码展示

cpp 复制代码
template<class InputIterator, class Type>  
Type accumulate(  
InputIterator _First,  //开始迭代器  
InputIterator _Last,   //结束迭代器  
Type _Val              //初始值  
);

源码剖析

cpp 复制代码
template<class InputIterator, class T> 
T accumulate( 
InputIterator first,  
InputIterator last,   
T init ) 
{
    for(;first != last; ++first) 
        init = init + *first; //默认为累加 
    return init; 
}

应用举例

cpp 复制代码
 #include <iostream> 
    #include <vector> 
    #include <numeric> 
    using namespace std; 
    int main() 
    {
        vector<int>v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
        auto sum = accumulate(v.begin(), v.end(), 0);//把v的所有值累加,初始值为0

    
        cout << "累加结果为:"<<sum<<endl; 
    
        return 0; 
    }

本篇完!

相关推荐
Jackson@ML3 分钟前
如何快速高效学习Python?
开发语言·python
西瓜本瓜@2 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
UFIT2 小时前
Python函数与模块笔记
开发语言·python
机智的人猿泰山2 小时前
java kafka
java·开发语言·kafka
Y1nhl2 小时前
搜广推校招面经八十一
开发语言·人工智能·pytorch·深度学习·机器学习·推荐算法·搜索算法
Algorithm15762 小时前
谈谈接口和抽象类有什么区别?
java·开发语言
Starry_hello world2 小时前
C++ 快速幂算法
c++·算法·有问必答
yu4106212 小时前
Rust 语言使用场景分析
开发语言·后端·rust
良艺呐^O^2 小时前
uniapp实现app自动更新
开发语言·javascript·uni-app
264玫瑰资源库4 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏