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; 
    }

本篇完!

相关推荐
JQLvopkk13 分钟前
能用C#开发AI
开发语言·人工智能·c#
郝学胜-神的一滴1 小时前
当AI遇见架构:Vibe Coding时代的设计模式复兴
开发语言·数据结构·人工智能·算法·设计模式·架构
阿里嘎多学长6 小时前
2026-02-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管
啊吧怪不啊吧7 小时前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
CeshirenTester8 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例
发现你走远了8 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
游乐码8 小时前
c#类和对象
开发语言·c#
黎雁·泠崖8 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
懒惰成性的9 小时前
12.Java的异常
java·开发语言
-To be number.wan9 小时前
Python数据分析:时间序列数据分析
开发语言·python·数据分析