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

本篇完!

相关推荐
阿里加多36 分钟前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood1 小时前
java中`==`和`.equals()`区别
java·开发语言·python
zs宝来了2 小时前
AQS详解
java·开发语言·jvm
telllong2 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
And_Ii2 小时前
LCR 168. 丑数
c++
CoderMeijun3 小时前
C++ 时间处理与格式化输出:从 Linux 时间函数到 Timestamp 封装
c++·printf·stringstream·时间处理·clock_gettime
wjs20244 小时前
JavaScript 条件语句
开发语言
阿里加多4 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
2301_792674865 小时前
java学习day29(juc)
java·开发语言·学习
周末也要写八哥5 小时前
MATLAB R2025a超详细下载与安装教程(附安装包)
开发语言·matlab