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

本篇完!

相关推荐
LilySesy1 分钟前
【与AI+】英语day1——ABAP基础与数据类型
开发语言·ai·sap·abap
你不是我我5 分钟前
【Java 开发日记】我们来说一下 b+ 树与 b 树的区别
java·开发语言
2501_9249526911 分钟前
C++中的过滤器模式
开发语言·c++·算法
左左右右左右摇晃11 分钟前
Java笔记——IO
java·开发语言·笔记
zhixingheyi_tian13 分钟前
gdb 之 attach
c++
2401_8732046513 分钟前
C++中的组合模式实战
开发语言·c++·算法
twc82913 分钟前
Query 改写 大模型测试的数据倍增器
开发语言·人工智能·python·rag·大模型测试
Byron__16 分钟前
HashSet/LinkedHashSet/TreeSet 原理深度解析
java·开发语言
CQU_JIAKE18 分钟前
3.23[Q]s
开发语言·windows·python
2401_8318249618 分钟前
高性能压缩库实现
开发语言·c++·算法