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

本篇完!

相关推荐
渡我白衣4 分钟前
计算机组成原理(5):计算机的性能指标
服务器·网络·c++·人工智能·网络协议·tcp/ip·网络安全
初願致夕霞4 分钟前
C++文件压缩及解压缩小程序的实现
c++·小程序·apache
IMPYLH4 分钟前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
郝学胜-神的一滴6 分钟前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程
草莓熊Lotso7 分钟前
Python 基础语法完全指南:变量、类型、运算符与输入输出(零基础入门)
运维·开发语言·人工智能·经验分享·笔记·python·其他
WordPress学习笔记16 分钟前
什么是functions.php文件?
开发语言·php·wordpress
ULTRA??20 分钟前
判断水仙花数并输出,c++
c++·算法
_Voosk20 分钟前
写了个开头的 C++ Tutorial
开发语言·c++
lingggggaaaa24 分钟前
C2远控篇&C&C++&SC转换格式&UUID标识&MAC物理&IPv4地址&减少熵值
c语言·c++·学习·安全·web安全·网络安全·免杀对抗